Add assistant configuration switching with persistent slug storage

This commit is contained in:
Nate 2025-07-16 01:31:52 -07:00
parent 64b02bf8c9
commit b7aec7e0b3
9 changed files with 481 additions and 17 deletions

View file

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

View file

@ -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("~")

View file

@ -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}`);
}

View file

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

200
src/ui/ConfigSelector.tsx Normal file
View file

@ -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<ConfigSelectorProps> = ({
onSelect,
onCancel,
}) => {
const [configs, setConfigs] = useState<ConfigOption[]>([]);
const [selectedIndex, setSelectedIndex] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(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 (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="blue"
>
<Text color="blue" bold>
Configuration Selector
</Text>
<Text color="gray">Loading configurations...</Text>
</Box>
);
}
if (error) {
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="red"
>
<Text color="red" bold>
Error
</Text>
<Text color="red">{error}</Text>
<Text color="gray" dimColor>
Press Escape to cancel
</Text>
</Box>
);
}
return (
<Box
flexDirection="column"
padding={1}
borderStyle="round"
borderColor="blue"
>
<Text color="blue" bold>
Select Configuration
</Text>
<Box flexDirection="column" marginTop={1}>
{configs.map((config, index) => {
const isSelected = index === selectedIndex;
return (
<Box key={config.id}>
<Text
color={isSelected ? "blue" : "white"}
bold={isSelected}
inverse={isSelected}
>
{isSelected ? "▶ " : " "}
{config.name}
{config.type === "local" ? " (local)" : ""}
{config.type === "create" ? " (opens web)" : ""}
{isSelected ? " (current)" : ""}
</Text>
</Box>
);
})}
</Box>
<Box marginTop={1}>
<Text color="gray" dimColor>
Use ↑/↓ to navigate, Enter to select, Escape to cancel
</Text>
</Box>
</Box>
);
};
export default ConfigSelector;

View file

@ -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<TUIChatProps> = ({
initialPrompt,
resume,
onShowOrgSelector: () => showOrganizationSelector(),
onShowConfigSelector: () => showConfigSelectorUI(),
onLoginPrompt: handleLoginPrompt,
});
@ -98,6 +101,25 @@ const TUIChat: React.FC<TUIChatProps> = ({
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 (
<Box flexDirection="column" height="100%">
{/* Chat history - takes up all available space above input */}
@ -148,6 +170,14 @@ const TUIChat: React.FC<TUIChatProps> = ({
/>
)}
{/* Config selector - shows above input when active */}
{showConfigSelector && (
<ConfigSelector
onSelect={handleConfigSelect}
onCancel={handleConfigCancel}
/>
)}
{/* Input area - always at bottom */}
<UserInput
onSubmit={handleUserMessage}
@ -156,7 +186,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
onInterrupt={handleInterrupt}
assistant={assistant}
onFileAttached={handleFileAttached}
disabled={showOrgSelector || !!loginPrompt}
disabled={showOrgSelector || showConfigSelector || !!loginPrompt}
/>
<Box marginRight={2} justifyContent="flex-end">
<Text color="gray">● Continue CLI</Text>

View file

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

View file

@ -22,6 +22,7 @@ interface UseChatProps {
initialPrompt?: string;
resume?: boolean;
onShowOrgSelector: () => void;
onShowConfigSelector: () => void;
onLoginPrompt?: (promptText: string) => Promise<string>;
}
@ -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] : [];

View file

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