diff --git a/REFACTOR_PLAN.md b/REFACTOR_PLAN.md index 61158b167..615873127 100644 --- a/REFACTOR_PLAN.md +++ b/REFACTOR_PLAN.md @@ -5,7 +5,7 @@ The current codebase has tightly coupled dependencies (config, apiClient, MCP service, model, etc.) that require full reloads when any component changes. This causes: 1. **Slow startup**: TUI can't start until all components are loaded -2. **Poor UX**: Slash commands like `/org`, `/config` trigger complete restarts +2. **Poor UX**: Slash commands like `/config` trigger complete restarts 3. **Tight coupling**: Can't change individual components without reloading everything 4. **Blocking initialization**: All dependencies must load before anything works @@ -99,7 +99,7 @@ Make slash commands reactive by updating services instead of triggering reloads. - [x] Update `src/slashCommands.ts` - Remove `onReload` callback pattern - [x] Update `/login` command to use AuthService.login() - [x] Update `/logout` command to use AuthService.logout() -- [x] Add `/org` command to use AuthService.switchOrg() +- [x] ~~Add `/org` command to use AuthService.switchOrg()~~ **Merged into `/config` command** - [x] Update `/config` command (handled via ConfigSelector UI) #### 3.2 Remove Reload Mechanisms @@ -178,7 +178,7 @@ Enhance the user experience with better loading states and error recovery. - [x] Slash commands work without full reloads - [x] `/login` and `/logout` commands update UI instantly -- [x] New `/org` command for organization switching +- [x] ~~New `/org` command for organization switching~~ **Merged into `/config` command** - [x] No more blocking reinitialization ### Phase 4 Success @@ -193,7 +193,7 @@ Enhance the user experience with better loading states and error recovery. 1. **Fast Startup**: TUI starts immediately, shows progressive loading 2. **Reactive Updates**: Services auto-propagate changes without reloads -3. **Better UX**: `/login`, `/logout`, `/org` commands work instantly +3. **Better UX**: `/login`, `/logout`, `/config` commands work instantly 4. **Cleaner Architecture**: Clear separation of concerns between services 5. **Type Safety**: Full TypeScript support with proper service typing diff --git a/src/commands/commands.integration.test.ts b/src/commands/commands.integration.test.ts index 7b684f29d..cd3a413b5 100644 --- a/src/commands/commands.integration.test.ts +++ b/src/commands/commands.integration.test.ts @@ -24,7 +24,7 @@ describe('Slash Commands Integration', () => { expect(commandNames).toContain('login'); expect(commandNames).toContain('logout'); expect(commandNames).toContain('whoami'); - expect(commandNames).toContain('org'); + expect(commandNames).toContain('model'); expect(commandNames).toContain('config'); }); @@ -39,7 +39,7 @@ describe('Slash Commands Integration', () => { it('should categorize system commands correctly', () => { const commands = getAllSlashCommands(mockAssistant); const systemCommands = commands.filter(cmd => - ['help', 'clear', 'exit', 'login', 'logout', 'whoami', 'org', 'model', 'config'].includes(cmd.name) + ['help', 'clear', 'exit', 'login', 'logout', 'whoami', 'model', 'config'].includes(cmd.name) ); systemCommands.forEach(cmd => { diff --git a/src/commands/commands.ts b/src/commands/commands.ts index 0f34bcf9c..a86d93899 100644 --- a/src/commands/commands.ts +++ b/src/commands/commands.ts @@ -52,7 +52,7 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ }, { name: "config", - description: "Switch configuration", + description: "Switch configuration or organization", category: "system", }, { @@ -60,11 +60,7 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ description: "Manage MCP server connections", category: "system", }, - { - name: "org", - description: "Switch organization", - category: "system", - }, + { name: "compact", description: "Summarize chat history into a compact form", diff --git a/src/slashCommands.test.ts b/src/slashCommands.test.ts index 619239860..4b4503f0c 100644 --- a/src/slashCommands.test.ts +++ b/src/slashCommands.test.ts @@ -73,55 +73,7 @@ describe("handleSlashCommands", () => { expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.CONFIG); }); - test.skip("org switch command should trigger automatic cascade reload via auth service", async () => { - const newOrgState: AuthServiceState = { - authConfig: { userEmail: "test@example.com" } as any, - isAuthenticated: true, - organizationId: "new-org", - }; - (services.auth.switchOrganization as any).mockResolvedValue(newOrgState); - (reloadService as any).mockResolvedValue(undefined); - const result = await handleSlashCommands("/org test-org", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.output).toContain( - "Switched to organization: test-org. All services updated automatically." - ); - - // Verify organization switch was called - expect(services.auth.switchOrganization).toHaveBeenCalledWith("test-org"); - - // Verify automatic cascade reload was triggered - only auth service reload needed - expect(reloadService).toHaveBeenCalledTimes(1); - expect(reloadService).toHaveBeenCalledWith(SERVICE_NAMES.AUTH); - - // Verify manual service reloads are NOT called - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.CONFIG); - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.MODEL); - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.MCP); - }); - - test.skip("org list command should not trigger any reloads", async () => { - const mockOrgs = [ - { id: "org1", name: "Organization 1" }, - { id: "org2", name: "Organization 2" }, - ]; - - (services.auth.getAvailableOrganizations as any).mockResolvedValue( - mockOrgs - ); - - const result = await handleSlashCommands("/org list", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.output).toContain("Available organizations:"); - expect(result?.output).toContain("org1: Organization 1"); - expect(result?.output).toContain("org2: Organization 2"); - - // Verify NO reload was triggered - expect(reloadService).not.toHaveBeenCalled(); - }); test.skip("login failure should not trigger any reloads", async () => { const loginError = new Error("Login failed"); @@ -136,23 +88,7 @@ describe("handleSlashCommands", () => { expect(reloadService).not.toHaveBeenCalled(); }); - test.skip("org switch failure should not trigger any reloads", async () => { - const switchError = new Error("Organization switch failed"); - (services.auth.switchOrganization as any).mockRejectedValue(switchError); - const result = await handleSlashCommands( - "/org invalid-org", - mockAssistant - ); - - expect(result).not.toBeNull(); - expect(result?.output).toContain( - "Failed to switch organization: Organization switch failed" - ); - - // Verify NO reload was triggered on failure - expect(reloadService).not.toHaveBeenCalled(); - }); }); describe("Other Commands (unchanged behavior)", () => { @@ -205,5 +141,12 @@ describe("handleSlashCommands", () => { expect(result).not.toBeNull(); expect(result?.output).toBe("Unknown command: unknown"); }); + + test("/org command should no longer exist (now merged into /config)", async () => { + const result = await handleSlashCommands("/org list", mockAssistant); + + expect(result).not.toBeNull(); + expect(result?.output).toBe("Unknown command: org"); + }); }); }); diff --git a/src/slashCommands.ts b/src/slashCommands.ts index a865c8e9c..76dc76f1a 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -11,58 +11,6 @@ import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; import { posthogService } from "./telemetry/posthogService.js"; import { SlashCommandResult } from "./ui/hooks/useChat.types.js"; -// Helper function to handle org list command -async function handleOrgList(services: any): Promise { - try { - const orgs = await services.auth.getAvailableOrganizations(); - if (!orgs || orgs.length === 0) { - return { - exit: false, - output: "No organizations available or using environment auth", - }; - } - - const orgList = orgs - .map((org: any) => ` ${org.id}: ${org.name}`) - .join("\n"); - return { - exit: false, - output: `Available organizations:\n${orgList}`, - }; - } catch (error: any) { - return { - exit: false, - output: `Failed to list organizations: ${error.message}`, - }; - } -} - -// Helper function to handle org switch command -async function handleOrgSwitch( - orgId: string, - services: any, - reloadService: any, - SERVICE_NAMES: any, -): Promise { - try { - await services.auth.switchOrganization(orgId); - - // Automatically cascade reload from auth service - this will reload - // API_CLIENT -> CONFIG -> MODEL/MCP in the correct dependency order - await reloadService(SERVICE_NAMES.AUTH); - - return { - exit: false, - output: `Switched to organization: ${orgId}. All services updated automatically.`, - }; - } catch (error: any) { - return { - exit: false, - output: `Failed to switch organization: ${error.message}`, - }; - } -} - type CommandHandler = ( args: string[], assistant: AssistantConfig, @@ -148,29 +96,6 @@ function handleWhoami() { } } -async function handleOrg(args: string[]) { - posthogService.capture("useSlashCommand", { name: "org" }); - - if (args.length === 0) { - return { - exit: false, - output: "Usage: /org or /org list", - }; - } - - const subCommand = args[0]; - if (subCommand === "list") { - return await handleOrgList(services); - } else { - return await handleOrgSwitch( - subCommand, - services, - reloadService, - SERVICE_NAMES, - ); - } -} - const commandHandlers: Record = { help: handleHelp, clear: () => { @@ -197,7 +122,6 @@ const commandHandlers: Record = { posthogService.capture("useSlashCommand", { name: "mcp" }); return { openMcpSelector: true }; }, - org: handleOrg, }; export async function handleSlashCommands( diff --git a/src/ui/ConfigSelector.tsx b/src/ui/ConfigSelector.tsx index 11be7c60c..652671c53 100644 --- a/src/ui/ConfigSelector.tsx +++ b/src/ui/ConfigSelector.tsx @@ -8,6 +8,7 @@ import { getOrganizationId, loadAuthConfig, getAssistantSlug, + listUserOrganizations, } from "../auth/workos.js"; import { getApiClient } from "../config.js"; import { env } from "../env.js"; @@ -17,6 +18,7 @@ import { Selector, SelectorOption } from "./Selector.js"; interface ConfigOption extends SelectorOption { type: "local" | "assistant" | "create"; slug?: string; + organizationId?: string | null; // null for personal, string for org } interface ConfigSelectorProps { @@ -41,7 +43,7 @@ const ConfigSelector: React.FC = ({ try { const authConfig = loadAuthConfig(); const accessToken = getAccessToken(authConfig); - const organizationId = getOrganizationId(authConfig); + const currentOrganizationId = getOrganizationId(authConfig); const options: ConfigOption[] = []; let currentId: string | null = null; @@ -50,34 +52,58 @@ const ConfigSelector: React.FC = ({ if (fs.existsSync(CONFIG_PATH)) { options.push({ id: "local", - name: "Local config.yaml", + name: "[Personal] Local config.yaml", type: "local", - displaySuffix: " (local)", + organizationId: null, }); } - // Add assistants from current organization if authenticated + // Add assistants from all organizations if authenticated if (accessToken) { const apiClient = getApiClient(accessToken); try { - const assistants = await apiClient.listAssistants({ - alwaysUseProxy: "false", - organizationId: organizationId ?? undefined, + // Get all organizations + const organizations = await listUserOrganizations(); + const allOrgs = [ + { id: null, name: "Personal" }, // Personal organization + ...(organizations || []), + ]; + + // Fetch assistants for each organization + const assistantPromises = allOrgs.map(async (org) => { + try { + const assistants = await apiClient.listAssistants({ + alwaysUseProxy: "false", + organizationId: org.id ?? undefined, + }); + + return assistants.map((assistant) => { + const displayName = `[${org.name}] ${assistant.ownerSlug}/${assistant.packageSlug}`; + // Create unique ID that includes org info to avoid conflicts + const uniqueId = `${org.id || "personal"}-${assistant.packageSlug}`; + return { + id: uniqueId, + name: displayName, + type: "assistant" as const, + slug: `${assistant.ownerSlug}/${assistant.packageSlug}`, + organizationId: org.id, + }; + }); + } catch (err) { + console.error( + `Failed to load assistants for org ${org.name}:`, + err, + ); + return []; + } }); - for (const assistant of assistants) { - // Use full ownerSlug/packageSlug as the slug and create a display name from ownerSlug/packageSlug - const displayName = `${assistant.ownerSlug}/${assistant.packageSlug}`; - options.push({ - id: assistant.packageSlug, - name: displayName, - type: "assistant", - slug: `${assistant.ownerSlug}/${assistant.packageSlug}`, - }); - } + const assistantResults = await Promise.all(assistantPromises); + const allAssistants = assistantResults.flat(); + options.push(...allAssistants); } catch (err) { - console.error("Failed to load assistants:", err); + console.error("Failed to load organizations or assistants:", err); } } @@ -92,8 +118,14 @@ const ConfigSelector: React.FC = ({ // Determine current config by checking auth config const assistantSlug = getAssistantSlug(authConfig); if (assistantSlug) { - // Extract packageSlug from the full slug for matching - currentId = assistantSlug.split("/")[1]; + // Find the matching config by slug and organization + const matchingConfig = options.find( + (opt) => + opt.type === "assistant" && + opt.slug === assistantSlug && + opt.organizationId === currentOrganizationId, + ); + currentId = matchingConfig?.id || null; } else if (fs.existsSync(CONFIG_PATH)) { // No assistant slug means local config is current currentId = "local"; diff --git a/src/ui/FreeTrialTransitionUI.tsx b/src/ui/FreeTrialTransitionUI.tsx index aac552274..7781d52e0 100644 --- a/src/ui/FreeTrialTransitionUI.tsx +++ b/src/ui/FreeTrialTransitionUI.tsx @@ -186,8 +186,8 @@ const FreeTrialTransitionUI: React.FC = ({ // Option 3: Switch to different configuration navigateTo("config"); } else if (selectedOption === 4 && hasOrganizations) { - // Option 4: Switch to organization - navigateTo("organization"); + // Option 4: Switch to configuration (includes organization switching) + navigateTo("config"); } }; @@ -242,7 +242,7 @@ const FreeTrialTransitionUI: React.FC = ({ {hasOrganizations && ( {selectedOption === 4 ? "▶ " : " "}4. 🏢 Switch to organization - profile + configuration )} diff --git a/src/ui/OrganizationSelector.tsx b/src/ui/OrganizationSelector.tsx deleted file mode 100644 index dfa535090..000000000 --- a/src/ui/OrganizationSelector.tsx +++ /dev/null @@ -1,85 +0,0 @@ -import React, { useEffect, useState } from "react"; - -import { - getOrganizationId, - listUserOrganizations, - loadAuthConfig, -} from "../auth/workos.js"; - -import { Selector, SelectorOption } from "./Selector.js"; - -interface Organization extends SelectorOption {} - -interface OrganizationSelectorProps { - onSelect: (organizationId: string | null, organizationName: string) => void; - onCancel: () => void; -} - -const OrganizationSelector: React.FC = ({ - onSelect, - onCancel, -}) => { - const [allOptions, setAllOptions] = useState([]); - const [selectedIndex, setSelectedIndex] = useState(0); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - const [currentOrgId, setCurrentOrgId] = useState(); - - useEffect(() => { - const loadOrganizations = async () => { - try { - const authConfig = loadAuthConfig(); - setCurrentOrgId(getOrganizationId(authConfig)); - - const organizations = await listUserOrganizations(); - if (organizations === null) { - setError("Failed to load organizations"); - setLoading(false); - return; - } - - const options: Organization[] = [ - { - id: "personal", - name: "Personal", - slug: "personal", - }, - ...organizations, - ]; - - setAllOptions(options); - setLoading(false); - } catch (err: any) { - setError(err.message || "Failed to load organizations"); - setLoading(false); - } - }; - - loadOrganizations(); - }, []); - - const handleSelect = (option: Organization) => { - if (option.id === "personal") { - onSelect(null, "Personal"); - } else { - onSelect(option.id, option.name); - } - }; - - return ( - - ); -}; - -export { OrganizationSelector }; diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index c8c4e0f29..0d99c29fe 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -124,7 +124,6 @@ const TUIChat: React.FC = ({ initialPrompt, resume, additionalRules, - onShowOrgSelector: () => navigateTo("organization"), onShowConfigSelector: () => navigateTo("config"), onShowModelSelector: () => navigateTo("model"), onShowMCPSelector: () => navigateTo("mcp"), @@ -143,8 +142,11 @@ const TUIChat: React.FC = ({ const { renderMessage } = useMessageRenderer(); - const { handleOrganizationSelect, handleConfigSelect, handleModelSelect } = - useSelectors(configPath, setMessages, resetChatHistory); + const { handleConfigSelect, handleModelSelect } = useSelectors( + configPath, + setMessages, + resetChatHistory, + ); // Determine if input should be disabled // Allow input even when services are loading, but disable for UI overlays @@ -200,7 +202,6 @@ const TUIChat: React.FC = ({ navState={navState} services={services} handleLoginTokenSubmit={handleLoginTokenSubmit} - handleOrganizationSelect={handleOrganizationSelect} handleConfigSelect={handleConfigSelect} handleModelSelect={handleModelSelect} handleReload={handleReload} diff --git a/src/ui/components/ScreenContent.tsx b/src/ui/components/ScreenContent.tsx index 8e0e8c779..94a558dd9 100644 --- a/src/ui/components/ScreenContent.tsx +++ b/src/ui/components/ScreenContent.tsx @@ -6,7 +6,6 @@ import type { NavigationScreen } from "../context/NavigationContext.js"; import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; import { MCPSelector } from "../MCPSelector.js"; import { ModelSelector } from "../ModelSelector.js"; -import { OrganizationSelector } from "../OrganizationSelector.js"; import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; import { UserInput } from "../UserInput.js"; @@ -17,10 +16,6 @@ interface ScreenContentProps { navState: any; services: any; handleLoginTokenSubmit: (token: string) => void; - handleOrganizationSelect: ( - organizationId: string | null, - organizationName: string, - ) => Promise; handleConfigSelect: (config: ConfigOption) => Promise; handleModelSelect: (model: ModelOption) => Promise; handleReload: () => Promise; @@ -46,7 +41,6 @@ export const ScreenContent: React.FC = ({ navState, services, handleLoginTokenSubmit, - handleOrganizationSelect, handleConfigSelect, handleModelSelect, handleReload, @@ -88,16 +82,6 @@ export const ScreenContent: React.FC = ({ ); } - // Organization selector - if (isScreenActive("organization")) { - return ( - - ); - } - // Config selector if (isScreenActive("config")) { return ( diff --git a/src/ui/context/NavigationContext.tsx b/src/ui/context/NavigationContext.tsx index 70e052940..ee7861b80 100644 --- a/src/ui/context/NavigationContext.tsx +++ b/src/ui/context/NavigationContext.tsx @@ -12,8 +12,7 @@ import React, { */ export type NavigationScreen = | "chat" // Normal chat interface - | "organization" // Organization selector - | "config" // Config selector + | "config" // Config selector (includes organization switching) | "model" // Model selector | "free-trial" // Free trial transition UI | "login" // Login prompt diff --git a/src/ui/context/__tests__/NavigationContext.test.tsx b/src/ui/context/__tests__/NavigationContext.test.tsx index 7d35b84d7..bd18c7324 100644 --- a/src/ui/context/__tests__/NavigationContext.test.tsx +++ b/src/ui/context/__tests__/NavigationContext.test.tsx @@ -50,10 +50,10 @@ describe("NavigationContext", () => { const { result } = renderHook(() => useNavigation(), { wrapper }); act(() => { - result.current.navigateTo("organization"); + result.current.navigateTo("config"); }); - expect(result.current.state.currentScreen).toBe("organization"); + expect(result.current.state.currentScreen).toBe("config"); }); it("navigates to a new screen with data", () => { @@ -72,11 +72,11 @@ describe("NavigationContext", () => { const { result } = renderHook(() => useNavigation(), { wrapper }); const screens: NavigationScreen[] = [ "chat", - "organization", "config", "model", "free-trial", "login", + "mcp", ]; screens.forEach((screen) => { @@ -113,7 +113,7 @@ describe("NavigationContext", () => { expect(result.current.state.screenData).toEqual(testData); act(() => { - result.current.navigateTo("organization"); + result.current.navigateTo("config"); }); expect(result.current.state.screenData).toBeNull(); }); @@ -124,9 +124,9 @@ describe("NavigationContext", () => { const { result } = renderHook(() => useNavigation(), { wrapper }); act(() => { - result.current.navigateTo("organization"); + result.current.navigateTo("config"); }); - expect(result.current.state.currentScreen).toBe("organization"); + expect(result.current.state.currentScreen).toBe("config"); act(() => { result.current.closeCurrentScreen(); @@ -163,12 +163,12 @@ describe("NavigationContext", () => { it("closes from any screen back to chat", () => { const { result } = renderHook(() => useNavigation(), { wrapper }); - const screens: Array<"organization" | "config" | "model" | "free-trial" | "login"> = [ - "organization", + const screens: Array<"config" | "model" | "free-trial" | "login" | "mcp"> = [ "config", "model", "free-trial", "login", + "mcp", ]; screens.forEach((screen) => { @@ -192,19 +192,19 @@ describe("NavigationContext", () => { expect(result.current.isScreenActive("chat")).toBe(true); act(() => { - result.current.navigateTo("organization"); + result.current.navigateTo("config"); }); - expect(result.current.isScreenActive("organization")).toBe(true); + expect(result.current.isScreenActive("config")).toBe(true); expect(result.current.isScreenActive("chat")).toBe(false); }); it("returns false for inactive screens", () => { const { result } = renderHook(() => useNavigation(), { wrapper }); - expect(result.current.isScreenActive("organization")).toBe(false); expect(result.current.isScreenActive("config")).toBe(false); expect(result.current.isScreenActive("model")).toBe(false); + expect(result.current.isScreenActive("mcp")).toBe(false); expect(result.current.isScreenActive("free-trial")).toBe(false); expect(result.current.isScreenActive("login")).toBe(false); }); @@ -237,11 +237,11 @@ describe("NavigationContext", () => { const initialState = result.current.state; act(() => { - result.current.navigateTo("organization"); + result.current.navigateTo("config"); }); expect(result.current.state).not.toBe(initialState); - expect(result.current.state.currentScreen).toBe("organization"); + expect(result.current.state.currentScreen).toBe("config"); }); it("preserves unrelated state when updating", () => { @@ -288,14 +288,14 @@ describe("NavigationContext", () => { expect(result.current.state.screenData).toBeNull(); }); - it("handles organization selection flow", () => { + it("handles config selection flow (now includes organization switching)", () => { const { result } = renderHook(() => useNavigation(), { wrapper }); - // Navigate to organization selector + // Navigate to config selector act(() => { - result.current.navigateTo("organization"); + result.current.navigateTo("config"); }); - expect(result.current.isScreenActive("organization")).toBe(true); + expect(result.current.isScreenActive("config")).toBe(true); // Close after selection act(() => { diff --git a/src/ui/hooks/useChat.helpers.ts b/src/ui/hooks/useChat.helpers.ts index b2b0687e3..a4fa494a9 100644 --- a/src/ui/hooks/useChat.helpers.ts +++ b/src/ui/hooks/useChat.helpers.ts @@ -33,16 +33,6 @@ export async function initChatHistory( return history; } -/** - * Handle /org command - */ -export function handleOrgCommand(onShowOrgSelector: () => void): void { - posthogService.capture("useSlashCommand", { - name: "org", - }); - onShowOrgSelector(); -} - /** * Handle /config command */ @@ -227,7 +217,6 @@ interface HandleSpecialCommandsOptions { message: string; isRemoteMode: boolean; remoteUrl?: string; - onShowOrgSelector: () => void; onShowConfigSelector: () => void; exit: () => void; setMessages: React.Dispatch>; @@ -240,19 +229,12 @@ export async function handleSpecialCommands({ message, isRemoteMode, remoteUrl, - onShowOrgSelector, onShowConfigSelector, exit, setMessages, }: HandleSpecialCommandsOptions): Promise { const trimmedMessage = message.trim(); - // Special handling for /org command in TUI - if (trimmedMessage === "/org") { - handleOrgCommand(onShowOrgSelector); - return true; - } - // Special handling for /config command in TUI if (trimmedMessage === "/config") { handleConfigCommand(onShowConfigSelector); diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index b679c327e..ff6306ca7 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -42,7 +42,6 @@ export function useChat({ initialPrompt, resume, additionalRules, - onShowOrgSelector, onShowConfigSelector, onShowModelSelector, onShowMCPSelector, @@ -164,7 +163,6 @@ export function useChat({ message, isRemoteMode, remoteUrl, - onShowOrgSelector, onShowConfigSelector, exit, setMessages, diff --git a/src/ui/hooks/useChat.types.ts b/src/ui/hooks/useChat.types.ts index 8660cd717..dfdec112e 100644 --- a/src/ui/hooks/useChat.types.ts +++ b/src/ui/hooks/useChat.types.ts @@ -11,7 +11,6 @@ export interface UseChatProps { initialPrompt?: string; resume?: boolean; additionalRules?: string[]; - onShowOrgSelector: () => void; onShowConfigSelector: () => void; onShowMCPSelector: () => void; onShowModelSelector?: () => void; diff --git a/src/ui/hooks/useConfigSelector.ts b/src/ui/hooks/useConfigSelector.ts index 89b97fc20..4d57695ca 100644 --- a/src/ui/hooks/useConfigSelector.ts +++ b/src/ui/hooks/useConfigSelector.ts @@ -10,6 +10,7 @@ interface ConfigOption { name: string; type: "local" | "assistant" | "create"; slug?: string; + organizationId?: string | null; } interface UseConfigSelectorProps { @@ -77,6 +78,12 @@ export function useConfigSelector({ messageType: "system" as const, }); + // First, check if we need to switch organizations + const currentAuthState = services.auth.getState(); + const currentOrgId = currentAuthState.authConfig + ? (currentAuthState.authConfig.organizationId ?? null) + : null; + let targetConfigPath: string | undefined; if (config.type === "local") { @@ -85,9 +92,25 @@ export function useConfigSelector({ targetConfigPath = config.slug; } - // Use the ConfigService's reactive updateConfigPath method - // This will automatically update state and trigger dependent service reloads - await services.config.updateConfigPath(targetConfigPath); + // If we need to switch organizations, we'll handle both org + config switching + // using a different approach to avoid duplicate reloads + if (config.organizationId === currentOrgId) { + // Only config path is changing, no organization switch needed + await services.config.updateConfigPath(targetConfigPath); + } else { + onMessage({ + role: "system", + content: `Switching to organization for ${config.name}...`, + messageType: "system" as const, + }); + + // Switch organization first + await services.auth.switchOrganization(config.organizationId ?? null); + + // Update config path THEN reload services once + // This avoids the double reload issue + await services.config.updateConfigPath(targetConfigPath); + } // Reset chat history onChatReset(); diff --git a/src/ui/hooks/useOrganizationSelector.ts b/src/ui/hooks/useOrganizationSelector.ts deleted file mode 100644 index 98daead95..000000000 --- a/src/ui/hooks/useOrganizationSelector.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { isAuthenticatedConfig } from "../../auth/workos.js"; -import { services, reloadService } from "../../services/index.js"; -import { SERVICE_NAMES } from "../../services/types.js"; -import { useNavigation } from "../context/NavigationContext.js"; - -interface UseOrganizationSelectorProps { - onMessage: (message: { - role: string; - content: string; - messageType: "system"; - }) => void; - onChatReset: () => void; -} - -export function useOrganizationSelector({ - onMessage, - onChatReset, -}: UseOrganizationSelectorProps) { - const { closeCurrentScreen } = useNavigation(); - - const handleOrganizationSelect = async ( - organizationId: string | null, - organizationName: string, - ) => { - try { - // Check if user is authenticated - const authState = services.auth.getState(); - if (!authState.isAuthenticated || !authState.authConfig) { - onMessage({ - role: "system", - content: "Organization switching not available - not authenticated", - messageType: "system" as const, - }); - return; - } - - if (!isAuthenticatedConfig(authState.authConfig)) { - onMessage({ - role: "system", - content: - "Organization switching not available for environment variable auth", - messageType: "system" as const, - }); - return; - } - - // Show loading message - onMessage({ - role: "system", - content: `Switching to organization: ${organizationName}...`, - messageType: "system" as const, - }); - - // Switch organization through the auth service - await services.auth.switchOrganization(organizationId); - - // Reload all dependent services (API_CLIENT -> CONFIG -> MODEL/MCP) - await reloadService(SERVICE_NAMES.AUTH); - - // Reset chat history - onChatReset(); - - // Clear the screen completely - process.stdout.write("\x1b[2J\x1b[H"); - - // Show success message - onMessage({ - role: "system", - content: `Successfully switched to organization: ${organizationName}`, - messageType: "system" as const, - }); - - // Close the organization selector - closeCurrentScreen(); - } catch (error: any) { - // Show error message - onMessage({ - role: "system", - content: `Failed to switch organization: ${error.message}`, - messageType: "system" as const, - }); - - // Close selector even on error - closeCurrentScreen(); - } - }; - - return { - handleOrganizationSelect, - }; -} diff --git a/src/ui/hooks/useTUIChatHooks.ts b/src/ui/hooks/useTUIChatHooks.ts index 762c9d481..f32a893ff 100644 --- a/src/ui/hooks/useTUIChatHooks.ts +++ b/src/ui/hooks/useTUIChatHooks.ts @@ -7,7 +7,6 @@ import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; import { useConfigSelector } from "./useConfigSelector.js"; import { useModelSelector } from "./useModelSelector.js"; -import { useOrganizationSelector } from "./useOrganizationSelector.js"; // Helper function to get repo URL text export function getRepoUrlText(remoteUrl?: string): string { @@ -112,20 +111,9 @@ export function useSelectors( setMessages: React.Dispatch>, resetChatHistory: () => void, ): { - handleOrganizationSelect: ( - organizationId: string | null, - organizationName: string, - ) => Promise; handleConfigSelect: (config: ConfigOption) => Promise; handleModelSelect: (model: ModelOption) => Promise; } { - const { handleOrganizationSelect } = useOrganizationSelector({ - onMessage: (message) => { - setMessages((prev) => [...prev, message]); - }, - onChatReset: resetChatHistory, - }); - const { handleConfigSelect } = useConfigSelector({ configPath, onMessage: (message) => { @@ -141,7 +129,6 @@ export function useSelectors( }); return { - handleOrganizationSelect, handleConfigSelect, handleModelSelect, };