Merge branch 'main' into resume-slash

This commit is contained in:
Nate 2025-08-18 19:01:44 -07:00
commit 2adee663a4
19 changed files with 120 additions and 428 deletions

View file

@ -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

View file

@ -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 => {

View file

@ -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",

View file

@ -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)", () => {
@ -212,5 +148,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");
});
});
});

View file

@ -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<SlashCommandResult> {
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<SlashCommandResult> {
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 <organization-id> 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<string, CommandHandler> = {
help: handleHelp,
clear: () => {
@ -201,7 +126,6 @@ const commandHandlers: Record<string, CommandHandler> = {
posthogService.capture("useSlashCommand", { name: "resume" });
return { openSessionSelector: true };
},
org: handleOrg,
};
export async function handleSlashCommands(

View file

@ -11,7 +11,7 @@ export const writeChecklistTool: Tool = {
checklist: {
type: "string",
description:
"The complete checklist in markdown format using - [ ] for incomplete tasks and - [x] for completed tasks. Avoid headers and additional content unless specifically being used to group checkboxes",
"The complete checklist in markdown format using - [ ] for incomplete tasks and - [x] for completed tasks. Avoid headers and additional content unless specifically being used to group checkboxes. Try to keep the list short, and make each item specific and actionable.",
required: true,
},
},

View file

@ -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<ConfigSelectorProps> = ({
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<ConfigSelectorProps> = ({
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<ConfigSelectorProps> = ({
// 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";

View file

@ -186,8 +186,8 @@ const FreeTrialTransitionUI: React.FC<FreeTrialTransitionUIProps> = ({
// 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<FreeTrialTransitionUIProps> = ({
{hasOrganizations && (
<Text color={selectedOption === 4 ? "cyan" : "white"}>
{selectedOption === 4 ? "▶ " : " "}4. 🏢 Switch to organization
profile
configuration
</Text>
)}
<Text></Text>

View file

@ -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<OrganizationSelectorProps> = ({
onSelect,
onCancel,
}) => {
const [allOptions, setAllOptions] = useState<Organization[]>([]);
const [selectedIndex, setSelectedIndex] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [currentOrgId, setCurrentOrgId] = useState<string | null | undefined>();
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 (
<Selector
title="Select Organization"
options={allOptions}
selectedIndex={selectedIndex}
loading={loading}
error={error}
loadingMessage="Loading organizations..."
currentId={currentOrgId === null ? "personal" : currentOrgId}
onSelect={handleSelect}
onCancel={onCancel}
onNavigate={setSelectedIndex}
/>
);
};
export { OrganizationSelector };

View file

@ -125,7 +125,6 @@ const TUIChat: React.FC<TUIChatProps> = ({
initialPrompt,
resume,
additionalRules,
onShowOrgSelector: () => navigateTo("organization"),
onShowConfigSelector: () => navigateTo("config"),
onShowModelSelector: () => navigateTo("model"),
onShowMCPSelector: () => navigateTo("mcp"),
@ -145,8 +144,11 @@ const TUIChat: React.FC<TUIChatProps> = ({
const { renderMessage } = useMessageRenderer();
const { handleOrganizationSelect, handleConfigSelect, handleModelSelect } =
useSelectors(configPath, setMessages, resetChatHistory);
const { handleConfigSelect, handleModelSelect } = useSelectors(
configPath,
setMessages,
resetChatHistory,
);
// Session selection handler
const handleSessionSelect = async (sessionId: string) => {
@ -244,7 +246,6 @@ const TUIChat: React.FC<TUIChatProps> = ({
navState={navState}
services={services}
handleLoginTokenSubmit={handleLoginTokenSubmit}
handleOrganizationSelect={handleOrganizationSelect}
handleConfigSelect={handleConfigSelect}
handleModelSelect={handleModelSelect}
handleSessionSelect={handleSessionSelect}

View file

@ -7,7 +7,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 { SessionSelector } from "../SessionSelector.js";
import type { ConfigOption, ModelOption } from "../types/selectorTypes.js";
import { UserInput } from "../UserInput.js";
@ -19,10 +18,6 @@ interface ScreenContentProps {
navState: any;
services: any;
handleLoginTokenSubmit: (token: string) => void;
handleOrganizationSelect: (
organizationId: string | null,
organizationName: string,
) => Promise<void>;
handleConfigSelect: (config: ConfigOption) => Promise<void>;
handleModelSelect: (model: ModelOption) => Promise<void>;
handleSessionSelect: (sessionId: string) => Promise<void>;
@ -49,7 +44,6 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
navState,
services,
handleLoginTokenSubmit,
handleOrganizationSelect,
handleConfigSelect,
handleModelSelect,
handleSessionSelect,
@ -92,16 +86,6 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
);
}
// Organization selector
if (isScreenActive("organization")) {
return (
<OrganizationSelector
onSelect={handleOrganizationSelect}
onCancel={closeCurrentScreen}
/>
);
}
// Config selector
if (isScreenActive("config")) {
return (

View file

@ -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

View file

@ -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(() => {

View file

@ -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
*/
@ -234,7 +224,6 @@ interface HandleSpecialCommandsOptions {
message: string;
isRemoteMode: boolean;
remoteUrl?: string;
onShowOrgSelector: () => void;
onShowConfigSelector: () => void;
exit: () => void;
setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
@ -247,19 +236,12 @@ export async function handleSpecialCommands({
message,
isRemoteMode,
remoteUrl,
onShowOrgSelector,
onShowConfigSelector,
exit,
setMessages,
}: HandleSpecialCommandsOptions): Promise<boolean> {
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);

View file

@ -42,7 +42,6 @@ export function useChat({
initialPrompt,
resume,
additionalRules,
onShowOrgSelector,
onShowConfigSelector,
onShowModelSelector,
onShowMCPSelector,
@ -165,7 +164,6 @@ export function useChat({
message,
isRemoteMode,
remoteUrl,
onShowOrgSelector,
onShowConfigSelector,
exit,
setMessages,

View file

@ -11,7 +11,6 @@ export interface UseChatProps {
initialPrompt?: string;
resume?: boolean;
additionalRules?: string[];
onShowOrgSelector: () => void;
onShowConfigSelector: () => void;
onShowMCPSelector: () => void;
onShowModelSelector?: () => void;

View file

@ -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();

View file

@ -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,
};
}

View file

@ -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<React.SetStateAction<any[]>>,
resetChatHistory: () => void,
): {
handleOrganizationSelect: (
organizationId: string | null,
organizationName: string,
) => Promise<void>;
handleConfigSelect: (config: ConfigOption) => Promise<void>;
handleModelSelect: (model: ModelOption) => Promise<void>;
} {
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,
};