org switcher
This commit is contained in:
parent
5e73c07ba9
commit
d192625901
8 changed files with 364 additions and 31 deletions
|
|
@ -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<boolean> {
|
||||
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
|
||||
*/
|
||||
|
|
|
|||
35
src/index.ts
35
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 });
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
156
src/ui/OrganizationSelector.tsx
Normal file
156
src/ui/OrganizationSelector.tsx
Normal file
|
|
@ -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<OrganizationSelectorProps> = ({
|
||||
onSelect,
|
||||
onCancel,
|
||||
}) => {
|
||||
const [organizations, setOrganizations] = 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(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 (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
padding={1}
|
||||
borderStyle="round"
|
||||
borderColor="blue"
|
||||
>
|
||||
<Text color="blue" bold>
|
||||
Organization Selector
|
||||
</Text>
|
||||
<Text color="gray">Loading organizations...</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>
|
||||
);
|
||||
}
|
||||
|
||||
const allOptions = [
|
||||
{ id: null, name: "Personal", isCurrent: currentOrgId === null },
|
||||
...organizations.map((org) => ({
|
||||
...org,
|
||||
isCurrent: currentOrgId === org.id,
|
||||
})),
|
||||
];
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
padding={1}
|
||||
borderStyle="round"
|
||||
borderColor="blue"
|
||||
>
|
||||
<Text color="blue" bold>
|
||||
Select Organization
|
||||
</Text>
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
{allOptions.map((option, index) => {
|
||||
const isSelected = index === selectedIndex;
|
||||
const isCurrent = option.isCurrent;
|
||||
|
||||
return (
|
||||
<Box key={option.id || "personal"}>
|
||||
<Text
|
||||
color={isSelected ? "blue" : "white"}
|
||||
bold={isSelected}
|
||||
inverse={isSelected}
|
||||
>
|
||||
{isSelected ? "▶ " : " "}
|
||||
{option.name}
|
||||
{isCurrent ? " (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 OrganizationSelector;
|
||||
|
|
@ -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<SlashCommandUIProps> = ({
|
|||
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<SlashCommandUIProps> = ({
|
|||
description: "Check who you're currently logged in as",
|
||||
category: "system",
|
||||
},
|
||||
...(hasMultipleOrgs ? [{
|
||||
name: "org",
|
||||
description: "Switch organization",
|
||||
category: "system" as const,
|
||||
}] : []),
|
||||
];
|
||||
|
||||
const assistantCommands: SlashCommand[] =
|
||||
|
|
|
|||
|
|
@ -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<TUIChatProps> = ({
|
||||
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<ChatCompletionMessageParam[]>(
|
||||
() => {
|
||||
let history: ChatCompletionMessageParam[] = [];
|
||||
|
|
@ -85,6 +99,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
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<TUIChatProps> = ({
|
|||
}, [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<TUIChatProps> = ({
|
|||
return;
|
||||
}
|
||||
|
||||
|
||||
// Add command output to messages
|
||||
if (commandResult.output) {
|
||||
setMessages((prev) => [
|
||||
|
|
@ -392,6 +414,82 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
);
|
||||
};
|
||||
|
||||
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 (
|
||||
<Box flexDirection="column" height="100%">
|
||||
{/* Chat history - takes up all available space above input */}
|
||||
|
|
@ -409,6 +507,14 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
</Box>
|
||||
)}
|
||||
|
||||
{/* Organization selector - shows above input when active */}
|
||||
{showOrgSelector && (
|
||||
<OrganizationSelector
|
||||
onSelect={handleOrganizationSelect}
|
||||
onCancel={handleOrganizationCancel}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Input area - always at bottom */}
|
||||
<UserInput
|
||||
onSubmit={handleUserMessage}
|
||||
|
|
@ -417,6 +523,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
onInterrupt={handleInterrupt}
|
||||
assistant={assistant}
|
||||
onFileAttached={handleFileAttached}
|
||||
disabled={showOrgSelector}
|
||||
/>
|
||||
<Box marginRight={2} justifyContent="flex-end">
|
||||
<Text color="gray">● Continue CLI</Text>
|
||||
|
|
|
|||
|
|
@ -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<UserInputProps> = ({
|
||||
|
|
@ -22,6 +24,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
onInterrupt,
|
||||
assistant,
|
||||
onFileAttached,
|
||||
disabled = false,
|
||||
}) => {
|
||||
const [textBuffer] = useState(() => new TextBuffer());
|
||||
const [inputHistory] = useState(() => new InputHistory());
|
||||
|
|
@ -39,6 +42,12 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
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<UserInputProps> = ({
|
|||
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<UserInputProps> = ({
|
|||
};
|
||||
|
||||
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<UserInputProps> = ({
|
|||
}
|
||||
};
|
||||
|
||||
// Don't render anything when disabled
|
||||
if (disabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{/* Input box */}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue