From d19262590187ebf87c5255c718004231fd8a1537 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 13:24:07 -0700 Subject: [PATCH] org switcher --- src/auth/workos.ts | 40 ++++++++ src/index.ts | 35 +++---- src/slashCommands.ts | 6 +- src/ui/OrganizationSelector.tsx | 156 ++++++++++++++++++++++++++++++++ src/ui/SlashCommandUI.tsx | 14 ++- src/ui/TUIChat.tsx | 115 ++++++++++++++++++++++- src/ui/UserInput.tsx | 24 ++++- src/ui/index.ts | 5 +- 8 files changed, 364 insertions(+), 31 deletions(-) create mode 100644 src/ui/OrganizationSelector.tsx diff --git a/src/auth/workos.ts b/src/auth/workos.ts index c60b610c1..b87e2e039 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -356,6 +356,46 @@ export async function ensureOrganization( } } +/** + * Gets the list of available organizations for the user + */ +export async function listUserOrganizations(): Promise< + { id: string; name: string }[] | null +> { + // If using CONTINUE_API_KEY environment variable, organization switching is not supported + if (process.env.CONTINUE_API_KEY) { + return null; + } + + const authConfig = loadAuthConfig(); + + if (!authConfig.accessToken) { + return null; + } + + const apiClient = new DefaultApi( + new Configuration({ + accessToken: authConfig.accessToken, + }) + ); + + try { + const resp = await apiClient.listOrganizations(); + return resp.organizations || []; + } catch (error) { + return null; + } +} + +/** + * Checks if the user has multiple organizations available + */ +export async function hasMultipleOrganizations(): Promise { + const organizations = await listUserOrganizations(); + // Has multiple organizations if there's at least one organization (plus personal) + return organizations !== null && organizations.length > 0; +} + /** * Logs the user out by clearing saved credentials */ diff --git a/src/index.ts b/src/index.ts index 8366b3b34..b6c3c4060 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,11 +6,10 @@ import * as readlineSync from "readline-sync"; import { parseArgs } from "./args.js"; import { initializeAssistant } from "./assistant.js"; import { ensureAuthenticated } from "./auth/ensureAuth.js"; -import { loadAuthConfig, ensureOrganization } from "./auth/workos.js"; +import { ensureOrganization, loadAuthConfig } from "./auth/workos.js"; import { introMessage } from "./intro.js"; import { configureLogger } from "./logger.js"; import { loadSession, saveSession } from "./session.js"; -import { handleSlashCommands } from "./slashCommands.js"; import { streamChatResponse } from "./streamChatResponse.js"; import { constructSystemMessage } from "./systemMessage.js"; import { startTUIChat } from "./ui/index.js"; @@ -21,7 +20,7 @@ const args = parseArgs(); // Configure logger based on headless mode configureLogger(args.isHeadless); -async function chat() { +async function initializeChat() { const isAuthenticated = await ensureAuthenticated(true); if (!isAuthenticated) { @@ -32,7 +31,10 @@ async function chat() { const authConfig = loadAuthConfig(); // Ensure organization is selected - const authConfigWithOrg = await ensureOrganization(authConfig, args.isHeadless); + const authConfigWithOrg = await ensureOrganization( + authConfig, + args.isHeadless + ); // Initialize ContinueSDK and MCPService once const { config, llmApi, model, mcpService } = await initializeAssistant( @@ -40,6 +42,12 @@ async function chat() { args.configPath ); + return { config, llmApi, model, mcpService }; +} + +async function chat() { + let { config, llmApi, model, mcpService } = await initializeChat(); + // If not in headless mode, start the TUI chat (default) if (!args.isHeadless) { await startTUIChat( @@ -48,7 +56,8 @@ async function chat() { model, mcpService, args.prompt, - args.resume + args.resume, + args.configPath ); return; } @@ -94,22 +103,6 @@ async function chat() { isFirstMessage = false; - // Handle slash commands - const commandResult = handleSlashCommands(userInput, config); - if (commandResult) { - if (commandResult.exit) { - break; - } - - // Note that `console.log` is shown in headless mode, `console.info` is not - console.log(`\n${chalk.italic.gray(commandResult.output ?? "")}`); - - if (commandResult.newInput) { - userInput = commandResult.newInput; - } else { - continue; - } - } // Add user message to history chatHistory.push({ role: "user", content: userInput }); diff --git a/src/slashCommands.ts b/src/slashCommands.ts index c7d011f71..f29de50ea 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -7,15 +7,15 @@ import { } from "./auth/workos.js"; import { type AssistantConfig } from "@continuedev/sdk"; -export function handleSlashCommands( +export async function handleSlashCommands( input: string, assistant: AssistantConfig -): { +): Promise<{ output?: string; exit?: boolean; newInput?: string; clear?: boolean; -} | null { +} | null> { if (input.startsWith("/")) { const [command, ...args] = input.slice(1).split(" "); switch (command) { diff --git a/src/ui/OrganizationSelector.tsx b/src/ui/OrganizationSelector.tsx new file mode 100644 index 000000000..076c9fd4b --- /dev/null +++ b/src/ui/OrganizationSelector.tsx @@ -0,0 +1,156 @@ +import { Box, Text, useInput } from "ink"; +import React, { useEffect, useState } from "react"; +import { loadAuthConfig, listUserOrganizations } from "../auth/workos.js"; + +interface Organization { + id: string; + name: string; +} + +interface OrganizationSelectorProps { + onSelect: (organizationId: string | null, organizationName: string) => void; + onCancel: () => void; +} + +const OrganizationSelector: React.FC = ({ + onSelect, + onCancel, +}) => { + const [organizations, setOrganizations] = 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(authConfig.organizationId); + + const organizations = await listUserOrganizations(); + if (organizations === null) { + setError("Failed to load organizations"); + setLoading(false); + return; + } + + setOrganizations(organizations); + setLoading(false); + } catch (err: any) { + setError(err.message || "Failed to load organizations"); + setLoading(false); + } + }; + + loadOrganizations(); + }, []); + + useInput((input, key) => { + if (key.escape) { + onCancel(); + return; + } + + if (key.return) { + const totalOptions = organizations.length + 1; // +1 for personal + if (selectedIndex === 0) { + onSelect(null, "Personal"); + } else if (selectedIndex <= organizations.length) { + const selectedOrg = organizations[selectedIndex - 1]; + onSelect(selectedOrg.id, selectedOrg.name); + } + return; + } + + if (key.upArrow) { + setSelectedIndex((prev) => Math.max(0, prev - 1)); + } else if (key.downArrow) { + const totalOptions = organizations.length + 1; // +1 for personal + setSelectedIndex((prev) => Math.min(totalOptions - 1, prev + 1)); + } + }); + + if (loading) { + return ( + + + Organization Selector + + Loading organizations... + + ); + } + + if (error) { + return ( + + + Error + + {error} + + Press Escape to cancel + + + ); + } + + const allOptions = [ + { id: null, name: "Personal", isCurrent: currentOrgId === null }, + ...organizations.map((org) => ({ + ...org, + isCurrent: currentOrgId === org.id, + })), + ]; + + return ( + + + Select Organization + + + {allOptions.map((option, index) => { + const isSelected = index === selectedIndex; + const isCurrent = option.isCurrent; + + return ( + + + {isSelected ? "▶ " : " "} + {option.name} + {isCurrent ? " (current)" : ""} + + + ); + })} + + + + Use ↑/↓ to navigate, Enter to select, Escape to cancel + + + + ); +}; + +export default OrganizationSelector; \ No newline at end of file diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx index 60d454715..089b28987 100644 --- a/src/ui/SlashCommandUI.tsx +++ b/src/ui/SlashCommandUI.tsx @@ -1,6 +1,7 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text } from "ink"; -import React from "react"; +import React, { useEffect, useState } from "react"; +import { hasMultipleOrganizations } from "../auth/workos.js"; interface SlashCommandUIProps { assistant: AssistantConfig; @@ -21,6 +22,12 @@ const SlashCommandUI: React.FC = ({ selectedIndex, onSelect, }) => { + const [hasMultipleOrgs, setHasMultipleOrgs] = useState(false); + + useEffect(() => { + hasMultipleOrganizations().then(setHasMultipleOrgs); + }, []); + // Get all available slash commands const getSlashCommands = (): SlashCommand[] => { const systemCommands: SlashCommand[] = [ @@ -42,6 +49,11 @@ const SlashCommandUI: React.FC = ({ description: "Check who you're currently logged in as", category: "system", }, + ...(hasMultipleOrgs ? [{ + name: "org", + description: "Switch organization", + category: "system" as const, + }] : []), ]; const assistantCommands: SlashCommand[] = diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index fc0b058be..e968be15b 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -6,11 +6,16 @@ import path from "path"; import React, { useEffect, useState } from "react"; import { loadSession, saveSession } from "../session.js"; import { handleSlashCommands } from "../slashCommands.js"; +import { saveAuthConfig, loadAuthConfig } from "../auth/workos.js"; +import { initializeAssistant } from "../assistant.js"; +import { MCPService } from "../mcp.js"; +import { introMessage } from "../intro.js"; import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; import { getToolDisplayName } from "../tools.js"; import LoadingAnimation from "./LoadingAnimation.js"; import MarkdownRenderer from "./MarkdownRenderer.js"; +import OrganizationSelector from "./OrganizationSelector.js"; import ToolResultSummary from "./ToolResultSummary.js"; import UserInput from "./UserInput.js"; @@ -18,6 +23,8 @@ interface TUIChatProps { config: AssistantUnrolled; model: string; llmApi: BaseLlmApi; + mcpService: MCPService; + configPath?: string; initialPrompt?: string; resume?: boolean; } @@ -32,12 +39,19 @@ interface DisplayMessage { } const TUIChat: React.FC = ({ - config: assistant, - model, - llmApi, + config: initialAssistant, + model: initialModel, + llmApi: initialLlmApi, + mcpService: initialMcpService, + configPath, initialPrompt, resume, }) => { + // Track current assistant configuration state + const [assistant, setAssistant] = useState(initialAssistant); + const [model, setModel] = useState(initialModel); + const [llmApi, setLlmApi] = useState(initialLlmApi); + const [mcpService, setMcpService] = useState(initialMcpService); const [chatHistory, setChatHistory] = useState( () => { let history: ChatCompletionMessageParam[] = []; @@ -85,6 +99,7 @@ const TUIChat: React.FC = ({ const [attachedFiles, setAttachedFiles] = useState< Array<{ path: string; content: string }> >([]); + const [showOrgSelector, setShowOrgSelector] = useState(false); const { exit } = useApp(); // Handle initial prompt @@ -95,8 +110,14 @@ const TUIChat: React.FC = ({ }, [initialPrompt]); const handleUserMessage = async (message: string) => { + // Special handling for /org command in TUI - show selector instead of prompting + if (message.trim() === "/org") { + setShowOrgSelector(true); + return; + } + // Handle slash commands - const commandResult = handleSlashCommands(message, assistant); + const commandResult = await handleSlashCommands(message, assistant); if (commandResult) { if (commandResult.exit) { exit(); @@ -123,6 +144,7 @@ const TUIChat: React.FC = ({ return; } + // Add command output to messages if (commandResult.output) { setMessages((prev) => [ @@ -392,6 +414,82 @@ const TUIChat: React.FC = ({ ); }; + const handleOrganizationSelect = async (organizationId: string | null, organizationName: string) => { + setShowOrgSelector(false); + + // Update auth config + const authConfig = loadAuthConfig(); + const updatedConfig = { + ...authConfig, + organizationId, + }; + saveAuthConfig(updatedConfig); + + try { + // Show loading message + setMessages([ + { + role: "system", + content: `Switching to organization: ${organizationName}...`, + messageType: "system", + }, + ]); + + // Reinitialize assistant with new organization (full refresh) + const { config, llmApi: newLlmApi, model: newModel, mcpService: newMcpService } = await initializeAssistant( + updatedConfig, + configPath // Pass the original config path to potentially load different assistant + ); + + // Update state with new assistant configuration + setAssistant(config); + setLlmApi(newLlmApi); + setModel(newModel); + setMcpService(newMcpService); + + // Clear chat history and start fresh + const rulesSystemMessage = ""; // TODO: get from assistant.systemMessage if available + const systemMessage = constructSystemMessage(rulesSystemMessage); + const newHistory = systemMessage ? [{ role: "system" as const, content: systemMessage }] : []; + setChatHistory(newHistory); + + // Clear the screen completely + clearScreen(); + + // Show the new intro message for the new assistant + introMessage(config, newModel, newMcpService); + + // Clear messages and show success + setMessages([ + { + role: "system", + content: `Successfully switched to organization: ${organizationName}`, + messageType: "system", + }, + ]); + + } catch (error: any) { + // Show error message + setMessages((prev) => [ + ...prev, + { + role: "system", + content: `Failed to switch organization: ${error.message}`, + messageType: "system", + }, + ]); + } + }; + + const handleOrganizationCancel = () => { + setShowOrgSelector(false); + }; + + const clearScreen = () => { + // Clear the terminal screen + process.stdout.write('\x1b[2J\x1b[H'); + }; + return ( {/* Chat history - takes up all available space above input */} @@ -409,6 +507,14 @@ const TUIChat: React.FC = ({ )} + {/* Organization selector - shows above input when active */} + {showOrgSelector && ( + + )} + {/* Input area - always at bottom */} = ({ onInterrupt={handleInterrupt} assistant={assistant} onFileAttached={handleFileAttached} + disabled={showOrgSelector} /> ● Continue CLI diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index b6c30cd73..0283f2ec2 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -1,6 +1,7 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text, useApp, useInput } from "ink"; -import React, { useState } from "react"; +import React, { useState, useEffect } from "react"; +import { hasMultipleOrganizations } from "../auth/workos.js"; import { InputHistory } from "../util/inputHistory.js"; import FileSearchUI from "./FileSearchUI.js"; import SlashCommandUI from "./SlashCommandUI.js"; @@ -13,6 +14,7 @@ interface UserInputProps { onInterrupt?: () => void; assistant: AssistantConfig; onFileAttached?: (filePath: string, content: string) => void; + disabled?: boolean; } const UserInput: React.FC = ({ @@ -22,6 +24,7 @@ const UserInput: React.FC = ({ onInterrupt, assistant, onFileAttached, + disabled = false, }) => { const [textBuffer] = useState(() => new TextBuffer()); const [inputHistory] = useState(() => new InputHistory()); @@ -39,6 +42,12 @@ const UserInput: React.FC = ({ const { exit } = useApp(); // Get all available slash commands + const [hasMultipleOrgs, setHasMultipleOrgs] = useState(false); + + useEffect(() => { + hasMultipleOrganizations().then(setHasMultipleOrgs); + }, []); + const getSlashCommands = () => { const systemCommands = [ { name: "help", description: "Show help message" }, @@ -49,6 +58,10 @@ const UserInput: React.FC = ({ name: "whoami", description: "Check who you're currently logged in as", }, + ...(hasMultipleOrgs ? [{ + name: "org", + description: "Switch organization", + }] : []), ]; const assistantCommands = @@ -185,6 +198,10 @@ const UserInput: React.FC = ({ }; useInput((input, key) => { + // Don't handle any input when disabled + if (disabled) { + return; + } if (key.ctrl && (input === "c" || input === "d")) { exit(); return; @@ -433,6 +450,11 @@ const UserInput: React.FC = ({ } }; + // Don't render anything when disabled + if (disabled) { + return null; + } + return ( {/* Input box */} diff --git a/src/ui/index.ts b/src/ui/index.ts index 03c20f6e4..12711075d 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -14,7 +14,8 @@ export async function startTUIChat( model: string, mcpService: MCPService, initialPrompt?: string, - resume?: boolean + resume?: boolean, + configPath?: string ) { // Show intro message before starting TUI introMessage(config, model, mcpService); @@ -25,6 +26,8 @@ export async function startTUIChat( config: config, model, llmApi, + mcpService, + configPath, initialPrompt, resume, })