diff --git a/src/auth/workos.ts b/src/auth/workos.ts index 3548a8023..d68a343e8 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -23,12 +23,14 @@ export interface AuthenticatedConfig { refreshToken: string; expiresAt: number; organizationId: string | null; // null means personal organization + assistantSlug?: string; // Optional assistant slug } // Represents configuration when using environment variable auth export interface EnvironmentAuthConfig { accessToken: string; organizationId: null; // Environment auth always uses personal organization + assistantSlug?: string; // Optional assistant slug } // Union type representing the possible authentication states @@ -68,6 +70,14 @@ export function getOrganizationId(config: AuthConfig): string | null { return config.organizationId; } +/** + * Gets the assistant slug from any auth config type + */ +export function getAssistantSlug(config: AuthConfig): string | null { + if (config === null) return null; + return config.assistantSlug || null; +} + /** * Loads the authentication configuration from disk */ @@ -99,6 +109,7 @@ export function loadAuthConfig(): AuthConfig { refreshToken: data.refreshToken, expiresAt: data.expiresAt, organizationId: data.organizationId || null, + assistantSlug: data.assistantSlug || undefined, }; } else { console.warn("Invalid auth config found, ignoring."); @@ -134,6 +145,25 @@ export function saveAuthConfig(config: AuthenticatedConfig): void { } } +/** + * Updates the assistant slug in the authentication configuration + */ +export function updateAssistantSlug(assistantSlug: string | null): void { + // If using CONTINUE_API_KEY environment variable, don't save anything + if (process.env.CONTINUE_API_KEY) { + return; + } + + const config = loadAuthConfig(); + if (config && isAuthenticatedConfig(config)) { + const updatedConfig: AuthenticatedConfig = { + ...config, + assistantSlug: assistantSlug || undefined, + }; + saveAuthConfig(updatedConfig); + } +} + /** * Checks if the user is authenticated and the token is valid */ @@ -232,6 +262,10 @@ async function refreshToken( organizationId: isAuthenticatedConfig(existingConfig) ? existingConfig.organizationId : null, + // Preserve existing assistantSlug if it exists + assistantSlug: isAuthenticatedConfig(existingConfig) + ? existingConfig.assistantSlug + : undefined, }; // Save the config @@ -331,6 +365,7 @@ export async function ensureOrganization( refreshToken: authenticatedConfig.refreshToken, expiresAt: authenticatedConfig.expiresAt, organizationId: null, // Default to personal organization + assistantSlug: authenticatedConfig.assistantSlug, }; saveAuthConfig(updatedConfig); return updatedConfig; @@ -355,6 +390,7 @@ export async function ensureOrganization( refreshToken: authenticatedConfig.refreshToken, expiresAt: authenticatedConfig.expiresAt, organizationId: null, + assistantSlug: authenticatedConfig.assistantSlug, }; saveAuthConfig(updatedConfig); return updatedConfig; @@ -371,6 +407,7 @@ export async function ensureOrganization( refreshToken: authenticatedConfig.refreshToken, expiresAt: authenticatedConfig.expiresAt, organizationId: selectedOrgId, + assistantSlug: authenticatedConfig.assistantSlug, }; saveAuthConfig(updatedConfig); @@ -388,6 +425,7 @@ export async function ensureOrganization( refreshToken: authenticatedConfig.refreshToken, expiresAt: authenticatedConfig.expiresAt, organizationId: null, + assistantSlug: authenticatedConfig.assistantSlug, }; saveAuthConfig(updatedConfig); return updatedConfig; diff --git a/src/config.ts b/src/config.ts index 0f4dda331..1553d9807 100644 --- a/src/config.ts +++ b/src/config.ts @@ -17,6 +17,7 @@ import { dirname } from "node:path"; import { AuthConfig, getAccessToken, + getAssistantSlug, getOrganizationId, } from "./auth/workos.js"; import { CLIPlatformClient } from "./CLIPlatformClient.js"; @@ -116,19 +117,30 @@ export async function loadConfig( ); if (!config) { - // Fall back to listing assistants and taking the first one - const assistants = await apiClient.listAssistants({ - alwaysUseProxy: "false", - organizationId: organizationId ?? undefined, - }); + // Check if there's a saved assistant slug in auth config + const assistantSlug = getAssistantSlug(authConfig); + if (assistantSlug) { + // Use the saved assistant slug + config = assistantSlug; + } else { + // Fall back to listing assistants and taking the first one + const assistants = await apiClient.listAssistants({ + alwaysUseProxy: "false", + organizationId: organizationId ?? undefined, + }); - const result = assistants[0].configResult; - if (result.errors?.length || !result.config) { - throw new Error(result.errors?.join("\n") ?? "Failed to load assistant."); + const result = assistants[0].configResult; + if (result.errors?.length || !result.config) { + throw new Error( + result.errors?.join("\n") ?? "Failed to load assistant." + ); + } + + return result.config as AssistantUnrolled; } + } - return result.config as AssistantUnrolled; - } else if ( + if ( config.startsWith(".") || config.startsWith("/") || config.startsWith("~") diff --git a/src/intro.ts b/src/intro.ts index 24233b918..f1dc82994 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -47,6 +47,8 @@ export function introMessage( console.info( `- ${chalk.green("/whoami")}: Check who you're currently logged in as` ); + console.info(`- ${chalk.green("/org")}: Switch organization`); + console.info(`- ${chalk.green("/config")}: Switch configuration`); for (const prompt of config.prompts ?? []) { console.info(`- /${prompt?.name}: ${prompt?.description}`); } diff --git a/src/slashCommands.ts b/src/slashCommands.ts index e9c7b5c26..ab5cb50f7 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -17,6 +17,7 @@ export async function handleSlashCommands( exit?: boolean; newInput?: string; clear?: boolean; + openConfigSelector?: boolean; } | null> { if (input.startsWith("/")) { const [command, ...args] = input.slice(1).split(" "); @@ -30,6 +31,8 @@ export async function handleSlashCommands( "/login - Authenticate with your account", "/logout - Sign out of your current session", "/whoami - Check who you're currently logged in as", + "/org - Switch organization", + "/config - Switch configuration", ...(assistant.prompts?.map( (prompt) => `/${prompt?.name} - ${prompt?.description}` ) ?? []), @@ -39,6 +42,8 @@ export async function handleSlashCommands( return { clear: true, output: "Chat history cleared" }; case "exit": return { exit: true, output: "Goodbye!" }; + case "config": + return { openConfigSelector: true }; case "login": login(false, onLoginPrompt) .then((config) => { diff --git a/src/ui/ConfigSelector.tsx b/src/ui/ConfigSelector.tsx new file mode 100644 index 000000000..435f4f638 --- /dev/null +++ b/src/ui/ConfigSelector.tsx @@ -0,0 +1,200 @@ +import { + Configuration, + DefaultApi, +} from "@continuedev/sdk/dist/api/dist/index.js"; +import * as fs from "fs"; +import { Box, Text, useInput } from "ink"; +import * as os from "os"; +import * as path from "path"; +import React, { useEffect, useState } from "react"; +import { + getAccessToken, + getOrganizationId, + loadAuthConfig, +} from "../auth/workos.js"; + +interface ConfigOption { + id: string; + name: string; + type: "local" | "assistant" | "create"; + slug?: string; +} + +interface ConfigSelectorProps { + onSelect: (config: ConfigOption) => void; + onCancel: () => void; +} + +const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); + +const ConfigSelector: React.FC = ({ + onSelect, + onCancel, +}) => { + const [configs, setConfigs] = useState([]); + const [selectedIndex, setSelectedIndex] = useState(0); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + const loadConfigs = async () => { + try { + const authConfig = loadAuthConfig(); + const accessToken = getAccessToken(authConfig); + const organizationId = getOrganizationId(authConfig); + + const options: ConfigOption[] = []; + + // Add local config.yaml if it exists + if (fs.existsSync(CONFIG_PATH)) { + options.push({ + id: "local", + name: "Local config.yaml", + type: "local", + }); + } + + // Add assistants from current organization if authenticated + if (accessToken) { + const apiClient = new DefaultApi( + new Configuration({ + accessToken, + }) + ); + + try { + const assistants = await apiClient.listAssistants({ + alwaysUseProxy: "false", + organizationId: organizationId ?? undefined, + }); + + for (const assistant of assistants) { + // Use 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.packageSlug, + }); + } + } catch (err) { + console.error("Failed to load assistants:", err); + } + } + + // Add "Create new assistant" option + options.push({ + id: "create", + name: "Create new assistant", + type: "create", + }); + + setConfigs(options); + setLoading(false); + } catch (err: any) { + setError(err.message || "Failed to load configurations"); + setLoading(false); + } + }; + + loadConfigs(); + }, []); + + useInput((input, key) => { + if (key.escape) { + onCancel(); + return; + } + + if (key.return) { + const selectedConfig = configs[selectedIndex]; + if (selectedConfig) { + onSelect(selectedConfig); + } + return; + } + + if (key.upArrow) { + setSelectedIndex((prev) => Math.max(0, prev - 1)); + } else if (key.downArrow) { + setSelectedIndex((prev) => Math.min(configs.length - 1, prev + 1)); + } + }); + + if (loading) { + return ( + + + Configuration Selector + + Loading configurations... + + ); + } + + if (error) { + return ( + + + Error + + {error} + + Press Escape to cancel + + + ); + } + + return ( + + + Select Configuration + + + {configs.map((config, index) => { + const isSelected = index === selectedIndex; + + return ( + + + {isSelected ? "▶ " : " "} + {config.name} + {config.type === "local" ? " (local)" : ""} + {config.type === "create" ? " (opens web)" : ""} + {isSelected ? " (current)" : ""} + + + ); + })} + + + + Use ↑/↓ to navigate, Enter to select, Escape to cancel + + + + ); +}; + +export default ConfigSelector; diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 457b24910..46703e653 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -3,7 +3,9 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; import { Box, Text } from "ink"; import React, { useState } from "react"; import { MCPService } from "../mcp.js"; +import ConfigSelector from "./ConfigSelector.js"; import { useChat } from "./hooks/useChat.js"; +import { useConfigSelector } from "./hooks/useConfigSelector.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; import LoadingAnimation from "./LoadingAnimation.js"; @@ -74,6 +76,7 @@ const TUIChat: React.FC = ({ initialPrompt, resume, onShowOrgSelector: () => showOrganizationSelector(), + onShowConfigSelector: () => showConfigSelectorUI(), onLoginPrompt: handleLoginPrompt, }); @@ -98,6 +101,25 @@ const TUIChat: React.FC = ({ onChatReset: resetChatHistory, }); + const { + showConfigSelector, + handleConfigSelect, + handleConfigCancel, + showConfigSelectorUI, + } = useConfigSelector({ + configPath, + onAssistantChange: (newAssistant, newModel, newLlmApi, newMcpService) => { + setAssistant(newAssistant); + setModel(newModel); + setLlmApi(newLlmApi); + setMcpService(newMcpService); + }, + onMessage: (message) => { + setMessages((prev) => [...prev, message]); + }, + onChatReset: resetChatHistory, + }); + return ( {/* Chat history - takes up all available space above input */} @@ -148,6 +170,14 @@ const TUIChat: React.FC = ({ /> )} + {/* Config selector - shows above input when active */} + {showConfigSelector && ( + + )} + {/* Input area - always at bottom */} = ({ onInterrupt={handleInterrupt} assistant={assistant} onFileAttached={handleFileAttached} - disabled={showOrgSelector || !!loginPrompt} + disabled={showOrgSelector || showConfigSelector || !!loginPrompt} /> ● Continue CLI diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index 67e537b04..a4a617ea1 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -1,6 +1,6 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text, useApp, useInput } from "ink"; -import React, { useState, useEffect } from "react"; +import React, { useEffect, useState } from "react"; import { hasMultipleOrganizations } from "../auth/workos.js"; import { InputHistory } from "../util/inputHistory.js"; import FileSearchUI from "./FileSearchUI.js"; @@ -63,10 +63,18 @@ const UserInput: React.FC = ({ name: "whoami", description: "Check who you're currently logged in as", }, - ...(hasMultipleOrgs ? [{ - name: "org", - description: "Switch organization", - }] : []), + { + name: "config", + description: "Switch configuration", + }, + ...(hasMultipleOrgs + ? [ + { + name: "org", + description: "Switch organization", + }, + ] + : []), ]; const assistantCommands = @@ -383,7 +391,8 @@ const UserInput: React.FC = ({ }); const renderInputText = () => { - const placeholderText = placeholder || "Ask anything, @ for context, / for slash commands"; + const placeholderText = + placeholder || "Ask anything, @ for context, / for slash commands"; if (inputText.length === 0) { return ( <> diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 5bb0a4bcf..0616d30da 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -22,6 +22,7 @@ interface UseChatProps { initialPrompt?: string; resume?: boolean; onShowOrgSelector: () => void; + onShowConfigSelector: () => void; onLoginPrompt?: (promptText: string) => Promise; } @@ -32,6 +33,7 @@ export function useChat({ initialPrompt, resume, onShowOrgSelector, + onShowConfigSelector, onLoginPrompt, }: UseChatProps) { const { exit } = useApp(); @@ -95,6 +97,12 @@ export function useChat({ return; } + // Special handling for /config command in TUI + if (message.trim() === "/config") { + onShowConfigSelector(); + return; + } + // Handle slash commands const commandResult = await handleSlashCommands(message, assistant, onLoginPrompt); if (commandResult) { @@ -103,6 +111,11 @@ export function useChat({ return; } + if (commandResult.openConfigSelector) { + onShowConfigSelector(); + return; + } + if (commandResult.clear) { const systemMessage = chatHistory.find((msg) => msg.role === "system"); const newHistory = systemMessage ? [systemMessage] : []; diff --git a/src/ui/hooks/useConfigSelector.ts b/src/ui/hooks/useConfigSelector.ts new file mode 100644 index 000000000..592928e48 --- /dev/null +++ b/src/ui/hooks/useConfigSelector.ts @@ -0,0 +1,155 @@ +import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { useState } from "react"; +import { exec } from "child_process"; +import { loadAuthConfig, updateAssistantSlug } from "../../auth/workos.js"; +import { initialize } from "../../config.js"; +import { introMessage } from "../../intro.js"; +import { MCPService } from "../../mcp.js"; +import * as path from "path"; +import * as os from "os"; + +interface ConfigOption { + id: string; + name: string; + type: "local" | "assistant" | "create"; + slug?: string; +} + +interface UseConfigSelectorProps { + configPath?: string; + onAssistantChange: ( + assistant: AssistantUnrolled, + model: string, + llmApi: BaseLlmApi, + mcpService: MCPService + ) => void; + onMessage: (message: { + role: string; + content: string; + messageType: "system"; + }) => void; + onChatReset: () => void; +} + +const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); + +export function useConfigSelector({ + configPath, + onAssistantChange, + onMessage, + onChatReset, +}: UseConfigSelectorProps) { + const [showConfigSelector, setShowConfigSelector] = useState(false); + + const handleConfigSelect = async (config: ConfigOption) => { + setShowConfigSelector(false); + + if (config.type === "create") { + // Open the web browser to create new assistant + const url = "https://hub.continue.dev/new?type=assistant"; + + try { + let command: string; + if (process.platform === "darwin") { + command = `open "${url}"`; + } else if (process.platform === "win32") { + command = `start "${url}"`; + } else { + command = `xdg-open "${url}"`; + } + + exec(command, (error) => { + if (error) { + console.error("Failed to open browser:", error); + } + }); + + onMessage({ + role: "system", + content: `Opening ${url} in your browser to create a new assistant...`, + messageType: "system" as const, + }); + } catch (error) { + onMessage({ + role: "system", + content: `Please visit ${url} to create a new assistant`, + messageType: "system" as const, + }); + } + return; + } + + try { + // Show loading message + onMessage({ + role: "system", + content: `Switching to configuration: ${config.name}...`, + messageType: "system" as const, + }); + + const authConfig = loadAuthConfig(); + let targetConfigPath: string | undefined; + + if (config.type === "local") { + targetConfigPath = CONFIG_PATH; + // Clear assistant slug when switching to local config + updateAssistantSlug(null); + } else if (config.type === "assistant" && config.slug) { + // Use the slug to load the assistant + targetConfigPath = config.slug; + // Save the assistant slug to auth config + updateAssistantSlug(config.slug); + } + + // Reinitialize with the selected configuration + const { + config: newConfig, + llmApi: newLlmApi, + model: newModel, + mcpService: newMcpService, + } = await initialize(authConfig, targetConfigPath); + + // Update assistant configuration + onAssistantChange(newConfig, newModel, newLlmApi, newMcpService); + + // Reset chat history + onChatReset(); + + // Clear the screen completely + process.stdout.write("\x1b[2J\x1b[H"); + + // Show the new intro message + introMessage(newConfig, newModel, newMcpService); + + // Show success message + onMessage({ + role: "system", + content: `Successfully switched to configuration: ${config.name}`, + messageType: "system" as const, + }); + } catch (error: any) { + // Show error message + onMessage({ + role: "system", + content: `Failed to switch configuration: ${error.message}`, + messageType: "system" as const, + }); + } + }; + + const handleConfigCancel = () => { + setShowConfigSelector(false); + }; + + const showConfigSelectorUI = () => { + setShowConfigSelector(true); + }; + + return { + showConfigSelector, + handleConfigSelect, + handleConfigCancel, + showConfigSelectorUI, + }; +} \ No newline at end of file