From 440a0c019680bbe10f5ca3c422516ce99c8dce50 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 7 Aug 2025 16:29:29 -0700 Subject: [PATCH 1/4] Update shared-options.ts --- src/shared-options.ts | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/shared-options.ts b/src/shared-options.ts index fb4c9faa6..0de339929 100644 --- a/src/shared-options.ts +++ b/src/shared-options.ts @@ -3,7 +3,10 @@ import { Command } from "commander"; // Function to add common options to any command export function addCommonOptions(command: Command): Command { return command - .option("--config ", "Path to configuration file") + .option( + "--config ", + "Configure the assistant (can be a file path or hub slug)" + ) .option("--readonly", "Start in plan mode (read-only tools)") .option("--auto", "Start in auto mode (all tools allowed)") .option("-v, --verbose", "Enable verbose logging") @@ -56,22 +59,25 @@ export function mergeParentOptions(parentCommand: Command, options: any): any { // List of options to inherit from parent if not present in subcommand const inheritableOptions = [ - 'config', - 'readonly', - 'auto', - 'tools', - 'verbose', - 'rule', - 'allow', - 'ask', - 'exclude' + "config", + "readonly", + "auto", + "tools", + "verbose", + "rule", + "allow", + "ask", + "exclude", ]; for (const optName of inheritableOptions) { - if (parentOpts[optName] !== undefined && mergedOptions[optName] === undefined) { + if ( + parentOpts[optName] !== undefined && + mergedOptions[optName] === undefined + ) { mergedOptions[optName] = parentOpts[optName]; } } return mergedOptions; -} \ No newline at end of file +} From 67813ec5f2b920e1406bcf62cbcf2750b2509d25 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 7 Aug 2025 16:30:09 -0700 Subject: [PATCH 2/4] Update shared-options.ts --- src/shared-options.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared-options.ts b/src/shared-options.ts index 0de339929..bf29e6928 100644 --- a/src/shared-options.ts +++ b/src/shared-options.ts @@ -5,7 +5,7 @@ export function addCommonOptions(command: Command): Command { return command .option( "--config ", - "Configure the assistant (can be a file path or hub slug)" + "Configure the assistant (can be a file path or hub slug)" ) .option("--readonly", "Start in plan mode (read-only tools)") .option("--auto", "Start in auto mode (all tools allowed)") From 45a3de00e7bdb2538425d606506538fe76fa2d39 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Mon, 11 Aug 2025 17:31:52 -0700 Subject: [PATCH 3/4] improv: eslint config (#163) * improv: eslint config * chore: temporarily disable rules * fix: negated conditions * improv: disable linting when testing * fix: too many parameters errors * fix: complexity errors * fix: complexity * fix: complexity * fix: complexity * fix: complexity * fix: unused imports * fix: imports * fix: complexity * fix: complexity * fix: linter errors * fix: complexity * fix: linter errors * fix: linter errors * fix: complexity * fix: linter errors * fix: linter errors * fix: complexity * fix: imports * fix: complexity * fix: complexity * fix: type errors * fix: lint * fix: lint * fix: file length * fix: lint * fix: failing tests * fix: prettier --- eslint.config.js | 81 ++- package.json | 2 +- src/__mocks__/auth/uriUtils.ts | 6 + src/__mocks__/auth/workos.ts | 4 - src/auth/uriUtils.ts | 25 + src/auth/workos.helpers.ts | 164 ++++++ src/auth/workos.test.ts | 2 +- src/auth/workos.ts | 170 +----- src/commands/chat.ts | 278 +++++---- src/commands/serve.ts | 6 +- src/compaction.ts | 5 +- src/configLoader.ts | 11 +- src/permissions/policyWriter.ts | 6 +- src/services/ModelService.refactored.ts | 10 +- src/services/ModelService.ts | 10 +- src/services/index.ts | 11 +- src/session.ts | 38 +- src/slashCommands.ts | 394 +++++++------ src/streamChatResponse.helpers.ts | 451 +++++++++++++++ src/streamChatResponse.test.ts | 84 +-- src/streamChatResponse.ts | 719 ++++++++---------------- src/streamChatResponse.types.ts | 31 + src/telemetry/telemetryService.ts | 67 +-- src/tools/index.ts | 31 +- src/tools/multiEdit.ts | 178 +++--- src/ui/ColoredDiff.tsx | 37 +- src/ui/FreeTrialTransitionUI.tsx | 107 +++- src/ui/SyntaxHighlighter.ts | 24 +- src/ui/TUIChat.tsx | 602 +++++++++++++------- src/ui/TextBuffer.ts | 161 +++--- src/ui/UpdateNotification.test.tsx | 6 +- src/ui/UserInput.tsx | 413 +++++++------- src/ui/components/ToolPreview.tsx | 2 +- src/ui/hooks/useChat.helpers.ts | 357 ++++++++++++ src/ui/hooks/useChat.remote.helpers.ts | 269 +++++++++ src/ui/hooks/useChat.stream.helpers.ts | 171 ++++++ src/ui/hooks/useChat.ts | 707 ++++------------------- src/ui/hooks/useChat.types.ts | 60 ++ src/ui/hooks/useUserInput.ts | 66 +++ src/ui/index.ts | 29 +- 40 files changed, 3470 insertions(+), 2325 deletions(-) create mode 100644 src/__mocks__/auth/uriUtils.ts create mode 100644 src/auth/uriUtils.ts create mode 100644 src/auth/workos.helpers.ts create mode 100644 src/streamChatResponse.helpers.ts create mode 100644 src/streamChatResponse.types.ts create mode 100644 src/ui/hooks/useChat.helpers.ts create mode 100644 src/ui/hooks/useChat.remote.helpers.ts create mode 100644 src/ui/hooks/useChat.stream.helpers.ts create mode 100644 src/ui/hooks/useChat.types.ts create mode 100644 src/ui/hooks/useUserInput.ts diff --git a/eslint.config.js b/eslint.config.js index da7a3556d..1481e9d99 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -23,9 +23,66 @@ export default [ // Core rules - all as errors "max-classes-per-file": ["error", 1], "prefer-const": "error", + // "class-methods-use-this": [ + // "error", + // { + // exceptMethods: [ + // "render", + // "shouldComponentUpdate", + // "componentDidMount", + // "componentDidUpdate", + // "componentWillUnmount", + // ], + // }, + // ], + "no-negated-condition": "error", + "max-lines": [ + "error", + { max: 500, skipBlankLines: true, skipComments: true }, + ], + complexity: ["error", { max: 20 }], + // "max-lines-per-function": [ + // "error", + // { max: 150, skipBlankLines: true, skipComments: true }, + // ], + "max-statements": ["error", { max: 50 }], + "max-depth": ["error", { max: 4 }], + "max-nested-callbacks": ["error", { max: 3 }], + "max-params": ["error", { max: 5 }], + eqeqeq: "error", // TypeScript specific rules - "@typescript-eslint/no-floating-promises": "off", + // "@typescript-eslint/no-floating-promises": "error", + "@typescript-eslint/no-explicit-any": "error", + // "@typescript-eslint/member-ordering": [ + // "error", + // { + // default: [ + // // Static fields + // "public-static-field", + // "protected-static-field", + // "private-static-field", + + // // Instance fields + // "public-instance-field", + // "protected-instance-field", + // "private-instance-field", + + // // Constructors + // "constructor", + + // // Static methods + // "public-static-method", + // "protected-static-method", + // "private-static-method", + + // // Instance methods + // "public-instance-method", + // "protected-instance-method", + // "private-instance-method", + // ], + // }, + // ], // Import rules "import/order": [ @@ -62,7 +119,7 @@ export default [ }, ], - // Turn off rules that might be too strict + // Turn off rules that might be too strict for CLI "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/explicit-function-return-type": "off", "@typescript-eslint/explicit-module-boundary-types": "off", @@ -89,11 +146,29 @@ export default [ }, { // Test files can have different rules - files: ["**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx"], + files: [ + "**/*.test.ts", + "**/*.test.tsx", + "**/*.spec.ts", + "**/*.spec.tsx", + "**/test-helpers/**/*.ts", + "**/test-helpers/**/*.tsx", + "**/__tests__/**/*.ts", + "**/__tests__/**/*.tsx", + "**/__mocks__/**/*.ts", + "**/__mocks__/**/*.tsx", + ], rules: { "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-floating-promises": "off", "unused-imports/no-unused-vars": "off", "max-classes-per-file": "off", + "max-lines": "off", + "max-lines-per-function": "off", + "max-statements": "off", + complexity: "off", + "class-methods-use-this": "off", + "max-nested-callbacks": "off", }, }, { diff --git a/package.json b/package.json index 241801616..f4e77a052 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "cn": "dist/index.js" }, "scripts": { - "test": "npm run lint && vitest run", + "test": "vitest run", "test:watch": "vitest watch", "test:ui": "vitest --ui", "build": "tsc -p tsconfig.build.json", diff --git a/src/__mocks__/auth/uriUtils.ts b/src/__mocks__/auth/uriUtils.ts new file mode 100644 index 000000000..fed34135f --- /dev/null +++ b/src/__mocks__/auth/uriUtils.ts @@ -0,0 +1,6 @@ +import { vi } from "vitest"; + +export const pathToUri = vi.fn((path: string) => path); +export const slugToUri = vi.fn((slug: string) => slug); +export const uriToPath = vi.fn(() => null); +export const uriToSlug = vi.fn(() => null); diff --git a/src/__mocks__/auth/workos.ts b/src/__mocks__/auth/workos.ts index 54fbfdfb7..f77d87462 100644 --- a/src/__mocks__/auth/workos.ts +++ b/src/__mocks__/auth/workos.ts @@ -18,10 +18,6 @@ export const getAccessToken = vi.fn(() => null); export const getConfigUri = vi.fn(() => null); export const getAssistantSlug = vi.fn(() => null); export const getLocalConfigPath = vi.fn(() => null); -export const pathToUri = vi.fn((path: string) => path); -export const slugToUri = vi.fn((slug: string) => slug); -export const uriToPath = vi.fn(() => null); -export const uriToSlug = vi.fn(() => null); export const updateConfigUri = vi.fn(); export const updateModelName = vi.fn(); export const updateAssistantSlug = vi.fn(); diff --git a/src/auth/uriUtils.ts b/src/auth/uriUtils.ts new file mode 100644 index 000000000..832c01298 --- /dev/null +++ b/src/auth/uriUtils.ts @@ -0,0 +1,25 @@ +/** + * URI utility functions for auth config + */ + +export function pathToUri(path: string): string { + return `file://${path}`; +} + +export function slugToUri(slug: string): string { + return `slug://${slug}`; +} + +export function uriToPath(uri: string): string | null { + if (!uri.startsWith("file://")) { + return null; + } + return uri.slice(7); +} + +export function uriToSlug(uri: string): string | null { + if (!uri.startsWith("slug://")) { + return null; + } + return uri.slice(7); +} diff --git a/src/auth/workos.helpers.ts b/src/auth/workos.helpers.ts new file mode 100644 index 000000000..67dac76c9 --- /dev/null +++ b/src/auth/workos.helpers.ts @@ -0,0 +1,164 @@ +import chalk from "chalk"; + +import { getApiClient } from "../config.js"; + +import type { + AuthConfig, + AuthenticatedConfig, + EnvironmentAuthConfig, +} from "./workos.js"; +import { saveAuthConfig } from "./workos.js"; + +/** + * Creates an updated AuthenticatedConfig with a new organization ID + */ +export function createUpdatedAuthConfig( + config: AuthenticatedConfig, + organizationId: string | null, +): AuthenticatedConfig { + return { + userId: config.userId, + userEmail: config.userEmail, + accessToken: config.accessToken, + refreshToken: config.refreshToken, + expiresAt: config.expiresAt, + organizationId, + configUri: config.configUri, + modelName: config.modelName, + }; +} + +/** + * Helper function to resolve organization by slug + */ +export async function resolveOrganizationBySlug( + apiClient: ReturnType, + organizationSlug: string, +): Promise<{ id: string; slug: string }> { + const resp = await apiClient.listOrganizations(); + const organizations = resp.organizations; + + // Find organization by slug (case-insensitive) + const matchedOrg = organizations.find( + (org) => org?.slug?.toLowerCase() === organizationSlug.toLowerCase(), + ); + + if (matchedOrg) { + return { id: matchedOrg.id, slug: matchedOrg.slug }; + } else { + // Organization not found - show available options + const availableSlugs = organizations + .map((org) => org?.slug) + .filter(Boolean); + const availableOptions = ["personal", ...availableSlugs]; + console.info( + chalk.yellow("Available organizations:"), + availableOptions.join(", "), + ); + + throw new Error(`Organization "${organizationSlug}" not found`); + } +} + +/** + * Handle CLI organization flag for environment auth configs + */ +export async function handleCliOrgForEnvironmentAuth( + authConfig: EnvironmentAuthConfig, + cliOrganizationSlug: string, + isHeadless: boolean, +): Promise { + // Only allow --org flag in headless mode + if (!isHeadless) { + console.error( + chalk.red( + "The --org flag is only supported in headless mode (with -p/--print flag)", + ), + ); + process.exit(1); + } + + const apiClient = getApiClient(authConfig.accessToken); + const resolvedOrg = await resolveOrganizationBySlug( + apiClient, + cliOrganizationSlug, + ); + + // Return modified environment auth config with organization ID + return { + ...authConfig, + organizationId: resolvedOrg.id, + }; +} + +/** + * Handle CLI organization flag for authenticated configs + */ +export async function handleCliOrgForAuthenticatedConfig( + authenticatedConfig: AuthenticatedConfig, + cliOrganizationSlug: string, + isHeadless: boolean, +): Promise { + // Only allow --org flag in headless mode + if (!isHeadless) { + console.error( + chalk.red( + "The --org flag is only supported in headless mode (with -p/--print flag)", + ), + ); + process.exit(1); + } + + const apiClient = getApiClient(authenticatedConfig.accessToken); + const resolvedOrg = await resolveOrganizationBySlug( + apiClient, + cliOrganizationSlug, + ); + + const updatedConfig = createUpdatedAuthConfig( + authenticatedConfig, + resolvedOrg.id, + ); + saveAuthConfig(updatedConfig); + return updatedConfig; +} + +/** + * Automatically select organization for authenticated config + */ +export async function autoSelectOrganization( + authenticatedConfig: AuthenticatedConfig, +): Promise { + const apiClient = getApiClient(authenticatedConfig.accessToken); + + try { + const resp = await apiClient.listOrganizations(); + const organizations = resp.organizations; + + if (organizations.length === 0) { + const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); + saveAuthConfig(updatedConfig); + return updatedConfig; + } + + // Automatically select the first organization if available + const selectedOrg = organizations[0]; + const selectedOrgId = selectedOrg.id; + + const updatedConfig = createUpdatedAuthConfig( + authenticatedConfig, + selectedOrgId, + ); + saveAuthConfig(updatedConfig); + return updatedConfig; + } catch (error: any) { + console.error( + chalk.red("Error fetching organizations:"), + error.response?.data?.message || error.message || error, + ); + console.info(chalk.yellow("Continuing without organization selection.")); + const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); + saveAuthConfig(updatedConfig); + return updatedConfig; + } +} diff --git a/src/auth/workos.test.ts b/src/auth/workos.test.ts index 3a3fd72f8..22e13642b 100644 --- a/src/auth/workos.test.ts +++ b/src/auth/workos.test.ts @@ -1,3 +1,4 @@ +import { slugToUri } from "./uriUtils.js"; import { AuthenticatedConfig, EnvironmentAuthConfig, @@ -6,7 +7,6 @@ import { getOrganizationId, isAuthenticatedConfig, isEnvironmentAuthConfig, - slugToUri, } from "./workos.js"; describe("workos utility functions", () => { diff --git a/src/auth/workos.ts b/src/auth/workos.ts index 56a4aec0e..8ae14c25f 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -95,30 +95,14 @@ export function getModelName(config: AuthConfig): string | null { return config.modelName || null; } -/** - * Utility functions for config URI conversion - */ -export function pathToUri(path: string): string { - return `file://${path}`; -} - -export function slugToUri(slug: string): string { - return `slug://${slug}`; -} - -export function uriToPath(uri: string): string | null { - if (uri.startsWith("file://")) { - return uri.slice(7); - } - return null; -} - -export function uriToSlug(uri: string): string | null { - if (uri.startsWith("slug://")) { - return uri.slice(7); // Remove 'slug://' prefix - } - return null; -} +// URI utility functions have been moved to ./uriUtils.ts +import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js"; +import { + autoSelectOrganization, + createUpdatedAuthConfig, + handleCliOrgForAuthenticatedConfig, + handleCliOrgForEnvironmentAuth, +} from "./workos.helpers.js"; /** * Legacy functions for backward compatibility @@ -537,38 +521,6 @@ export async function login(): Promise { return authConfig; } -/** - * Helper function to resolve organization by slug - */ -async function resolveOrganizationBySlug( - apiClient: ReturnType, - organizationSlug: string, -): Promise<{ id: string; slug: string }> { - const resp = await apiClient.listOrganizations(); - const organizations = resp.organizations; - - // Find organization by slug (case-insensitive) - const matchedOrg = organizations.find( - (org) => org?.slug?.toLowerCase() === organizationSlug.toLowerCase(), - ); - - if (matchedOrg) { - return { id: matchedOrg.id, slug: matchedOrg.slug }; - } else { - // Organization not found - show available options - const availableSlugs = organizations - .map((org) => org?.slug) - .filter(Boolean); - const availableOptions = ["personal", ...availableSlugs]; - console.info( - chalk.yellow("Available organizations:"), - availableOptions.join(", "), - ); - - throw new Error(`Organization "${organizationSlug}" not found`); - } -} - /** * Ensures the user has selected an organization, automatically selecting the first one if available */ @@ -579,30 +531,13 @@ export async function ensureOrganization( ): Promise { // Handle CLI organization slug if provided (undefined means no --org flag or --org personal) if (cliOrganizationSlug) { - // Only allow --org flag in headless mode - if (!isHeadless) { - console.error( - chalk.red( - "The --org flag is only supported in headless mode (with -p/--print flag)", - ), - ); - process.exit(1); - } - // For environment auth configs if (isEnvironmentAuthConfig(authConfig)) { - const apiClient = getApiClient(authConfig.accessToken); - - const resolvedOrg = await resolveOrganizationBySlug( - apiClient, + return handleCliOrgForEnvironmentAuth( + authConfig, cliOrganizationSlug, + isHeadless, ); - - // Return modified environment auth config with organization ID - return { - ...authConfig, - organizationId: resolvedOrg.id, - }; } } else if (isEnvironmentAuthConfig(authConfig)) { // No CLI organization slug (or "personal" was specified) - return as-is @@ -619,19 +554,11 @@ export async function ensureOrganization( // If a CLI organization slug is provided, try to use it (for authenticated configs) if (cliOrganizationSlug) { - const apiClient = getApiClient(authenticatedConfig.accessToken); - - const resolvedOrg = await resolveOrganizationBySlug( - apiClient, + return handleCliOrgForAuthenticatedConfig( + authenticatedConfig, cliOrganizationSlug, + isHeadless, ); - - const updatedConfig: AuthenticatedConfig = { - ...authenticatedConfig, - organizationId: resolvedOrg.id, - }; - saveAuthConfig(updatedConfig); - return updatedConfig; } // If already have organization ID (including null for personal), return as-is @@ -641,78 +568,13 @@ export async function ensureOrganization( // In headless mode, default to personal organization if none saved if (isHeadless) { - const updatedConfig: AuthenticatedConfig = { - userId: authenticatedConfig.userId, - userEmail: authenticatedConfig.userEmail, - accessToken: authenticatedConfig.accessToken, - refreshToken: authenticatedConfig.refreshToken, - expiresAt: authenticatedConfig.expiresAt, - organizationId: null, // Default to personal organization - configUri: authenticatedConfig.configUri, - modelName: authenticatedConfig.modelName, - }; + const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null); saveAuthConfig(updatedConfig); return updatedConfig; } // Need to select organization - const apiClient = getApiClient(authenticatedConfig.accessToken); - - try { - const resp = await apiClient.listOrganizations(); - const organizations = resp.organizations; - - if (organizations.length === 0) { - const updatedConfig: AuthenticatedConfig = { - userId: authenticatedConfig.userId, - userEmail: authenticatedConfig.userEmail, - accessToken: authenticatedConfig.accessToken, - refreshToken: authenticatedConfig.refreshToken, - expiresAt: authenticatedConfig.expiresAt, - organizationId: null, - configUri: authenticatedConfig.configUri, - modelName: authenticatedConfig.modelName, - }; - saveAuthConfig(updatedConfig); - return updatedConfig; - } - - // Automatically select the first organization if available, otherwise use personal - const selectedOrg = organizations[0]; - const selectedOrgId = selectedOrg.id; - - const updatedConfig: AuthenticatedConfig = { - userId: authenticatedConfig.userId, - userEmail: authenticatedConfig.userEmail, - accessToken: authenticatedConfig.accessToken, - refreshToken: authenticatedConfig.refreshToken, - expiresAt: authenticatedConfig.expiresAt, - organizationId: selectedOrgId, - configUri: authenticatedConfig.configUri, - modelName: authenticatedConfig.modelName, - }; - - saveAuthConfig(updatedConfig); - return updatedConfig; - } catch (error: any) { - console.error( - chalk.red("Error fetching organizations:"), - error.response?.data?.message || error.message || error, - ); - console.info(chalk.yellow("Continuing without organization selection.")); - const updatedConfig: AuthenticatedConfig = { - userId: authenticatedConfig.userId, - userEmail: authenticatedConfig.userEmail, - accessToken: authenticatedConfig.accessToken, - refreshToken: authenticatedConfig.refreshToken, - expiresAt: authenticatedConfig.expiresAt, - organizationId: null, - configUri: authenticatedConfig.configUri, - modelName: authenticatedConfig.modelName, - }; - saveAuthConfig(updatedConfig); - return updatedConfig; - } + return autoSelectOrganization(authenticatedConfig); } /** diff --git a/src/commands/chat.ts b/src/commands/chat.ts index f2743987b..ac3ee2487 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -118,56 +118,147 @@ export async function initializeChatHistory( return chatHistory; } -async function processMessage( - userInput: string, +// Helper function to handle manual compaction +async function handleManualCompaction( + chatHistory: ChatCompletionMessageParam[], + model: ModelConfig, + llmApi: any, + isHeadless: boolean, +): Promise<{ compactionIndex?: number | null } | void> { + if (!isHeadless) { + console.info(chalk.yellow("Compacting chat history...")); + } + + try { + const result = await compactChatHistory(chatHistory, model, llmApi); + + // Replace chat history with compacted version + chatHistory.length = 0; + chatHistory.push(...result.compactedHistory); + + // Save the compacted session + saveSession(chatHistory); + + if (isHeadless) { + safeStdout( + JSON.stringify({ + status: "success", + message: "Chat history compacted", + historyLength: chatHistory.length, + }) + "\n", + ); + } else { + console.info(chalk.green("Chat history compacted successfully.")); + } + + return { compactionIndex: result.compactionIndex }; + } catch (error) { + const errorMsg = `Compaction error: ${formatError(error)}`; + if (isHeadless) { + safeStdout(JSON.stringify({ status: "error", message: errorMsg }) + "\n"); + } else { + console.error(chalk.red(errorMsg)); + } + return; + } +} + +// Helper function to handle auto-compaction +async function handleAutoCompaction( chatHistory: ChatCompletionMessageParam[], model: ModelConfig, llmApi: any, isHeadless: boolean, format?: "json", - silent?: boolean, - compactionIndex?: number | null, +): Promise { + logger.info("Auto-compacting triggered due to context limit"); + + if (!isHeadless) { + console.info( + chalk.yellow( + "\nApproaching context limit. Auto-compacting chat history...", + ), + ); + } else if (format === "json") { + safeStdout( + JSON.stringify({ + status: "info", + message: "Auto-compacting triggered", + contextUsage: + calculateContextUsagePercentage( + countChatHistoryTokens(chatHistory), + model, + ) + "%", + }) + "\n", + ); + } + + try { + const result = await compactChatHistory(chatHistory, model, llmApi); + chatHistory.length = 0; + chatHistory.push(...result.compactedHistory); + saveSession(chatHistory); + + if (!isHeadless) { + console.info(chalk.green("✓ Chat history auto-compacted successfully.")); + } else if (format === "json") { + safeStdout( + JSON.stringify({ + status: "success", + message: "Auto-compacted successfully", + historyLength: chatHistory.length, + }) + "\n", + ); + } + + return result.compactionIndex; + } catch (error) { + const errorMsg = `Auto-compaction error: ${formatError(error)}`; + logger.error(errorMsg); + + if (!isHeadless) { + console.error(chalk.red(`Warning: ${errorMsg}`)); + console.info(chalk.yellow("Continuing without compaction...")); + } else if (format === "json") { + safeStdout( + JSON.stringify({ + status: "warning", + message: "Auto-compaction failed, continuing without compaction", + }) + "\n", + ); + } + return null; + } +} + +interface ProcessMessageOptions { + userInput: string; + chatHistory: ChatCompletionMessageParam[]; + model: ModelConfig; + llmApi: any; + isHeadless: boolean; + format?: "json"; + silent?: boolean; + compactionIndex?: number | null; +} + +async function processMessage( + options: ProcessMessageOptions, ): Promise<{ compactionIndex?: number | null } | void> { + const { + userInput, + chatHistory, + model, + llmApi, + isHeadless, + format, + silent, + compactionIndex: initialCompactionIndex, + } = options; + let compactionIndex = initialCompactionIndex; // Check for slash commands in headless mode if (userInput.trim() === "/compact") { - if (!isHeadless) { - console.info(chalk.yellow("Compacting chat history...")); - } - - try { - const result = await compactChatHistory(chatHistory, model, llmApi); - - // Replace chat history with compacted version - chatHistory.length = 0; - chatHistory.push(...result.compactedHistory); - - // Save the compacted session - saveSession(chatHistory); - - if (!isHeadless) { - console.info(chalk.green("Chat history compacted successfully.")); - } else { - safeStdout( - JSON.stringify({ - status: "success", - message: "Chat history compacted", - historyLength: chatHistory.length, - }) + "\n", - ); - } - - return { compactionIndex: result.compactionIndex }; - } catch (error) { - const errorMsg = `Compaction error: ${formatError(error)}`; - if (!isHeadless) { - console.error(chalk.red(errorMsg)); - } else { - safeStdout( - JSON.stringify({ status: "error", message: errorMsg }) + "\n", - ); - } - return; - } + return handleManualCompaction(chatHistory, model, llmApi, isHeadless); } // Track user prompt @@ -175,72 +266,15 @@ async function processMessage( // Check if auto-compacting is needed BEFORE adding user message if (shouldAutoCompact(chatHistory, model)) { - logger.info("Auto-compacting triggered due to context limit"); - - if (!isHeadless) { - console.info( - chalk.yellow( - "\nApproaching context limit. Auto-compacting chat history...", - ), - ); - } else if (format === "json") { - safeStdout( - JSON.stringify({ - status: "info", - message: "Auto-compacting triggered", - contextUsage: - calculateContextUsagePercentage( - countChatHistoryTokens(chatHistory), - model, - ) + "%", - }) + "\n", - ); - } - - try { - // Compact the history WITHOUT the current user message - const result = await compactChatHistory(chatHistory, model, llmApi); - - // Replace chat history with compacted version - chatHistory.length = 0; - chatHistory.push(...result.compactedHistory); - - // Save the compacted session - saveSession(chatHistory); - - if (!isHeadless) { - console.info( - chalk.green("✓ Chat history auto-compacted successfully."), - ); - } else if (format === "json") { - safeStdout( - JSON.stringify({ - status: "success", - message: "Auto-compacted successfully", - historyLength: chatHistory.length, - }) + "\n", - ); - } - - // Update compaction index - compactionIndex = result.compactionIndex; - } catch (error) { - const errorMsg = `Auto-compaction error: ${formatError(error)}`; - logger.error(errorMsg); - - if (!isHeadless) { - console.error(chalk.red(`Warning: ${errorMsg}`)); - console.info(chalk.yellow("Continuing without compaction...")); - } else if (format === "json") { - safeStdout( - JSON.stringify({ - status: "warning", - message: "Auto-compaction failed, continuing without compaction", - }) + "\n", - ); - } - - // Continue without compaction on error + const newIndex = await handleAutoCompaction( + chatHistory, + model, + llmApi, + isHeadless, + format, + ); + if (newIndex !== null) { + compactionIndex = newIndex; } } @@ -373,16 +407,16 @@ async function runHeadlessMode( isFirstMessage = false; - const result = await processMessage( + const result = await processMessage({ userInput, chatHistory, model, llmApi, - true, - options.format, - options.silent, + isHeadless: true, + format: options.format, + silent: options.silent, compactionIndex, - ); + }); // Update compaction index if compaction occurred if (result && result.compactionIndex !== undefined) { @@ -429,15 +463,15 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { console.log(CONTINUE_ASCII_ART); // Start TUI with skipOnboarding since we already handled it - await startTUIChat( - prompt, - options.resume, - options.config, - options.org, - options.rule, - permissionOverrides, - true, - ); + await startTUIChat({ + initialPrompt: prompt, + resume: options.resume, + configPath: options.config, + organizationSlug: options.org, + additionalRules: options.rule, + toolPermissionOverrides: permissionOverrides, + skipOnboarding: true, + }); return; } diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 6cf428e22..073aafcbb 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -20,10 +20,8 @@ import { ModelServiceState, } from "../services/types.js"; import { saveSession } from "../session.js"; -import { - streamChatResponse, - type StreamCallbacks, -} from "../streamChatResponse.js"; +import { streamChatResponse } from "../streamChatResponse.js"; +import { StreamCallbacks } from "../streamChatResponse.types.js"; import { constructSystemMessage } from "../systemMessage.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { getToolDisplayName } from "../tools/index.js"; diff --git a/src/compaction.ts b/src/compaction.ts index 1034644b3..c60f814a7 100644 --- a/src/compaction.ts +++ b/src/compaction.ts @@ -2,7 +2,8 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; -import { StreamCallbacks, streamChatResponse } from "./streamChatResponse.js"; +import { streamChatResponse } from "./streamChatResponse.js"; +import { StreamCallbacks } from "./streamChatResponse.types.js"; import { logger } from "./util/logger.js"; export const COMPACTION_MARKER = "[COMPACTED HISTORY]"; @@ -111,7 +112,7 @@ export function findCompactionIndex( typeof msg.content === "string" && msg.content.startsWith(COMPACTION_MARKER), ); - return compactedIndex !== -1 ? compactedIndex : null; + return compactedIndex === -1 ? null : compactedIndex; } /** diff --git a/src/configLoader.ts b/src/configLoader.ts index 48692471e..44035b940 100644 --- a/src/configLoader.ts +++ b/src/configLoader.ts @@ -11,6 +11,7 @@ import { import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; +import { uriToPath, uriToSlug } from "./auth/uriUtils.js"; import { AuthConfig, getAccessToken, @@ -18,8 +19,6 @@ import { getOrganizationId, isEnvironmentAuthConfig, updateConfigUri, - uriToPath, - uriToSlug, } from "./auth/workos.js"; import { CLIPlatformClient } from "./CLIPlatformClient.js"; import { env } from "./env.js"; @@ -94,16 +93,16 @@ function determineConfigSource( } // Priority 3: Default resolution based on auth state - if (authConfig !== null) { - // Authenticated: try user assistants first - return { type: "user-assistant", slug: "" }; // Empty slug means "first available" - } else { + if (authConfig === null) { // Unauthenticated: check for default config.yaml, then fallback to default agent const defaultConfigPath = path.join(env.continueHome, "config.yaml"); if (fs.existsSync(defaultConfigPath)) { return { type: "default-config-yaml" }; } return { type: "default-agent" }; + } else { + // Authenticated: try user assistants first + return { type: "user-assistant", slug: "" }; // Empty slug means "first available" } } diff --git a/src/permissions/policyWriter.ts b/src/permissions/policyWriter.ts index 2aec69746..adda2688f 100644 --- a/src/permissions/policyWriter.ts +++ b/src/permissions/policyWriter.ts @@ -48,7 +48,9 @@ export async function addPolicyToYaml(policyRule: string): Promise { } // Add the policy if it doesn't already exist - if (!config.allow.includes(policyRule)) { + if (config.allow.includes(policyRule)) { + logger.debug(`Policy rule already exists: ${policyRule}`); + } else { config.allow.push(policyRule); // Write the updated config back to the file @@ -63,8 +65,6 @@ ${yamlContent}`; await fs.promises.writeFile(PERMISSIONS_YAML_PATH, finalContent, "utf-8"); logger.info(`Added policy rule to permissions.yaml: ${policyRule}`); - } else { - logger.debug(`Policy rule already exists: ${policyRule}`); } } catch (error) { logger.error("Failed to add policy to permissions.yaml", { diff --git a/src/services/ModelService.refactored.ts b/src/services/ModelService.refactored.ts index 9a4b5d4c9..694d32d34 100644 --- a/src/services/ModelService.refactored.ts +++ b/src/services/ModelService.refactored.ts @@ -56,17 +56,17 @@ export class ModelService const persistedModelName = getModelName(authConfig); if (persistedModelName) { const modelIndex = this.getModelIndexByName(persistedModelName); - if (modelIndex !== -1) { - // Use the persisted model - const state = await this.switchModel(modelIndex); - return state; - } else { + if (modelIndex === -1) { // Model name not found, use default model selection const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, model, }; + } else { + // Use the persisted model + const state = await this.switchModel(modelIndex); + return state; } } else { // Use default model selection diff --git a/src/services/ModelService.ts b/src/services/ModelService.ts index 66465e129..0ba08d6d4 100644 --- a/src/services/ModelService.ts +++ b/src/services/ModelService.ts @@ -56,17 +56,17 @@ export class ModelService const persistedModelName = getModelName(authConfig); if (persistedModelName) { const modelIndex = this.getModelIndexByName(persistedModelName); - if (modelIndex !== -1) { - // Use the persisted model - const state = await this.switchModel(modelIndex); - return state; - } else { + if (modelIndex === -1) { // Model name not found, use default model selection const [llmApi, model] = getLlmApi(assistant, authConfig); return { llmApi, model, }; + } else { + // Use the persisted model + const state = await this.switchModel(modelIndex); + return state; } } else { // Use default model selection diff --git a/src/services/index.ts b/src/services/index.ts index 258040042..833459ec1 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -152,15 +152,14 @@ export async function initializeServices( const currentState = configService.getState(); let configPath = options.configPath || - (currentState.configPath !== undefined - ? currentState.configPath - : undefined); + (currentState.configPath === undefined + ? undefined + : currentState.configPath); // If no config path is available, check for saved config URI in auth config if (!configPath) { - const { getConfigUri, uriToPath, uriToSlug } = await import( - "../auth/workos.js" - ); + const { getConfigUri } = await import("../auth/workos.js"); + const { uriToPath, uriToSlug } = await import("../auth/uriUtils.js"); const configUri = getConfigUri(finalAuthState.authConfig); if (configUri) { const filePath = uriToPath(configUri); diff --git a/src/session.ts b/src/session.ts index 4a2e92010..b75417dff 100644 --- a/src/session.ts +++ b/src/session.ts @@ -7,6 +7,28 @@ import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { logger } from "./util/logger.js"; +// List of known terminal process names +const TERMINAL_PROCESSES = [ + "Terminal", + "iTerm", + "tmux", + "screen", + "bash", + "zsh", + "fish", + "kitty", + "alacritty", + "wt", // Windows Terminal + "cmd", // Windows Command Prompt + "powershell", +]; + +// Check if a process name looks like a terminal +function isTerminalProcess(comm: string): boolean { + if (!comm) return false; + return TERMINAL_PROCESSES.some((term) => comm.includes(term)); +} + /** * Get the terminal process ID by walking up the process tree */ @@ -35,21 +57,7 @@ function getTerminalProcessId(): string | null { const [pid, ppid, comm] = processInfo; // Check if this looks like a terminal process - if ( - comm && - (comm.includes("Terminal") || - comm.includes("iTerm") || - comm.includes("tmux") || - comm.includes("screen") || - comm.includes("bash") || - comm.includes("zsh") || - comm.includes("fish") || - comm.includes("kitty") || - comm.includes("alacritty") || - comm.includes("wt") || // Windows Terminal - comm.includes("cmd") || // Windows Command Prompt - comm.includes("powershell")) - ) { + if (isTerminalProcess(comm)) { return pid; } diff --git a/src/slashCommands.ts b/src/slashCommands.ts index 360a48185..e86b45b8f 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -10,6 +10,196 @@ import { getAllSlashCommands } from "./commands/commands.js"; import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; import { posthogService } from "./telemetry/posthogService.js"; +interface SlashCommandResult { + exit?: boolean; + output?: string; + model?: boolean; + compact?: boolean; +} + +// Helper function to handle org list command +async function handleOrgList(services: any): Promise { + 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 { + 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, +) => Promise | any; + +async function handleHelp(args: string[], assistant: AssistantConfig) { + const allCommands = getAllSlashCommands(assistant); + const helpMessage = [ + chalk.cyan("Slash commands:"), + ...allCommands.map( + (cmd) => + `- ${chalk.white(`/${cmd.name}:`)} ${chalk.gray(cmd.description)}`, + ), + ].join("\n"); + posthogService.capture("useSlashCommand", { name: "help" }); + return { output: helpMessage }; +} + +async function handleLogin() { + posthogService.capture("useSlashCommand", { name: "login" }); + try { + const newAuthState = await services.auth.login(); + await reloadService(SERVICE_NAMES.AUTH); + + const userInfo = + newAuthState.authConfig && isAuthenticatedConfig(newAuthState.authConfig) + ? newAuthState.authConfig.userEmail || newAuthState.authConfig.userId + : "user"; + + console.info(chalk.green(`\nLogged in as ${userInfo}`)); + + return { + exit: false, + output: "Login successful! All services updated automatically.", + }; + } catch (error: any) { + console.error(chalk.red(`\nLogin failed: ${error.message}`)); + return { + exit: false, + output: `Login failed: ${error.message}`, + }; + } +} + +async function handleLogout() { + posthogService.capture("useSlashCommand", { name: "logout" }); + try { + await services.auth.logout(); + return { + exit: true, + output: "Logged out successfully", + }; + } catch { + return { + exit: true, + output: "Logged out successfully", + }; + } +} + +function handleWhoami() { + posthogService.capture("useSlashCommand", { name: "whoami" }); + if (isAuthenticated()) { + const config = loadAuthConfig(); + if (config && isAuthenticatedConfig(config)) { + return { + exit: false, + output: `Logged in as ${config.userEmail || config.userId}`, + }; + } else { + return { + exit: false, + output: "Authenticated via environment variable", + }; + } + } else { + return { + exit: false, + output: "Not logged in. Use /login to authenticate.", + }; + } +} + +async function handleOrg(args: string[]) { + posthogService.capture("useSlashCommand", { name: "org" }); + + if (args.length === 0) { + return { + exit: false, + output: "Usage: /org 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 = { + help: handleHelp, + clear: () => { + posthogService.capture("useSlashCommand", { name: "clear" }); + return { clear: true, output: "Chat history cleared" }; + }, + exit: () => { + posthogService.capture("useSlashCommand", { name: "exit" }); + return { exit: true, output: "Goodbye!" }; + }, + config: () => { + posthogService.capture("useSlashCommand", { name: "config" }); + return { openConfigSelector: true }; + }, + login: handleLogin, + logout: handleLogout, + whoami: handleWhoami, + model: () => ({ openModelSelector: true }), + compact: () => { + posthogService.capture("useSlashCommand", { name: "compact" }); + return { compact: true }; + }, + org: handleOrg, +}; + export async function handleSlashCommands( input: string, assistant: AssistantConfig, @@ -23,189 +213,25 @@ export async function handleSlashCommands( compact?: boolean; } | null> { // Only trigger slash commands if slash is the very first character - if (input.startsWith("/") && input.trim().startsWith("/")) { - const [command, ...args] = input.slice(1).split(" "); - switch (command) { - case "help": - const allCommands = getAllSlashCommands(assistant); - const helpMessage = [ - chalk.cyan("Slash commands:"), - ...allCommands.map( - (cmd) => - `- ${chalk.white(`/${cmd.name}:`)} ${chalk.gray(cmd.description)}`, - ), - ].join("\n"); - posthogService.capture("useSlashCommand", { - name: "help", - }); - return { output: helpMessage }; - case "clear": - posthogService.capture("useSlashCommand", { - name: "clear", - }); - return { clear: true, output: "Chat history cleared" }; - case "exit": - posthogService.capture("useSlashCommand", { - name: "exit", - }); - return { exit: true, output: "Goodbye!" }; - case "config": - posthogService.capture("useSlashCommand", { - name: "config", - }); - return { openConfigSelector: true }; - case "login": - posthogService.capture("useSlashCommand", { - name: "login", - }); - try { - const newAuthState = await services.auth.login(); - - // Automatically cascade reload from auth service - this will reload - // API_CLIENT -> CONFIG -> MODEL/MCP in the correct dependency order - await reloadService(SERVICE_NAMES.AUTH); - - const userInfo = - newAuthState.authConfig && - isAuthenticatedConfig(newAuthState.authConfig) - ? newAuthState.authConfig.userEmail || - newAuthState.authConfig.userId - : "user"; - - console.info(chalk.green(`\nLogged in as ${userInfo}`)); - - return { - exit: false, - output: "Login successful! All services updated automatically.", - }; - } catch (error: any) { - console.error(chalk.red(`\nLogin failed: ${error.message}`)); - return { - exit: false, - output: `Login failed: ${error.message}`, - }; - } - - case "logout": - posthogService.capture("useSlashCommand", { - name: "logout", - }); - try { - await services.auth.logout(); - - // Logout should exit the application since many services will be invalid - return { - exit: true, - output: "Logged out successfully", - }; - } catch { - return { - exit: true, - output: "Logged out successfully", - }; - } - - case "whoami": - posthogService.capture("useSlashCommand", { - name: "whoami", - }); - if (isAuthenticated()) { - const config = loadAuthConfig(); - if (config && isAuthenticatedConfig(config)) { - return { - exit: false, - output: `Logged in as ${config.userEmail || config.userId}`, - }; - } else { - return { - exit: false, - output: "Authenticated via environment variable", - }; - } - } else { - return { - exit: false, - output: "Not logged in. Use /login to authenticate.", - }; - } - - case "model": - // Open model selector UI - return { openModelSelector: true }; - - case "compact": - posthogService.capture("useSlashCommand", { - name: "compact", - }); - return { compact: true }; - - case "org": - posthogService.capture("useSlashCommand", { - name: "org", - }); - // Organization switching command - if (args.length === 0) { - return { - exit: false, - output: "Usage: /org or /org list", - }; - } - - const subCommand = args[0]; - if (subCommand === "list") { - 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) => ` ${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}`, - }; - } - } else { - // Switch to specific organization - const orgId = subCommand; - 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}`, - }; - } - } - default: - const assistantPrompt = assistant.prompts?.find( - (prompt) => prompt?.name === command, - ); - if (assistantPrompt) { - const newInput = assistantPrompt.prompt + args.join(" "); - return { newInput }; - } - return { output: `Unknown command: ${command}` }; - } + if (!input.startsWith("/") || !input.trim().startsWith("/")) { + return null; } - return null; + + const [command, ...args] = input.slice(1).split(" "); + + const handler = commandHandlers[command]; + if (handler) { + return await handler(args, assistant); + } + + // Check for custom assistant prompts + const assistantPrompt = assistant.prompts?.find( + (prompt) => prompt?.name === command, + ); + if (assistantPrompt) { + const newInput = assistantPrompt.prompt + args.join(" "); + return { newInput }; + } + + return { output: `Unknown command: ${command}` }; } diff --git a/src/streamChatResponse.helpers.ts b/src/streamChatResponse.helpers.ts new file mode 100644 index 000000000..9c2f4a72b --- /dev/null +++ b/src/streamChatResponse.helpers.ts @@ -0,0 +1,451 @@ +// Helper functions extracted from streamChatResponse.ts to reduce file size + +import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs"; + +import { checkToolPermission } from "./permissions/permissionChecker.js"; +import { toolPermissionManager } from "./permissions/permissionManager.js"; +import { ToolCallRequest } from "./permissions/types.js"; +import { StreamCallbacks } from "./streamChatResponse.types.js"; +import { telemetryService } from "./telemetry/telemetryService.js"; +import { calculateTokenCost } from "./telemetry/utils.js"; +import { + getAllBuiltinTools, + getAvailableTools, + Tool, + validateToolCallArgsPresent, + executeToolCall, +} from "./tools/index.js"; +import { PreprocessedToolCall, ToolCall } from "./tools/types.js"; +import { logger } from "./util/logger.js"; + +// Helper function to handle permission denied +export function handlePermissionDenied( + toolCall: PreprocessedToolCall, + chatHistoryEntries: ChatCompletionToolMessageParam[], + callbacks?: StreamCallbacks, +): void { + const deniedMessage = `Permission denied by user`; + logger.info("Tool call denied", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + + chatHistoryEntries.push({ + role: "tool", + tool_call_id: toolCall.id, + content: deniedMessage, + }); + + callbacks?.onToolResult?.(deniedMessage, toolCall.name); + logger.debug("Tool call rejected - stopping stream"); +} + +// Helper function to handle headless mode permission +export function handleHeadlessPermission( + toolCall: PreprocessedToolCall, +): never { + const allBuiltinTools = getAllBuiltinTools(); + const tool = allBuiltinTools.find((t) => t.name === toolCall.name); + const toolName = tool?.displayName || toolCall.name; + + console.error( + `Error: Tool '${toolName}' requires permission but cn is running in headless mode.`, + ); + console.error(`If you want to allow this tool, use --allow ${toolName}.`); + console.error( + `If you don't want the tool to be included, use --exclude ${toolName}.`, + ); + + process.exit(1); +} + +// Helper function to request user permission +export async function requestUserPermission( + toolCall: PreprocessedToolCall, + callbacks?: StreamCallbacks, +): Promise { + if (!callbacks?.onToolPermissionRequest) { + return false; + } + + const toolCallRequest: ToolCallRequest = { + name: toolCall.name, + arguments: toolCall.preprocessResult?.args ?? toolCall.arguments, + preview: toolCall.preprocessResult?.preview, + }; + + // Set up listener for permissionRequested event + const handlePermissionRequested = (event: { + requestId: string; + toolCall: ToolCallRequest; + }) => { + if (event.toolCall.name === toolCall.name) { + toolPermissionManager.off( + "permissionRequested", + handlePermissionRequested, + ); + // Notify UI about permission request + callbacks.onToolPermissionRequest!( + event.toolCall.name, + event.toolCall.arguments, + event.requestId, + event.toolCall.preview, + ); + } + }; + + toolPermissionManager.on("permissionRequested", handlePermissionRequested); + + // Request permission using the proper API + const permissionResult = + await toolPermissionManager.requestPermission(toolCallRequest); + + return permissionResult.approved; +} + +// Helper function to check if tool permission is needed +export async function checkToolPermissionApproval( + toolCall: PreprocessedToolCall, + callbacks?: StreamCallbacks, + isHeadless?: boolean, +): Promise { + const permissionCheck = checkToolPermission(toolCall); + + if (permissionCheck.permission === "allow") { + return true; + } else if (permissionCheck.permission === "ask") { + if (isHeadless) { + handleHeadlessPermission(toolCall); + } + return await requestUserPermission(toolCall, callbacks); + } else if (permissionCheck.permission === "exclude") { + // This shouldn't happen as excluded tools are filtered out earlier + return false; + } + + return false; +} + +// Helper function to track first token time +export function trackFirstTokenTime( + firstTokenTime: number | null, + chunk: any, + requestStartTime: number, + model: any, + tools?: any[], +): number | null { + if ( + firstTokenTime === null && + chunk.choices?.[0]?.delta && + (chunk.choices[0].delta.content || chunk.choices[0].delta.tool_calls) + ) { + const tokenTime = Date.now(); + telemetryService.recordResponseTime( + tokenTime - requestStartTime, + model.model, + "time_to_first_token", + (tools?.length || 0) > 0, + ); + return tokenTime; + } + return firstTokenTime; +} + +// Helper function to process content from a chunk +export function processChunkContent( + content: string, + aiResponse: string, + callbacks?: StreamCallbacks, + isHeadless?: boolean, +): string { + const updatedResponse = aiResponse + content; + + if (callbacks?.onContent) { + callbacks.onContent(content); + } else if (!isHeadless) { + process.stdout.write(content); + } + + return updatedResponse; +} + +// Helper function to handle tool call delta +export function processToolCallDelta( + toolCallDelta: any, + toolCallsMap: Map, + indexToIdMap: Map, +): void { + let toolCallId: string | undefined; + + // If we have an ID, use it and map the index + if (toolCallDelta.id) { + toolCallId = toolCallDelta.id; + if (toolCallDelta.index !== undefined && toolCallId) { + indexToIdMap.set(toolCallDelta.index, toolCallId); + } + } else if (toolCallDelta.index !== undefined) { + // No ID, but we have an index - look up the ID from our map + toolCallId = indexToIdMap.get(toolCallDelta.index); + } + + if (!toolCallId) { + logger.warn("Tool call delta without ID or valid index mapping", { + toolCallDelta, + }); + return; + } + + // Create tool call entry if it doesn't exist + if (!toolCallsMap.has(toolCallId)) { + toolCallsMap.set(toolCallId, { + id: toolCallId, + name: "", + arguments: null, + argumentsStr: "", + startNotified: false, + }); + } + + const toolCall = toolCallsMap.get(toolCallId); + if (!toolCall) { + logger.warn("Tool call not found in map", { toolCallId }); + return; + } + + // Update name + if (toolCallDelta.function?.name) { + toolCall.name = toolCallDelta.function.name; + } + + // Accumulate arguments + if (toolCallDelta.function?.arguments) { + toolCall.argumentsStr += toolCallDelta.function.arguments; + + // Try to parse when we might have complete JSON + try { + toolCall.arguments = JSON.parse(toolCall.argumentsStr); + toolCall.startNotified = true; + } catch { + // JSON not complete yet, continue + } + } +} + +// Helper function to record telemetry +export function recordStreamTelemetry(options: { + requestStartTime: number; + responseEndTime: number; + inputTokens: number; + outputTokens: number; + model: any; + tools?: any[]; +}): number { + const { + requestStartTime, + responseEndTime, + inputTokens, + outputTokens, + model, + tools, + } = options; + const totalDuration = responseEndTime - requestStartTime; + const cost = calculateTokenCost(inputTokens, outputTokens, model.model); + + telemetryService.recordTokenUsage(inputTokens, "input", model.model); + telemetryService.recordTokenUsage(outputTokens, "output", model.model); + telemetryService.recordCost(cost, model.model); + + telemetryService.recordResponseTime( + totalDuration, + model.model, + "total_response_time", + (tools?.length || 0) > 0, + ); + + telemetryService.logApiRequest({ + model: model.model, + durationMs: totalDuration, + success: true, + inputTokens, + outputTokens, + costUsd: cost, + }); + + return cost; +} + +/** + * Processes tool calls by validating and preprocessing them + * @param toolCalls - The raw tool calls from the LLM + * @param callbacks - Optional callbacks for notifying of events + * @returns - Preprocessed tool calls that are ready for execution + */ +export async function preprocessStreamedToolCalls( + toolCalls: ToolCall[], + callbacks?: StreamCallbacks, +): Promise<{ + preprocessedCalls: PreprocessedToolCall[]; + errorChatEntries: ChatCompletionToolMessageParam[]; +}> { + const preprocessedCalls: PreprocessedToolCall[] = []; + const errorChatEntries: ChatCompletionToolMessageParam[] = []; + + // Get all available tools + const availableTools: Tool[] = await getAvailableTools(); + + // Process each tool call + for (const toolCall of toolCalls) { + const startTime = Date.now(); + try { + const tool = availableTools.find((t) => t.name === toolCall.name); + if (!tool) { + throw new Error(`Tool ${toolCall.name} not found`); + } + + validateToolCallArgsPresent(toolCall, tool); + + const preprocessedCall: PreprocessedToolCall = { + ...toolCall, + tool, + }; + + if (tool.preprocess) { + logger.debug("Preprocessing tool call args", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + const preprocessed = await tool.preprocess(toolCall.arguments); + preprocessedCall.preprocessResult = preprocessed; + } + + preprocessedCalls.push(preprocessedCall); + } catch (error) { + // Notify the UI about the tool start, even though it failed + callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); + + const errorMessage = `Error processing tool call: ${ + error instanceof Error ? error.message : String(error) + }`; + + logger.error("Invalid tool call", { + name: toolCall.name, + error: errorMessage, + }); + + const duration = Date.now() - startTime; + telemetryService.logToolResult({ + toolName: toolCall.name, + success: false, + durationMs: duration, + error: errorMessage, + }); + + // Add error to chat history + errorChatEntries.push({ + role: "tool", + tool_call_id: toolCall.id, + content: errorMessage, + }); + + // Notify about the error + callbacks?.onToolError?.(errorMessage, toolCall.name); + } + } + + return { preprocessedCalls, errorChatEntries }; +} + +/** + * Executes preprocessed tool calls, handling permissions and results + * @param preprocessedCalls - The preprocessed tool calls ready for execution + * @param callbacks - Optional callbacks for notifying of events + * @returns - Chat history entries with tool results + */ +export async function executeStreamedToolCalls( + preprocessedCalls: PreprocessedToolCall[], + callbacks?: StreamCallbacks, + isHeadless?: boolean, +): Promise<{ + hasRejection: boolean; + chatHistoryEntries: ChatCompletionToolMessageParam[]; +}> { + const chatHistoryEntries: ChatCompletionToolMessageParam[] = []; + let hasRejection = false; + + // Execute each preprocessed tool call + for (const toolCall of preprocessedCalls) { + if (hasRejection) { + const cancelledMessage = `Cancelled due to previous tool rejection`; + chatHistoryEntries.push({ + role: "tool", + tool_call_id: toolCall.id, + content: cancelledMessage, + }); + + callbacks?.onToolResult?.(cancelledMessage, toolCall.name); + continue; + } + + // Handle remaining tool calls in this batch to maintain chat history consistency + try { + logger.debug("Checking tool permissions", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + + // Notify tool start - before permission check + // This ensures the UI shows the tool call even if it's rejected + callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); + + // Check tool permissions using helper + const approved = await checkToolPermissionApproval( + toolCall, + callbacks, + isHeadless, + ); + + if (!approved) { + handlePermissionDenied(toolCall, chatHistoryEntries, callbacks); + hasRejection = true; + continue; + } + + logger.debug("Executing tool", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + + const toolResult = await executeToolCall(toolCall); + + chatHistoryEntries.push({ + role: "tool", + tool_call_id: toolCall.id, + content: toolResult, + }); + + callbacks?.onToolResult?.(toolResult, toolCall.name); + } catch (error) { + const errorMessage = `Error executing tool ${toolCall.name}: ${ + error instanceof Error ? error.message : String(error) + }`; + + logger.error("Tool execution failed", { + name: toolCall.name, + error: errorMessage, + }); + + chatHistoryEntries.push({ + role: "tool", + tool_call_id: toolCall.id, + content: errorMessage, + }); + + callbacks?.onToolError?.(errorMessage, toolCall.name); + } + } + + return { + hasRejection, + chatHistoryEntries, + }; +} diff --git a/src/streamChatResponse.test.ts b/src/streamChatResponse.test.ts index 25a8bd02f..9473395f9 100644 --- a/src/streamChatResponse.test.ts +++ b/src/streamChatResponse.test.ts @@ -10,8 +10,8 @@ import { toolPermissionManager } from "./permissions/permissionManager.js"; import { preprocessStreamedToolCalls, executeStreamedToolCalls, - processStreamingResponse, -} from "./streamChatResponse.js"; +} from "./streamChatResponse.helpers.js"; +import { processStreamingResponse } from "./streamChatResponse.js"; import { ToolCall } from "./tools/index.js"; import { readFileTool } from "./tools/readFile.js"; import { searchCodeTool } from "./tools/searchCode.js"; @@ -144,12 +144,12 @@ describe("processStreamingResponse - content preservation", () => { contentChunk("I'll read the README file for you."), ]; - const result = await processStreamingResponse( + const result = await processStreamingResponse({ chatHistory, - mockModel, - mockLlmApi, - mockAbortController - ); + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); expect(result.content).toBe("I'll read the README file for you."); expect(result.toolCalls.length).toBe(1); @@ -164,12 +164,12 @@ describe("processStreamingResponse - content preservation", () => { toolCallChunk("call_123", "search_code", '{"pattern": "test"}'), ]; - const result = await processStreamingResponse( + const result = await processStreamingResponse({ chatHistory, - mockModel, - mockLlmApi, - mockAbortController - ); + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); expect(result.content).toBe("Let me search for that. "); expect(result.toolCalls.length).toBe(1); @@ -212,12 +212,12 @@ describe("processStreamingResponse - content preservation", () => { contentChunk("I'll read the README file for you."), ]; - const result = await processStreamingResponse( + const result = await processStreamingResponse({ chatHistory, - mockModel, - mockLlmApi, - mockAbortController - ); + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); expect(result.content).toBe("I'll read the README file for you."); expect(result.toolCalls.length).toBe(1); @@ -235,12 +235,12 @@ describe("processStreamingResponse - content preservation", () => { it("shows content works fine without tool calls", async () => { chunks = [contentChunk("Hello "), contentChunk("world!")]; - const result = await processStreamingResponse( + const result = await processStreamingResponse({ chatHistory, - mockModel, - mockLlmApi, - mockAbortController - ); + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); expect(result.content).toBe("Hello world!"); expect(result.toolCalls.length).toBe(0); @@ -268,12 +268,12 @@ describe("processStreamingResponse - content preservation", () => { ), ]; - const result = await processStreamingResponse( + const result = await processStreamingResponse({ chatHistory, - mockModel, - mockLlmApi, - mockAbortController - ); + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); // Content is captured correctly expect(result.content).toBe( @@ -318,12 +318,12 @@ describe("processStreamingResponse - content preservation", () => { toolCallChunkWithIndex(0, undefined, undefined, 'd"}'), ]; - const result = await processStreamingResponse( + const result = await processStreamingResponse({ chatHistory, - mockModel, - mockLlmApi, - mockAbortController - ); + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); // Fixed: Both issues are resolved // 1. Content is preserved @@ -366,12 +366,12 @@ describe("processStreamingResponse - content preservation", () => { // This should not throw an error: "Cannot read properties of undefined (reading 'delta')" let caughtError: any = null; try { - await processStreamingResponse( + await processStreamingResponse({ chatHistory, - mockModel, - mockLlmApi, - mockAbortController - ); + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); } catch (error) { caughtError = error; } @@ -379,12 +379,12 @@ describe("processStreamingResponse - content preservation", () => { // Should NOT throw error about reading 'delta' property expect(caughtError).toBeNull(); - const result = await processStreamingResponse( + const result = await processStreamingResponse({ chatHistory, - mockModel, - mockLlmApi, - mockAbortController - ); + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); expect(result.content).toBe("Hello world!"); expect(result.toolCalls.length).toBe(0); diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index f504c32fd..55a969cde 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -1,34 +1,30 @@ -import { CompletionOptions, ModelConfig } from "@continuedev/config-yaml"; +import { ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import * as dotenv from "dotenv"; import type { - ChatCompletionCreateParamsStreaming, ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletionTool, - ChatCompletionToolMessageParam, } from "openai/resources.mjs"; import { MCPService } from "./mcp.js"; -import { - checkToolPermission, - filterExcludedTools, - ToolCallRequest, -} from "./permissions/index.js"; -import { toolPermissionManager } from "./permissions/permissionManager.js"; +import { filterExcludedTools } from "./permissions/index.js"; import { getServiceSync, SERVICE_NAMES } from "./services/index.js"; import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; -import { telemetryService } from "./telemetry/telemetryService.js"; -import { calculateTokenCost } from "./telemetry/utils.js"; import { - executeToolCall, - getAllBuiltinTools, - getAvailableTools, - Tool, - ToolCall, - validateToolCallArgsPresent, -} from "./tools/index.js"; -import { PreprocessedToolCall, ToolCallPreview } from "./tools/types.js"; + processChunkContent, + processToolCallDelta, + recordStreamTelemetry, + preprocessStreamedToolCalls, + executeStreamedToolCalls, + trackFirstTokenTime, +} from "./streamChatResponse.helpers.js"; +import { + StreamCallbacks, + getDefaultCompletionOptions, +} from "./streamChatResponse.types.js"; +import { telemetryService } from "./telemetry/telemetryService.js"; +import { getAllBuiltinTools, ToolCall } from "./tools/index.js"; import { chatCompletionStreamWithBackoff, withExponentialBackoff, @@ -37,6 +33,89 @@ import { logger } from "./util/logger.js"; dotenv.config(); +function updateFinalResponse( + content: string, + shouldContinue: boolean, + isHeadless: boolean, + currentFinalResponse: string, +): string { + if (!shouldContinue) { + return content; + } else if (isHeadless && content) { + return content; + } + return currentFinalResponse; +} + +function handleContentDisplay( + content: string, + callbacks: StreamCallbacks | undefined, + isHeadless: boolean, +): void { + // Add newline after content if needed + if (!callbacks?.onContent && !isHeadless && content) { + logger.info(""); + } + + // Notify content complete + if (content && callbacks?.onContentComplete) { + callbacks.onContentComplete(content); + } +} + +async function handleToolCalls( + toolCalls: ToolCall[], + chatHistory: ChatCompletionMessageParam[], + content: string, + callbacks: StreamCallbacks | undefined, + isHeadless: boolean, +): Promise { + if (toolCalls.length === 0) { + if (content) { + chatHistory.push({ role: "assistant", content }); + } + return false; + } + + const toolCallsForHistory: ChatCompletionMessageToolCall[] = toolCalls.map( + (tc) => ({ + id: tc.id, + type: "function", + function: { + name: tc.name, + arguments: JSON.stringify(tc.arguments), + }, + }), + ); + + chatHistory.push({ + role: "assistant", + content: content || null, + tool_calls: toolCallsForHistory, + }); + + // First preprocess the tool calls + const { preprocessedCalls, errorChatEntries } = + await preprocessStreamedToolCalls(toolCalls, callbacks); + + // Add any preprocessing errors to chat history + chatHistory.push(...errorChatEntries); + + // Execute the valid preprocessed tool calls + const { chatHistoryEntries: toolResults, hasRejection } = + await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless); + + if (isHeadless && hasRejection) { + logger.debug( + "Tool call rejected in headless mode - returning current content", + ); + return true; // Signal early return needed + } + + chatHistory.push(...toolResults); + return false; +} + export function getAllTools() { // Get all available tool names const allBuiltinTools = getAllBuiltinTools(); @@ -121,47 +200,90 @@ export function getAllTools() { return allTools; } -export interface StreamCallbacks { - onContent?: (content: string) => void; - onContentComplete?: (content: string) => void; - onToolStart?: (toolName: string, toolArgs?: any) => void; - onToolResult?: (result: string, toolName: string) => void; - onToolError?: (error: string, toolName?: string) => void; - onToolPermissionRequest?: ( - toolName: string, - toolArgs: any, - requestId: string, - preview?: ToolCallPreview[], - ) => void; +// Helper function to process a single chunk +interface ProcessChunkOptions { + chunk: any; + aiResponse: string; + toolCallsMap: Map; + indexToIdMap: Map; + callbacks?: StreamCallbacks; + isHeadless?: boolean; } -function getDefaultCompletionOptions( - opts?: CompletionOptions, -): Partial { - if (!opts) return {}; - return { - max_tokens: opts.maxTokens, - temperature: opts.temperature, - frequency_penalty: opts.frequencyPenalty, - presence_penalty: opts.presencePenalty, - top_p: opts.topP, - }; + +function processChunk(options: ProcessChunkOptions): { + aiResponse: string; + shouldContinue: boolean; +} { + const { + chunk, + aiResponse, + toolCallsMap, + indexToIdMap, + callbacks, + isHeadless, + } = options; + // Safety check: ensure chunk has the expected structure + if (!chunk.choices || !chunk.choices[0]) { + logger.warn("Malformed chunk received - missing choices", { chunk }); + return { aiResponse, shouldContinue: true }; + } + + const choice = chunk.choices[0]; + if (!choice.delta) { + logger.warn("Malformed chunk received - missing delta", { chunk }); + return { aiResponse, shouldContinue: true }; + } + + let updatedResponse = aiResponse; + + // Handle content streaming + if (choice.delta.content) { + updatedResponse = processChunkContent( + choice.delta.content, + aiResponse, + callbacks, + isHeadless, + ); + } + + // Handle tool calls + if (choice.delta.tool_calls) { + for (const toolCallDelta of choice.delta.tool_calls) { + processToolCallDelta(toolCallDelta, toolCallsMap, indexToIdMap); + } + } + + return { aiResponse: updatedResponse, shouldContinue: true }; +} + +interface ProcessStreamingResponseOptions { + chatHistory: ChatCompletionMessageParam[]; + model: ModelConfig; + llmApi: BaseLlmApi; + abortController: AbortController; + callbacks?: StreamCallbacks; + isHeadless?: boolean; + tools?: ChatCompletionTool[]; } // Process a single streaming response and return whether we need to continue export async function processStreamingResponse( - chatHistory: ChatCompletionMessageParam[], - model: ModelConfig, - llmApi: BaseLlmApi, - abortController: AbortController, - callbacks?: StreamCallbacks, - isHeadless?: boolean, - tools?: ChatCompletionTool[], + options: ProcessStreamingResponseOptions, ): Promise<{ content: string; finalContent: string; // Added field for final content only toolCalls: ToolCall[]; shouldContinue: boolean; }> { + const { + chatHistory, + model, + llmApi, + abortController, + callbacks, + isHeadless, + tools, + } = options; const requestStartTime = Date.now(); const streamFactory = async () => { @@ -215,136 +337,37 @@ export async function processStreamingResponse( break; } - // Safety check: ensure chunk has the expected structure - if (!chunk.choices || !chunk.choices[0]) { - logger.warn("Malformed chunk received - missing choices", { chunk }); - continue; - } - // Track first token time - if ( - firstTokenTime === null && - (chunk.choices[0].delta.content || chunk.choices[0].delta.tool_calls) - ) { - firstTokenTime = Date.now(); - telemetryService.recordResponseTime( - firstTokenTime - requestStartTime, - model.model, - "time_to_first_token", - (tools?.length || 0) > 0, - ); - } + firstTokenTime = trackFirstTokenTime( + firstTokenTime, + chunk, + requestStartTime, + model, + tools, + ); - const choice = chunk.choices[0]; - if (!choice.delta) { - logger.warn("Malformed chunk received - missing delta", { chunk }); - continue; - } - - // Handle content streaming - if (choice.delta.content) { - const content = choice.delta.content; - aiResponse += content; - - // Call the onContent callback if provided - if (callbacks?.onContent) { - callbacks.onContent(content); - } else if (!isHeadless) { - // Print content directly if no callback - process.stdout.write(content); - } - } - - // Handle tool calls - if (choice.delta.tool_calls) { - for (const toolCallDelta of choice.delta.tool_calls) { - let toolCallId: string | undefined; - - // If we have an ID, use it and map the index - if (toolCallDelta.id) { - toolCallId = toolCallDelta.id; - if (toolCallDelta.index !== undefined && toolCallId) { - indexToIdMap.set(toolCallDelta.index, toolCallId); - } - } else if (toolCallDelta.index !== undefined) { - // No ID, but we have an index - look up the ID from our map - toolCallId = indexToIdMap.get(toolCallDelta.index); - } - - if (!toolCallId) { - logger.warn("Tool call delta without ID or valid index mapping", { - toolCallDelta, - }); - continue; - } - - // Create tool call entry if it doesn't exist - if (!toolCallsMap.has(toolCallId)) { - toolCallsMap.set(toolCallId, { - id: toolCallId, - name: "", - arguments: null, - argumentsStr: "", - startNotified: false, - }); - } - - const toolCall = toolCallsMap.get(toolCallId); - if (!toolCall) { - logger.warn("Tool call not found in map", { toolCallId }); - continue; - } - - // Update name - if (toolCallDelta.function?.name) { - toolCall.name = toolCallDelta.function.name; - } - - // Accumulate arguments - if (toolCallDelta.function?.arguments) { - toolCall.argumentsStr += toolCallDelta.function.arguments; - - // Try to parse when we might have complete JSON - try { - toolCall.arguments = JSON.parse(toolCall.argumentsStr); - - // Don't notify onToolStart here anymore - wait until after permission check - toolCall.startNotified = true; - } catch { - // JSON not complete yet, continue - } - } - } - } + const result = processChunk({ + chunk, + aiResponse, + toolCallsMap, + indexToIdMap, + callbacks, + isHeadless, + }); + aiResponse = result.aiResponse; + if (!result.shouldContinue) break; } const responseEndTime = Date.now(); - const totalDuration = responseEndTime - requestStartTime; - - // Record API request metrics - const cost = calculateTokenCost(inputTokens, outputTokens, model.model); - - telemetryService.recordTokenUsage(inputTokens, "input", model.model); - telemetryService.recordTokenUsage(outputTokens, "output", model.model); - telemetryService.recordCost(cost, model.model); - - telemetryService.recordResponseTime( - totalDuration, - model.model, - "total_response_time", - (tools?.length || 0) > 0, - ); - - // Log API request event - telemetryService.logApiRequest( - model.model, - totalDuration, - true, // success - undefined, // no error + const cost = recordStreamTelemetry({ + requestStartTime, + responseEndTime, inputTokens, outputTokens, - cost, - ); + model, + tools, + }); + const totalDuration = responseEndTime - requestStartTime; logger.debug("Stream complete", { chunkCount, @@ -359,12 +382,12 @@ export async function processStreamingResponse( const errorDuration = Date.now() - requestStartTime; // Log failed API request - telemetryService.logApiRequest( - model.model, - errorDuration, - false, // failed - error.message || String(error), - ); + telemetryService.logApiRequest({ + model: model.model, + durationMs: errorDuration, + success: false, + error: error.message || String(error), + }); if (error.name === "AbortError" || abortController?.signal.aborted) { logger.debug("Stream aborted by user"); @@ -405,262 +428,6 @@ export async function processStreamingResponse( }; } -/** - * Processes tool calls by validating and preprocessing them - * @param toolCalls - The raw tool calls from the LLM - * @param callbacks - Optional callbacks for notifying of events - * @returns - Preprocessed tool calls that are ready for execution - */ -export async function preprocessStreamedToolCalls( - toolCalls: ToolCall[], - callbacks?: StreamCallbacks, -): Promise<{ - preprocessedCalls: PreprocessedToolCall[]; - errorChatEntries: ChatCompletionToolMessageParam[]; -}> { - const preprocessedCalls: PreprocessedToolCall[] = []; - const errorChatEntries: ChatCompletionToolMessageParam[] = []; - - // Get all available tools - const availableTools: Tool[] = await getAvailableTools(); - - // Process each tool call - for (const toolCall of toolCalls) { - const startTime = Date.now(); - try { - const tool = availableTools.find((t) => t.name === toolCall.name); - if (!tool) { - throw new Error(`Tool ${toolCall.name} not found`); - } - - validateToolCallArgsPresent(toolCall, tool); - - const preprocessedCall: PreprocessedToolCall = { - ...toolCall, - tool, - }; - - if (tool.preprocess) { - logger.debug("Preprocessing tool call args", { - name: toolCall.name, - arguments: toolCall.arguments, - }); - const preprocessed = await tool.preprocess(toolCall.arguments); - preprocessedCall.preprocessResult = preprocessed; - } - - preprocessedCalls.push(preprocessedCall); - } catch (error) { - // Notify the UI about the tool start, even though it failed - callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); - - const errorMessage = `Error processing tool call: ${ - error instanceof Error ? error.message : String(error) - }`; - - logger.error("Invalid tool call", { - name: toolCall.name, - error: errorMessage, - }); - - const duration = Date.now() - startTime; - telemetryService.logToolResult( - toolCall.name, - false, - duration, - errorMessage, - ); - - // Add error to chat history - errorChatEntries.push({ - role: "tool", - tool_call_id: toolCall.id, - content: errorMessage, - }); - - // Notify about the error - callbacks?.onToolError?.(errorMessage, toolCall.name); - } - } - - return { preprocessedCalls, errorChatEntries }; -} - -/** - * Executes preprocessed tool calls, handling permissions and results - * @param preprocessedCalls - The preprocessed tool calls ready for execution - * @param callbacks - Optional callbacks for notifying of events - * @returns - Chat history entries with tool results - */ -export async function executeStreamedToolCalls( - preprocessedCalls: PreprocessedToolCall[], - callbacks?: StreamCallbacks, - isHeadless?: boolean, -): Promise<{ - hasRejection: boolean; - chatHistoryEntries: ChatCompletionToolMessageParam[]; -}> { - const chatHistoryEntries: ChatCompletionToolMessageParam[] = []; - let hasRejection = false; - - // Execute each preprocessed tool call - for (const toolCall of preprocessedCalls) { - if (hasRejection) { - const cancelledMessage = `Cancelled due to previous tool rejection`; - chatHistoryEntries.push({ - role: "tool", - tool_call_id: toolCall.id, - content: cancelledMessage, - }); - - callbacks?.onToolResult?.(cancelledMessage, toolCall.name); - continue; - } - - // Handle remaining tool calls in this batch to maintain chat history consistency - try { - logger.debug("Checking tool permissions", { - name: toolCall.name, - arguments: toolCall.arguments, - }); - - // Notify tool start - before permission check - // This ensures the UI shows the tool call even if it's rejected - callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); - - // Check tool permissions - const permissionCheck = checkToolPermission(toolCall); - let approved = false; - - if (permissionCheck.permission === "allow") { - approved = true; - } else if (permissionCheck.permission === "ask") { - if (isHeadless) { - // In headless mode, exit immediately with instructions - const allBuiltinTools = getAllBuiltinTools(); - const tool = allBuiltinTools.find((t) => t.name === toolCall.name); - const toolName = tool?.displayName || toolCall.name; - console.error( - `Error: Tool '${toolName}' requires permission but cn is running in headless mode.`, - ); - console.error( - `If you want to allow this tool, use --allow ${toolName}.`, - ); - console.error( - `If you don't want the tool to be included, use --exclude ${toolName}.`, - ); - - process.exit(1); - } - - // Request permission from user - if (callbacks?.onToolPermissionRequest) { - // Use the proper toolPermissionManager API - const toolCallRequest: ToolCallRequest = { - name: toolCall.name, - arguments: toolCall.preprocessResult?.args ?? toolCall.arguments, - preview: toolCall.preprocessResult?.preview, - }; - - // Set up listener for permissionRequested event - const handlePermissionRequested = (event: { - requestId: string; - toolCall: ToolCallRequest; - }) => { - if (event.toolCall.name === toolCall.name) { - toolPermissionManager.off( - "permissionRequested", - handlePermissionRequested, - ); - // Notify UI about permission request - callbacks.onToolPermissionRequest!( - event.toolCall.name, - event.toolCall.arguments, - event.requestId, - event.toolCall.preview, - ); - } - }; - - toolPermissionManager.on( - "permissionRequested", - handlePermissionRequested, - ); - - // Request permission using the proper API - const permissionResult = - await toolPermissionManager.requestPermission(toolCallRequest); - - approved = permissionResult.approved; - } else { - // Fallback: deny if no UI callback available - approved = false; - } - } else if (permissionCheck.permission === "exclude") { - // This shouldn't happen as excluded tools are filtered out earlier - approved = false; - } - - if (!approved) { - const deniedMessage = `Permission denied by user`; - logger.info("Tool call denied", { - name: toolCall.name, - arguments: toolCall.arguments, - }); - - chatHistoryEntries.push({ - role: "tool", - tool_call_id: toolCall.id, - content: deniedMessage, - }); - - callbacks?.onToolResult?.(deniedMessage, toolCall.name); - - logger.debug("Tool call rejected - stopping stream"); - hasRejection = true; - continue; - } - - logger.debug("Executing tool", { - name: toolCall.name, - arguments: toolCall.arguments, - }); - - const toolResult = await executeToolCall(toolCall); - - chatHistoryEntries.push({ - role: "tool", - tool_call_id: toolCall.id, - content: toolResult, - }); - - callbacks?.onToolResult?.(toolResult, toolCall.name); - } catch (error) { - const errorMessage = `Error executing tool ${toolCall.name}: ${ - error instanceof Error ? error.message : String(error) - }`; - - logger.error("Tool execution failed", { - name: toolCall.name, - error: errorMessage, - }); - - chatHistoryEntries.push({ - role: "tool", - tool_call_id: toolCall.id, - content: errorMessage, - }); - - callbacks?.onToolError?.(errorMessage, toolCall.name); - } - } - - return { - hasRejection, - chatHistoryEntries, - }; -} - // Main function that handles the conversation loop export async function streamChatResponse( chatHistory: ChatCompletionMessageParam[], @@ -694,7 +461,7 @@ export async function streamChatResponse( // Get response from LLM const { content, toolCalls, shouldContinue } = - await processStreamingResponse( + await processStreamingResponse({ chatHistory, model, llmApi, @@ -702,74 +469,32 @@ export async function streamChatResponse( callbacks, isHeadless, tools, - ); + }); fullResponse += content; - // In headless mode, we only want to collect the final content after all tool calls - if (!shouldContinue) { - // This is the final message, so it's the content we want to show - finalResponse = content; - } else if (isHeadless && content) { - // In headless mode with tool calls, we still want to show any text content - // since we won't be making follow-up requests - finalResponse = content; - } + // Update final response based on mode + finalResponse = updateFinalResponse( + content, + shouldContinue, + isHeadless, + finalResponse, + ); - // Add newline after content if needed - if (!callbacks?.onContent && !isHeadless && content) { - logger.info(""); - } + // Handle content display + handleContentDisplay(content, callbacks, isHeadless); - // Notify content complete - if (content && callbacks?.onContentComplete) { - callbacks.onContentComplete(content); - } + // Handle tool calls and check for early return + const shouldReturn = await handleToolCalls( + toolCalls, + chatHistory, + content, + callbacks, + isHeadless, + ); - // Add assistant message to history - if (toolCalls.length > 0) { - const toolCallsForHistory: ChatCompletionMessageToolCall[] = - toolCalls.map((tc) => ({ - id: tc.id, - type: "function", - function: { - name: tc.name, - arguments: JSON.stringify(tc.arguments), - }, - })); - - chatHistory.push({ - role: "assistant", - content: content || null, - tool_calls: toolCallsForHistory, - }); - - // First preprocess the tool calls - const { preprocessedCalls, errorChatEntries } = - await preprocessStreamedToolCalls(toolCalls, callbacks); - - // Add any preprocessing errors to chat history - chatHistory.push(...errorChatEntries); - - // Execute the valid preprocessed tool calls - const { chatHistoryEntries: toolResults, hasRejection } = - await executeStreamedToolCalls( - preprocessedCalls, - callbacks, - isHeadless, - ); - - if (isHeadless && hasRejection) { - logger.debug( - "Tool call rejected in headless mode - returning current content", - ); - return finalResponse || content || fullResponse; - } - - chatHistory.push(...toolResults); - } else if (content) { - // Just content, no tools - chatHistory.push({ role: "assistant", content }); + if (shouldReturn) { + return finalResponse || content || fullResponse; } // Check if we should continue diff --git a/src/streamChatResponse.types.ts b/src/streamChatResponse.types.ts new file mode 100644 index 000000000..6519e0e48 --- /dev/null +++ b/src/streamChatResponse.types.ts @@ -0,0 +1,31 @@ +import { CompletionOptions } from "@continuedev/config-yaml"; +import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; + +import { ToolCallPreview } from "./tools/types.js"; + +export interface StreamCallbacks { + onContent?: (content: string) => void; + onContentComplete?: (content: string) => void; + onToolStart?: (toolName: string, toolArgs?: any) => void; + onToolResult?: (result: string, toolName: string) => void; + onToolError?: (error: string, toolName?: string) => void; + onToolPermissionRequest?: ( + toolName: string, + toolArgs: any, + requestId: string, + preview?: ToolCallPreview[], + ) => void; +} + +export function getDefaultCompletionOptions( + opts?: CompletionOptions, +): Partial { + if (!opts) return {}; + return { + max_tokens: opts.maxTokens, + temperature: opts.temperature, + frequency_penalty: opts.frequencyPenalty, + presence_penalty: opts.presencePenalty, + top_p: opts.topP, + }; +} diff --git a/src/telemetry/telemetryService.ts b/src/telemetry/telemetryService.ts index c3165e181..beffc672a 100644 --- a/src/telemetry/telemetryService.ts +++ b/src/telemetry/telemetryService.ts @@ -471,57 +471,60 @@ class TelemetryService { logger.debug("User prompt event", attributes); } - public logToolResult( - toolName: string, - success: boolean, - durationMs: number, - error?: string, - decision?: "accept" | "reject", - source?: string, - toolParameters?: string, - ) { + public logToolResult(options: { + toolName: string; + success: boolean; + durationMs: number; + error?: string; + decision?: "accept" | "reject"; + source?: string; + toolParameters?: string; + }) { if (!this.isEnabled()) return; const attributes = this.getStandardAttributes({ "event.name": "tool_result", "event.timestamp": new Date().toISOString(), - tool_name: toolName, - success: success.toString(), - duration_ms: durationMs.toString(), + tool_name: options.toolName, + success: options.success.toString(), + duration_ms: options.durationMs.toString(), }); - if (error) attributes.error = error; - if (decision) attributes.decision = decision; - if (source) attributes.source = source; - if (toolParameters) attributes.tool_parameters = toolParameters; + if (options.error) attributes.error = options.error; + if (options.decision) attributes.decision = options.decision; + if (options.source) attributes.source = options.source; + if (options.toolParameters) + attributes.tool_parameters = options.toolParameters; // TODO: Implement OTLP logs export logger.debug("Tool result event", attributes); } - public logApiRequest( - model: string, - durationMs: number, - success: boolean, - error?: string, - inputTokens?: number, - outputTokens?: number, - costUsd?: number, - ) { + public logApiRequest(options: { + model: string; + durationMs: number; + success: boolean; + error?: string; + inputTokens?: number; + outputTokens?: number; + costUsd?: number; + }) { if (!this.isEnabled()) return; const attributes = this.getStandardAttributes({ "event.name": "api_request", "event.timestamp": new Date().toISOString(), - model, - duration_ms: durationMs.toString(), - success: success.toString(), + model: options.model, + duration_ms: options.durationMs.toString(), + success: options.success.toString(), }); - if (error) attributes.error = error; - if (inputTokens) attributes.input_tokens = inputTokens.toString(); - if (outputTokens) attributes.output_tokens = outputTokens.toString(); - if (costUsd) attributes.cost_usd = costUsd.toString(); + if (options.error) attributes.error = options.error; + if (options.inputTokens) + attributes.input_tokens = options.inputTokens.toString(); + if (options.outputTokens) + attributes.output_tokens = options.outputTokens.toString(); + if (options.costUsd) attributes.cost_usd = options.costUsd.toString(); // TODO: Implement OTLP logs export logger.debug("API request event", attributes); diff --git a/src/tools/index.ts b/src/tools/index.ts index d761b8c83..77287c8d5 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -154,15 +154,12 @@ export async function executeToolCall( ); const duration = Date.now() - startTime; - telemetryService.logToolResult( - toolCall.name, - true, - duration, - undefined, // no error - undefined, // no decision - undefined, // no source - JSON.stringify(toolCall.arguments), - ); + telemetryService.logToolResult({ + toolName: toolCall.name, + success: true, + durationMs: duration, + toolParameters: JSON.stringify(toolCall.arguments), + }); logger.debug("Tool execution completed", { toolName: toolCall.name, @@ -174,15 +171,13 @@ export async function executeToolCall( const duration = Date.now() - startTime; const errorMessage = error instanceof Error ? error.message : String(error); - telemetryService.logToolResult( - toolCall.name, - false, - duration, - errorMessage, - undefined, // no decision - undefined, // no source - JSON.stringify(toolCall.arguments), - ); + telemetryService.logToolResult({ + toolName: toolCall.name, + success: false, + durationMs: duration, + error: errorMessage, + toolParameters: JSON.stringify(toolCall.arguments), + }); return `Error executing tool "${toolCall.name}": ${errorMessage}`; } diff --git a/src/tools/multiEdit.ts b/src/tools/multiEdit.ts index ed8ef05a6..5326172ab 100644 --- a/src/tools/multiEdit.ts +++ b/src/tools/multiEdit.ts @@ -29,6 +29,100 @@ function hasFileBeenRead(filePath: string): boolean { return readFilesSet.has(filePath); } +// Helper functions for multiEdit validation +function validateMultiEditArgs(args: any): MultiEditArgs { + const { file_path, edits } = args as MultiEditArgs; + + if (!file_path) { + throw new Error("file_path is required"); + } + if (!path.isAbsolute(file_path)) { + throw new Error("file_path must be an absolute path"); + } + if (!edits || !Array.isArray(edits) || edits.length === 0) { + throw new Error( + "edits array is required and must contain at least one edit", + ); + } + + return { file_path, edits }; +} + +function validateEdits(edits: EditOperation[]): void { + for (let i = 0; i < edits.length; i++) { + const edit = edits[i]; + if (!edit.old_string && edit.old_string !== "") { + throw new Error(`Edit ${i + 1}: old_string is required`); + } + if (edit.new_string === undefined) { + throw new Error(`Edit ${i + 1}: new_string is required`); + } + if (edit.old_string === edit.new_string) { + throw new Error( + `Edit ${i + 1}: old_string and new_string must be different`, + ); + } + } +} + +function validateFileAccess( + file_path: string, + isCreatingNewFile: boolean, +): void { + if (isCreatingNewFile) { + // For new file creation, check if parent directory exists + const parentDir = path.dirname(file_path); + if (parentDir && !fs.existsSync(parentDir)) { + throw new Error(`Parent directory does not exist: ${parentDir}`); + } + } else { + // For existing files, check if file has been read + if (!hasFileBeenRead(file_path)) { + throw new Error( + `You must use the Read tool to read ${file_path} before editing it.`, + ); + } + if (!fs.existsSync(file_path)) { + throw new Error(`File ${file_path} does not exist`); + } + } +} + +function applyEdit( + content: string, + edit: EditOperation, + editIndex: number, + isFirstEditOfNewFile: boolean, +): string { + const { old_string, new_string, replace_all = false } = edit; + + // For new file creation, the first edit can have empty old_string + if (isFirstEditOfNewFile && old_string === "") { + return new_string; + } + + // Check if old_string exists in current content + if (!content.includes(old_string)) { + throw new Error( + `Edit ${editIndex + 1}: String not found in file: "${old_string}"`, + ); + } + + if (replace_all) { + // Replace all occurrences + return content.split(old_string).join(new_string); + } else { + // Replace only the first occurrence, but check for uniqueness + const occurrences = content.split(old_string).length - 1; + if (occurrences > 1) { + throw new Error( + `Edit ${editIndex + 1}: String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`, + ); + } + return content.replace(old_string, new_string); + } +} + export const multiEditTool: Tool = { name: "MultiEdit", displayName: "MultiEdit", @@ -129,60 +223,17 @@ If you want to create a new file, use: }, }, preprocess: async (args) => { - const { file_path, edits } = args as MultiEditArgs; - - // Validate arguments - if (!file_path) { - throw new Error("file_path is required"); - } - if (!path.isAbsolute(file_path)) { - throw new Error("file_path must be an absolute path"); - } - if (!edits || !Array.isArray(edits) || edits.length === 0) { - throw new Error( - "edits array is required and must contain at least one edit", - ); - } + // Validate and extract arguments + const { file_path, edits } = validateMultiEditArgs(args); // Validate each edit operation - for (let i = 0; i < edits.length; i++) { - const edit = edits[i]; - if (!edit.old_string && edit.old_string !== "") { - throw new Error(`Edit ${i + 1}: old_string is required`); - } - if (edit.new_string === undefined) { - throw new Error(`Edit ${i + 1}: new_string is required`); - } - if (edit.old_string === edit.new_string) { - throw new Error( - `Edit ${i + 1}: old_string and new_string must be different`, - ); - } - } + validateEdits(edits); // Check if this is creating a new file (first edit has empty old_string) const isCreatingNewFile = edits[0].old_string === ""; - if (isCreatingNewFile) { - // For new file creation, check if parent directory exists - const parentDir = path.dirname(file_path); - if (parentDir && !fs.existsSync(parentDir)) { - throw new Error(`Parent directory does not exist: ${parentDir}`); - } - // Don't check if file has been read for new file creation - } else { - // For existing files, check if file has been read - if (!hasFileBeenRead(file_path)) { - throw new Error( - `You must use the Read tool to read ${file_path} before editing it.`, - ); - } - - // Check if file exists - if (!fs.existsSync(file_path)) { - throw new Error(`File ${file_path} does not exist`); - } - } + // Validate file access + validateFileAccess(file_path, isCreatingNewFile); // Read current file content (or start with empty for new files) let currentContent = ""; @@ -195,35 +246,8 @@ If you want to create a new file, use: // Apply all edits sequentially for (let i = 0; i < edits.length; i++) { - const edit = edits[i]; - const { old_string, new_string, replace_all = false } = edit; - - // For new file creation, the first edit can have empty old_string - if (i === 0 && isCreatingNewFile && old_string === "") { - newContent = new_string; - continue; - } - - // Check if old_string exists in current content - if (!newContent.includes(old_string)) { - throw new Error( - `Edit ${i + 1}: String not found in file: "${old_string}"`, - ); - } - - if (replace_all) { - // Replace all occurrences - newContent = newContent.split(old_string).join(new_string); - } else { - // Replace only the first occurrence, but check for uniqueness - const occurrences = newContent.split(old_string).length - 1; - if (occurrences > 1) { - throw new Error( - `Edit ${i + 1}: String "${old_string}" appears ${occurrences} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`, - ); - } - newContent = newContent.replace(old_string, new_string); - } + const isFirstEditOfNewFile = i === 0 && isCreatingNewFile; + newContent = applyEdit(newContent, edits[i], i, isFirstEditOfNewFile); } // Generate diff for preview diff --git a/src/ui/ColoredDiff.tsx b/src/ui/ColoredDiff.tsx index ecc7c34e9..a0c7b8d98 100644 --- a/src/ui/ColoredDiff.tsx +++ b/src/ui/ColoredDiff.tsx @@ -153,6 +153,26 @@ const WordLevelDiffGroup: React.FC<{ ); }; +// Helper function to process a group of lines +function processGroup( + group: DiffLine[], +): Array<{ type: "group" | "single"; lines: DiffLine[] }> { + if (group.length <= 1) { + return [{ type: "single", lines: group }]; + } + + const delLines = group.filter((l) => l.type === "del"); + const addLines = group.filter((l) => l.type === "add"); + + // Only do word-level diff if we have both deletions and additions + if (delLines.length > 0 && addLines.length > 0) { + return [{ type: "group", lines: group }]; + } + + // Single type, treat as individual lines + return group.map((l) => ({ type: "single" as const, lines: [l] })); +} + export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent, }) => { @@ -183,22 +203,7 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ // If next line is different type or end of array, finalize the group if (!nextLine || (nextLine.type !== "add" && nextLine.type !== "del")) { - if (currentGroup.length > 1) { - const delLines = currentGroup.filter((l) => l.type === "del"); - const addLines = currentGroup.filter((l) => l.type === "add"); - - // Only do word-level diff if we have both deletions and additions - if (delLines.length > 0 && addLines.length > 0) { - groupedLines.push({ type: "group", lines: currentGroup }); - } else { - // Single type, treat as individual lines - currentGroup.forEach((l) => - groupedLines.push({ type: "single", lines: [l] }), - ); - } - } else { - groupedLines.push({ type: "single", lines: currentGroup }); - } + groupedLines.push(...processGroup(currentGroup)); currentGroup = []; } } else { diff --git a/src/ui/FreeTrialTransitionUI.tsx b/src/ui/FreeTrialTransitionUI.tsx index aa2a6ce08..aac552274 100644 --- a/src/ui/FreeTrialTransitionUI.tsx +++ b/src/ui/FreeTrialTransitionUI.tsx @@ -18,6 +18,69 @@ import { useNavigation } from "./context/NavigationContext.js"; const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); +// Helper functions for input handling +interface ChoiceInputOptions { + input: string; + key: any; + selectedOption: number; + setSelectedOption: (option: number) => void; + hasOrganizations: boolean; + handleOptionSelect: () => void; +} + +function handleChoiceInput(options: ChoiceInputOptions): void { + const { + input, + key, + selectedOption, + setSelectedOption, + hasOrganizations, + handleOptionSelect, + } = options; + if (key.upArrow && selectedOption > 1) { + setSelectedOption(selectedOption - 1); + } else if (key.downArrow && selectedOption < (hasOrganizations ? 4 : 3)) { + setSelectedOption(selectedOption + 1); + } else if (input === "1") { + setSelectedOption(1); + } else if (input === "2") { + setSelectedOption(2); + } else if (input === "3") { + setSelectedOption(3); + } else if (input === "4" && hasOrganizations) { + setSelectedOption(4); + } else if (key.return) { + handleOptionSelect(); + } +} + +interface ApiKeyInputOptions { + input: string; + key: any; + apiKey: string; + setApiKey: (key: string) => void; + setErrorMessage: (msg: string) => void; + handleApiKeySubmit: () => void; +} + +function handleApiKeyInput(options: ApiKeyInputOptions): void { + const { input, key, apiKey, setApiKey, setErrorMessage, handleApiKeySubmit } = + options; + if (key.return) { + if (isValidAnthropicApiKey(apiKey)) { + handleApiKeySubmit(); + } else { + setErrorMessage(getApiKeyValidationError(apiKey)); + } + } else if (key.backspace || key.delete) { + setApiKey(apiKey.slice(0, -1)); + setErrorMessage(""); + } else if (input && !key.ctrl && !key.meta) { + setApiKey(apiKey + input); + setErrorMessage(""); + } +} + interface FreeTrialTransitionUIProps { onReload: () => void; } @@ -68,35 +131,23 @@ const FreeTrialTransitionUI: React.FC = ({ useInput((input, key) => { if (currentStep === "choice") { - if (key.upArrow && selectedOption > 1) { - setSelectedOption(selectedOption - 1); - } else if (key.downArrow && selectedOption < (hasOrganizations ? 4 : 3)) { - setSelectedOption(selectedOption + 1); - } else if (input === "1") { - setSelectedOption(1); - } else if (input === "2") { - setSelectedOption(2); - } else if (input === "3") { - setSelectedOption(3); - } else if (input === "4" && hasOrganizations) { - setSelectedOption(4); - } else if (key.return) { - handleOptionSelect(); - } + handleChoiceInput({ + input, + key, + selectedOption, + setSelectedOption, + hasOrganizations: !!hasOrganizations, + handleOptionSelect, + }); } else if (currentStep === "enterApiKey") { - if (key.return) { - if (isValidAnthropicApiKey(apiKey)) { - handleApiKeySubmit(); - } else { - setErrorMessage(getApiKeyValidationError(apiKey)); - } - } else if (key.backspace || key.delete) { - setApiKey(apiKey.slice(0, -1)); - setErrorMessage(""); - } else if (input && !key.ctrl && !key.meta) { - setApiKey(apiKey + input); - setErrorMessage(""); - } + handleApiKeyInput({ + input, + key, + apiKey, + setApiKey, + setErrorMessage, + handleApiKeySubmit, + }); } else if (currentStep === "success" || currentStep === "error") { if (key.return) { closeCurrentScreen(); diff --git a/src/ui/SyntaxHighlighter.ts b/src/ui/SyntaxHighlighter.ts index 7fd3b60b8..40c9ebff8 100644 --- a/src/ui/SyntaxHighlighter.ts +++ b/src/ui/SyntaxHighlighter.ts @@ -135,12 +135,12 @@ export function highlightCode( const children: React.ReactNode[] = []; for (let i = 0; i < node.children.length; i++) { const child = processNode(node.children[i], color); - if (child) { - if (Array.isArray(child)) { - children.push(...child); - } else { - children.push(child); - } + if (!child) continue; + + if (Array.isArray(child)) { + children.push(...child); + } else { + children.push(child); } } @@ -180,12 +180,12 @@ export function highlightCode( if (result.children) { for (let i = 0; i < result.children.length; i++) { const element = processNode(result.children[i]); - if (element) { - if (Array.isArray(element)) { - elements.push(...element); - } else { - elements.push(element); - } + if (!element) continue; + + if (Array.isArray(element)) { + elements.push(...element); + } else { + elements.push(element); } } } diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index e3c8bc27c..8539f8db6 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -1,5 +1,5 @@ import { Box, Text } from "ink"; -import React, { useEffect, useMemo, useState } from "react"; +import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useServices } from "../hooks/useService.js"; import type { PermissionMode } from "../permissions/types.js"; @@ -17,7 +17,10 @@ import { ModeIndicator } from "./components/ModeIndicator.js"; import { StaticChatContent } from "./components/StaticChatContent.js"; import { ToolPermissionSelector } from "./components/ToolPermissionSelector.js"; import { ConfigSelector } from "./ConfigSelector.js"; -import { useNavigation } from "./context/NavigationContext.js"; +import { + useNavigation, + type NavigationScreen, +} from "./context/NavigationContext.js"; import { startFileIndexing } from "./FileSearchUI.js"; import { FreeTrialStatus } from "./FreeTrialStatus.js"; import { FreeTrialTransitionUI } from "./FreeTrialTransitionUI.js"; @@ -29,10 +32,153 @@ import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; import { LoadingAnimation } from "./LoadingAnimation.js"; import { ModelSelector } from "./ModelSelector.js"; import { OrganizationSelector } from "./OrganizationSelector.js"; +import type { SelectorOption } from "./Selector.js"; import { Timer } from "./Timer.js"; import { UpdateNotification } from "./UpdateNotification.js"; import { UserInput } from "./UserInput.js"; +// Type definitions for selectors +interface ConfigOption extends SelectorOption { + type: "local" | "assistant" | "create"; + slug?: string; +} + +interface ModelOption extends SelectorOption { + index: number; + provider: string; +} + +// Helper function to get repo URL text +function getRepoUrlText(remoteUrl?: string): string { + let url = remoteUrl ?? ""; + if (!url) { + const isGit = isGitRepo(); + if (isGit) { + const gitUrl = getGitRemoteUrl(); + if (gitUrl) { + url = gitUrl; + } + } + } + if (!url) { + url = process.cwd(); + } + + url = url.replace(/\.git$/, ""); + url = url.replace(/^(https|http):\/\/.*?\//, ""); + return url; +} + +// Custom hook for intro message +function useIntroMessage( + isRemoteMode: boolean, + services: any, + allServicesReady: boolean, +) { + const [showIntroMessage, setShowIntroMessage] = useState(false); + + useEffect(() => { + const shouldShow = + !isRemoteMode && + allServicesReady && + !!services.config?.config && + !!services.model?.model && + !!services.mcp?.mcpService; + + setShowIntroMessage(shouldShow); + }, [ + isRemoteMode, + allServicesReady, + services.config?.config, + services.model?.model, + services.mcp?.mcpService, + ]); + + return [showIntroMessage, setShowIntroMessage] as const; +} + +// Custom hook for login handling +function useLoginHandlers( + navigateTo: any, + navState: any, + closeCurrentScreen: () => void, +) { + const handleLoginPrompt = useCallback( + (promptText: string): Promise => { + return new Promise((resolve) => { + navigateTo("login", { text: promptText, resolve }); + }); + }, + [navigateTo], + ); + + const handleLoginTokenSubmit = useCallback( + (token: string) => { + if (navState.screenData?.resolve) { + navState.screenData.resolve(token); + closeCurrentScreen(); + } + }, + [navState.screenData, closeCurrentScreen], + ); + + return { handleLoginPrompt, handleLoginTokenSubmit }; +} + +// Custom hook for mode tracking +function useCurrentMode() { + const [currentMode, setCurrentMode] = useState( + modeService.getCurrentMode(), + ); + + useEffect(() => { + const handleModeChange = (newMode: PermissionMode) => { + setCurrentMode(newMode); + }; + + modeService.on("modeChanged", handleModeChange); + return () => { + modeService.off("modeChanged", handleModeChange); + }; + }, []); + + return currentMode; +} + +// Custom hook to combine all selector logic +function useSelectors( + configPath: string | undefined, + setMessages: React.Dispatch>, + resetChatHistory: () => void, +) { + const { handleOrganizationSelect } = useOrganizationSelector({ + onMessage: (message) => { + setMessages((prev) => [...prev, message]); + }, + onChatReset: resetChatHistory, + }); + + const { handleConfigSelect } = useConfigSelector({ + configPath, + onMessage: (message) => { + setMessages((prev) => [...prev, message]); + }, + onChatReset: resetChatHistory, + }); + + const { handleModelSelect } = useModelSelector({ + onMessage: (message) => { + setMessages((prev) => [...prev, message]); + }, + }); + + return { + handleOrganizationSelect, + handleConfigSelect, + handleModelSelect, + }; +} + interface TUIChatProps { // Remote mode props remoteUrl?: string; @@ -44,6 +190,200 @@ interface TUIChatProps { additionalRules?: string[]; } +// Bottom status bar component +interface BottomStatusBarProps { + currentMode: PermissionMode; + repoURlText: string; + isRemoteMode: boolean; + services: any; + navState: any; + navigateTo: (screen: NavigationScreen, data?: any) => void; + closeCurrentScreen: () => void; +} + +const BottomStatusBar: React.FC = ({ + currentMode, + repoURlText, + isRemoteMode, + services, + navState, + navigateTo, + closeCurrentScreen, +}) => ( + + + {currentMode === "normal" && ( + <> + + {repoURlText} + + + + )} + + + + {!isRemoteMode && services.model?.model && ( + { + if (shouldShow && navState.currentScreen === "chat") { + navigateTo("free-trial"); + } else if (!shouldShow && navState.currentScreen === "free-trial") { + closeCurrentScreen(); + } + }} + /> + )} + + + + + +); + +// Component to handle all screen-specific rendering +interface ScreenContentProps { + isScreenActive: (screen: NavigationScreen) => boolean; + navState: any; + services: any; + handleLoginTokenSubmit: (token: string) => void; + handleOrganizationSelect: ( + organizationId: string | null, + organizationName: string, + ) => Promise; + handleConfigSelect: (config: ConfigOption) => Promise; + handleModelSelect: (model: ModelOption) => Promise; + handleReload: () => Promise; + closeCurrentScreen: () => void; + activePermissionRequest: any; + handleToolPermissionResponse: ( + requestId: string, + approved: boolean, + createPolicy?: boolean, + ) => void; + handleUserMessage: (message: string) => void; + isWaitingForResponse: boolean; + inputMode: boolean; + handleInterrupt: () => void; + handleFileAttached: (filePath: string, content: string) => void; + isInputDisabled: boolean; + isRemoteMode: boolean; +} + +const ScreenContent: React.FC = ({ + isScreenActive, + navState, + services, + handleLoginTokenSubmit, + handleOrganizationSelect, + handleConfigSelect, + handleModelSelect, + handleReload, + closeCurrentScreen, + activePermissionRequest, + handleToolPermissionResponse, + handleUserMessage, + isWaitingForResponse, + inputMode, + handleInterrupt, + handleFileAttached, + isInputDisabled, + isRemoteMode, +}) => { + // Login prompt + if (isScreenActive("login") && navState.screenData) { + return ( + + + Login Required + + {navState.screenData.text} + + + ); + } + + // Organization selector + if (isScreenActive("organization")) { + return ( + + ); + } + + // Config selector + if (isScreenActive("config")) { + return ( + + ); + } + + // Model selector + if (isScreenActive("model")) { + return ( + + ); + } + + // Free trial transition UI + if (isScreenActive("free-trial")) { + return ; + } + + // Chat screen with input area + if (isScreenActive("chat")) { + if (activePermissionRequest) { + return ( + + ); + } + return ( + + ); + } + + return null; +}; + const TUIChat: React.FC = ({ remoteUrl, configPath, @@ -56,25 +396,7 @@ const TUIChat: React.FC = ({ return !!remoteUrl; }, [remoteUrl]); - const repoURlText = useMemo(() => { - let url = remoteUrl ?? ""; - if (!url) { - const isGit = isGitRepo(); - if (isGit) { - const gitUrl = getGitRemoteUrl(); - if (gitUrl) { - url = gitUrl; - } - } - } - if (!url) { - url = process.cwd(); - } - - url = url.replace(/\.git$/, ""); - url = url.replace(/^(https|http):\/\/.*?\//, ""); - return url; - }, [remoteUrl]); + const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [remoteUrl]); // Get all services reactively - only in normal mode const { services, allReady: allServicesReady } = useServices<{ @@ -93,25 +415,22 @@ const TUIChat: React.FC = ({ isScreenActive, } = useNavigation(); - // State for intro message display - const [showIntroMessage, setShowIntroMessage] = useState(false); - - // State for current mode (for hiding cwd in plan/auto modes) - const [currentMode, setCurrentMode] = useState( - modeService.getCurrentMode(), + // Use intro message hook + const [showIntroMessage, setShowIntroMessage] = useIntroMessage( + isRemoteMode, + services, + allServicesReady, ); - // Listen for mode changes to update UI - useEffect(() => { - const handleModeChange = (newMode: PermissionMode) => { - setCurrentMode(newMode); - }; + // State for current mode (for hiding cwd in plan/auto modes) + const currentMode = useCurrentMode(); - modeService.on("modeChanged", handleModeChange); - return () => { - modeService.off("modeChanged", handleModeChange); - }; - }, []); + // Use login handlers + const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers( + navigateTo, + navState, + closeCurrentScreen, + ); // Start file indexing as soon as the component mounts useEffect(() => { @@ -121,44 +440,6 @@ const TUIChat: React.FC = ({ }); }, []); - // Show intro message when services are ready (only in non-remote mode) - useEffect(() => { - if (!isRemoteMode) { - if ( - allServicesReady && - services.config?.config && - services.model?.model && - services.mcp?.mcpService - ) { - setShowIntroMessage(true); - } else { - // Reset intro message when services are not ready (during transitions) - setShowIntroMessage(false); - } - } - }, [ - isRemoteMode, - allServicesReady, - services.config?.config, - services.model?.model, - services.mcp?.mcpService, - ]); - - // Custom login prompt handler for TUI - const handleLoginPrompt = (promptText: string): Promise => { - return new Promise((resolve) => { - navigateTo("login", { text: promptText, resolve }); - }); - }; - - // Handle login token submission - const handleLoginTokenSubmit = (token: string) => { - if (navState.screenData?.resolve) { - navState.screenData.resolve(token); - closeCurrentScreen(); - } - }; - // Service reload handlers - these will trigger reactive updates const handleReload = async () => { // Services will automatically update the UI when they reload @@ -199,26 +480,8 @@ const TUIChat: React.FC = ({ const { renderMessage } = useMessageRenderer(); - const { handleOrganizationSelect } = useOrganizationSelector({ - onMessage: (message) => { - setMessages((prev) => [...prev, message]); - }, - onChatReset: resetChatHistory, - }); - - const { handleConfigSelect } = useConfigSelector({ - configPath, - onMessage: (message) => { - setMessages((prev) => [...prev, message]); - }, - onChatReset: resetChatHistory, - }); - - const { handleModelSelect } = useModelSelector({ - onMessage: (message) => { - setMessages((prev) => [...prev, message]); - }, - }); + const { handleOrganizationSelect, handleConfigSelect, handleModelSelect } = + useSelectors(configPath, setMessages, resetChatHistory); // Determine if input should be disabled // Allow input even when services are loading, but disable for UI overlays @@ -264,127 +527,38 @@ const TUIChat: React.FC = ({ )} - {/* Login prompt - shows above input when active */} - {isScreenActive("login") && navState.screenData && ( - - - Login Required - - {navState.screenData.text} - - - )} - - {/* Organization selector - shows above input when active */} - {isScreenActive("organization") && ( - - )} - - {/* Config selector - shows above input when active */} - {isScreenActive("config") && ( - - )} - - {/* Model selector - shows above input when active */} - {isScreenActive("model") && ( - - )} - - {/* Free trial transition UI - replaces input when active */} - {isScreenActive("free-trial") && ( - - )} - - {/* Input area - only show when showing chat screen */} - {isScreenActive("chat") && ( - <> - {/* Show permission selector when there's an active permission request */} - {activePermissionRequest ? ( - - ) : ( - - )} - - )} + {/* All screen-specific content */} + {/* Free trial status and Continue CLI info - always show */} - - - {/* Only show cwd in normal mode to save space in plan/auto modes */} - {currentMode === "normal" && ( - <> - - {repoURlText} - - - - )} - - - - {!isRemoteMode && services.model?.model && ( - { - if (shouldShow && navState.currentScreen === "chat") { - navigateTo("free-trial"); - } else if ( - !shouldShow && - navState.currentScreen === "free-trial" - ) { - closeCurrentScreen(); - } - }} - /> - )} - - - - - + ); diff --git a/src/ui/TextBuffer.ts b/src/ui/TextBuffer.ts index 0e0d0fc01..1696f066a 100644 --- a/src/ui/TextBuffer.ts +++ b/src/ui/TextBuffer.ts @@ -137,81 +137,69 @@ export class TextBuffer { this._cursor = 0; } - handleInput(input: string, key: Key): boolean { - // Detect option key combinations through escape sequences - const isOptionKey = input.startsWith("\u001b") && input.length > 1; + private handleOptionKey(sequence: string): boolean { + // Option + backspace (usually \u001b\u0008 or \u001b\u007f) + if (sequence === "\u0008" || sequence === "\u007f") { + this.deleteWordBackward(); + return true; + } + return true; // Consume other option sequences + } - // Handle option key combinations (detected through escape sequences) - if (isOptionKey) { - const sequence = input.slice(1); - - // Option + backspace (usually \u001b\u0008 or \u001b\u007f) - if (sequence === "\u0008" || sequence === "\u007f") { + private handleCtrlKey(input: string): boolean { + switch (input) { + case "a": + this.moveToStart(); + return true; + case "e": + this.moveToEnd(); + return true; + case "u": + // Delete from cursor to start of line + this._text = this._text.slice(this._cursor); + this._cursor = 0; + return true; + case "k": + // Delete from cursor to end of line + this._text = this._text.slice(0, this._cursor); + return true; + case "w": this.deleteWordBackward(); return true; - } - - return true; // Consume other option sequences + case "d": + this.deleteWordForward(); + return true; + default: + return false; } + } - // Handle special key combinations based on input character - if (key.ctrl) { - switch (input) { - case "a": - this.moveToStart(); - return true; - case "e": - this.moveToEnd(); - return true; - case "u": - // Delete from cursor to start of line - this._text = this._text.slice(this._cursor); - this._cursor = 0; - return true; - case "k": - // Delete from cursor to end of line - this._text = this._text.slice(0, this._cursor); - return true; - case "w": - this.deleteWordBackward(); - return true; - case "d": - this.deleteWordForward(); - return true; - } + private handleMetaKey(input: string, key: Key): boolean { + if (key.backspace || key.delete) { + this.deleteWordBackward(); + return true; } - - // Handle meta key combinations (cmd on Mac) - if (key.meta) { - if (key.backspace) { - this.deleteWordBackward(); - return true; - } - if (key.delete) { - this.deleteWordBackward(); - return true; - } - if (key.leftArrow) { - this.moveWordLeft(); - return true; - } - if (key.rightArrow) { - this.moveWordRight(); - return true; - } - - // Handle option+left/right as characters (on Mac, option+arrow sends character codes) - if (input === "b") { - this.moveWordLeft(); - return true; - } - if (input === "f") { - this.moveWordRight(); - return true; - } + if (key.leftArrow) { + this.moveWordLeft(); + return true; } + if (key.rightArrow) { + this.moveWordRight(); + return true; + } + // Handle option+left/right as characters (on Mac, option+arrow sends character codes) + if (input === "b") { + this.moveWordLeft(); + return true; + } + if (input === "f") { + this.moveWordRight(); + return true; + } + return false; + } - // Handle arrow keys + private handleArrowKeys(key: Key): boolean { if (key.leftArrow && !key.meta) { this.moveLeft(); return true; @@ -220,15 +208,46 @@ export class TextBuffer { this.moveRight(); return true; } + return false; + } - // Handle backspace/delete + private handleDeleteKeys(key: Key): boolean { // On Mac, backspace key registers as key.delete, so treat it as backward deletion - if (key.delete && !key.meta) { + if ((key.delete || key.backspace) && !key.meta) { this.deleteBackward(); return true; } - if (key.backspace && !key.meta) { - this.deleteBackward(); + return false; + } + + handleInput(input: string, key: Key): boolean { + // Detect option key combinations through escape sequences + const isOptionKey = input.startsWith("\u001b") && input.length > 1; + + // Handle option key combinations (detected through escape sequences) + if (isOptionKey) { + return this.handleOptionKey(input.slice(1)); + } + + // Handle special key combinations based on input character + if (key.ctrl) { + const handled = this.handleCtrlKey(input); + if (handled) return true; + } + + // Handle meta key combinations (cmd on Mac) + if (key.meta) { + const handled = this.handleMetaKey(input, key); + if (handled) return true; + } + + // Handle arrow keys + if (this.handleArrowKeys(key)) { + return true; + } + + // Handle backspace/delete + if (this.handleDeleteKeys(key)) { return true; } diff --git a/src/ui/UpdateNotification.test.tsx b/src/ui/UpdateNotification.test.tsx index 8d1e36d04..dcedc5a5e 100644 --- a/src/ui/UpdateNotification.test.tsx +++ b/src/ui/UpdateNotification.test.tsx @@ -49,10 +49,10 @@ describe("UpdateNotification", () => { afterEach(() => { // Restore original NODE_ENV - if (originalNodeEnv !== undefined) { - process.env.NODE_ENV = originalNodeEnv; - } else { + if (originalNodeEnv === undefined) { delete process.env.NODE_ENV; + } else { + process.env.NODE_ENV = originalNodeEnv; } }); diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index 021ed39a7..ff7d5ad29 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -7,9 +7,12 @@ import type { PermissionMode } from "../permissions/types.js"; import { SERVICE_NAMES, serviceContainer } from "../services/index.js"; import { modeService } from "../services/ModeService.js"; import { InputHistory } from "../util/inputHistory.js"; -import { logger } from "../util/logger.js"; import { FileSearchUI } from "./FileSearchUI.js"; +import { + handleControlKeys, + updateTextBufferState, +} from "./hooks/useUserInput.js"; import { SlashCommandUI } from "./SlashCommandUI.js"; import { TextBuffer } from "./TextBuffer.js"; @@ -92,47 +95,52 @@ const UserInput: React.FC = ({ // Update slash command UI state based on input const updateSlashCommandState = (text: string, cursor: number) => { // Only show slash commands if slash is the very first character - if (text.trimStart().startsWith("/")) { - const trimmedText = text.trimStart(); - const beforeCursor = trimmedText.slice( - 0, - cursor - (text.length - trimmedText.length), - ); - - // Only show if cursor is after the slash and before any whitespace - if (beforeCursor.length > 0 && beforeCursor.startsWith("/")) { - const afterSlash = beforeCursor.slice(1); - - if (!afterSlash.includes(" ") && !afterSlash.includes("\n")) { - // We're in a slash command context - check if it's a complete command - const allCommands = getSlashCommands(); - const exactMatch = allCommands.find((cmd) => cmd.name === afterSlash); - - // Hide selector if we have an exact match and there's a space after cursor - if (exactMatch) { - const restOfText = text.slice(cursor); - // Only hide if there's a space or newline immediately after cursor - // Don't hide just because we're at the end - user might want to see the suggestion - if (restOfText.startsWith(" ") || restOfText.startsWith("\n")) { - setShowSlashCommands(false); - return; - } - } - - // Show selector for partial matches - setShowSlashCommands(true); - setSlashCommandFilter(afterSlash); - setSelectedCommandIndex(0); - setShowFileSearch(false); - } else { - setShowSlashCommands(false); - } - } else { - setShowSlashCommands(false); - } - } else { + if (!text.trimStart().startsWith("/")) { setShowSlashCommands(false); + return; } + + const trimmedText = text.trimStart(); + const beforeCursor = trimmedText.slice( + 0, + cursor - (text.length - trimmedText.length), + ); + + // Only show if cursor is after the slash and before any whitespace + if (beforeCursor.length === 0 || !beforeCursor.startsWith("/")) { + setShowSlashCommands(false); + return; + } + + const afterSlash = beforeCursor.slice(1); + + // Check if we have whitespace in the command + if (afterSlash.includes(" ") || afterSlash.includes("\n")) { + setShowSlashCommands(false); + return; + } + + // We're in a slash command context - check if it's a complete command + const allCommands = getSlashCommands(); + const exactMatch = allCommands.find((cmd) => cmd.name === afterSlash); + + // Hide selector if we have an exact match and there's a space after cursor + if (exactMatch) { + const restOfText = text.slice(cursor); + // Only hide if there's a space or newline immediately after cursor + const shouldHide = + restOfText.startsWith(" ") || restOfText.startsWith("\n"); + if (shouldHide) { + setShowSlashCommands(false); + return; + } + } + + // Show selector for partial matches + setShowSlashCommands(true); + setSlashCommandFilter(afterSlash); + setSelectedCommandIndex(0); + setShowFileSearch(false); }; // Update file search UI state based on input @@ -147,21 +155,21 @@ const UserInput: React.FC = ({ const beforeCursor = text.slice(0, cursor); const lastAtIndex = beforeCursor.lastIndexOf("@"); - if (lastAtIndex !== -1) { + if (lastAtIndex === -1) { + setShowFileSearch(false); + } else { // Check if there's any whitespace between the last @ and cursor const afterAt = beforeCursor.slice(lastAtIndex + 1); - if (!afterAt.includes(" ") && !afterAt.includes("\n")) { + if (afterAt.includes(" ") || afterAt.includes("\n")) { + setShowFileSearch(false); + } else { // We're in a file search context setShowFileSearch(true); setFileSearchFilter(afterAt); setSelectedFileIndex(0); setShowSlashCommands(false); - } else { - setShowFileSearch(false); } - } else { - setShowFileSearch(false); } }; @@ -240,39 +248,163 @@ const UserInput: React.FC = ({ } }; + const handleSlashCommandNavigation = (key: any): boolean => { + const filteredCommands = getFilteredCommands(); + + if (key.upArrow) { + setSelectedCommandIndex((prev) => + prev > 0 ? prev - 1 : filteredCommands.length - 1, + ); + return true; + } + + if (key.downArrow) { + setSelectedCommandIndex((prev) => + prev < filteredCommands.length - 1 ? prev + 1 : 0, + ); + return true; + } + + if ((key.return && !key.shift) || key.tab) { + if (filteredCommands.length > 0) { + selectSlashCommand(filteredCommands[selectedCommandIndex].name); + } + return true; + } + + return false; + }; + + const handleFileSearchNavigation = (key: any): boolean => { + if (key.upArrow) { + setSelectedFileIndex((prev) => + prev > 0 ? prev - 1 : Math.max(0, Math.min(currentFiles.length - 1, 9)), + ); + return true; + } + + if (key.downArrow) { + setSelectedFileIndex((prev) => + prev < Math.min(currentFiles.length - 1, 9) ? prev + 1 : 0, + ); + return true; + } + + if ((key.return && !key.shift) || key.tab) { + if (currentFiles.length > 0 && selectedFileIndex < currentFiles.length) { + selectFile(currentFiles[selectedFileIndex].path); + } + return true; + } + + return false; + }; + + const handleHistoryNavigation = (key: any): boolean => { + if (!showSlashCommands && !showFileSearch) { + if (key.upArrow) { + const historyEntry = inputHistory.navigateUp(inputText); + if (historyEntry !== null) { + textBuffer.setText(historyEntry); + textBuffer.setCursor(historyEntry.length); + setInputText(historyEntry); + setCursorPosition(historyEntry.length); + } + return true; + } + + if (key.downArrow) { + const historyEntry = inputHistory.navigateDown(); + if (historyEntry !== null) { + textBuffer.setText(historyEntry); + textBuffer.setCursor(historyEntry.length); + setInputText(historyEntry); + setCursorPosition(historyEntry.length); + } + return true; + } + } + return false; + }; + + const handleEnterKey = (key: any): boolean => { + if (key.return && !key.shift) { + if (textBuffer.text.trim() && !isWaitingForResponse) { + const submittedText = textBuffer.text.trim(); + inputHistory.addEntry(submittedText); + onSubmit(submittedText); + textBuffer.clear(); + setInputText(""); + setCursorPosition(0); + setShowSlashCommands(false); + } + return true; + } + return false; + }; + + const handleNewLine = (input: string, key: any): boolean => { + if (input === "\r" || input === "\\\r") { + const handled = textBuffer.handleInput("\n", key); + if (handled) { + const newText = textBuffer.text; + const newCursor = textBuffer.cursor; + setInputText(newText); + setCursorPosition(newCursor); + updateSlashCommandState(newText, newCursor); + updateFileSearchState(newText, newCursor); + } + return true; + } + return false; + }; + + const handleEscapeKey = (key: any): boolean => { + if (!key.escape) return false; + + // Handle escape key to interrupt streaming + if (isWaitingForResponse && onInterrupt) { + onInterrupt(); + return true; + } + + // Handle escape key to close slash command UI + if (showSlashCommands && inputMode) { + setShowSlashCommands(false); + return true; + } + + // Handle escape key to close file search UI + if (showFileSearch && inputMode) { + setShowFileSearch(false); + return true; + } + + return false; + }; + useInput((input, key) => { // Don't handle any input when disabled if (disabled) { return; } - if (key.ctrl && (input === "c" || input === "d")) { - exit(); + + // Handle control keys + if ( + handleControlKeys({ + input, + key, + exit, + showSlashCommands, + showFileSearch, + cycleModes, + }) + ) { return; } - // Handle Shift+Tab to cycle through modes - if (key.tab && key.shift && !showSlashCommands && !showFileSearch) { - cycleModes().catch((error) => { - logger.error("Failed to cycle modes:", error); - }); - return; - } - - // Handle escape key to interrupt streaming - if (key.escape && isWaitingForResponse && onInterrupt) { - onInterrupt(); - return; - } - - // Handle escape key to close slash command UI - if (key.escape && showSlashCommands && inputMode) { - setShowSlashCommands(false); - return; - } - - // Handle escape key to close file search UI - if (key.escape && showFileSearch && inputMode) { - setShowFileSearch(false); + // Handle escape key variations + if (handleEscapeKey(key)) { return; } @@ -287,127 +419,30 @@ const UserInput: React.FC = ({ // Handle slash command navigation if (showSlashCommands) { - const filteredCommands = getFilteredCommands(); - - if (key.upArrow) { - setSelectedCommandIndex((prev) => - prev > 0 ? prev - 1 : filteredCommands.length - 1, - ); - return; - } - - if (key.downArrow) { - setSelectedCommandIndex((prev) => - prev < filteredCommands.length - 1 ? prev + 1 : 0, - ); - return; - } - - if (key.return && !key.shift) { - if (filteredCommands.length > 0) { - selectSlashCommand(filteredCommands[selectedCommandIndex].name); - } - return; - } - - if (key.tab) { - if (filteredCommands.length > 0) { - selectSlashCommand(filteredCommands[selectedCommandIndex].name); - } + if (handleSlashCommandNavigation(key)) { return; } } // Handle file search navigation if (showFileSearch) { - if (key.upArrow) { - setSelectedFileIndex((prev) => - prev > 0 - ? prev - 1 - : Math.max(0, Math.min(currentFiles.length - 1, 9)), - ); - return; - } - - if (key.downArrow) { - setSelectedFileIndex((prev) => - prev < Math.min(currentFiles.length - 1, 9) ? prev + 1 : 0, - ); - return; - } - - if (key.return && !key.shift) { - if ( - currentFiles.length > 0 && - selectedFileIndex < currentFiles.length - ) { - selectFile(currentFiles[selectedFileIndex].path); - } - return; - } - - if (key.tab) { - if ( - currentFiles.length > 0 && - selectedFileIndex < currentFiles.length - ) { - selectFile(currentFiles[selectedFileIndex].path); - } + if (handleFileSearchNavigation(key)) { return; } } - // Handle input history navigation (only when not in slash command or file search mode) - if (!showSlashCommands && !showFileSearch) { - if (key.upArrow) { - const historyEntry = inputHistory.navigateUp(inputText); - if (historyEntry !== null) { - textBuffer.setText(historyEntry); - textBuffer.setCursor(historyEntry.length); - setInputText(historyEntry); - setCursorPosition(historyEntry.length); - } - return; - } - - if (key.downArrow) { - const historyEntry = inputHistory.navigateDown(); - if (historyEntry !== null) { - textBuffer.setText(historyEntry); - textBuffer.setCursor(historyEntry.length); - setInputText(historyEntry); - setCursorPosition(historyEntry.length); - } - return; - } - } - - // Handle Enter key (regular enter for submit) - if (key.return && !key.shift) { - if (textBuffer.text.trim() && !isWaitingForResponse) { - const submittedText = textBuffer.text.trim(); - inputHistory.addEntry(submittedText); - onSubmit(submittedText); - textBuffer.clear(); - setInputText(""); - setCursorPosition(0); - setShowSlashCommands(false); - } - // Note: Enter key is already blocked during streaming by the inputMode check above + // Handle input history navigation + if (handleHistoryNavigation(key)) { return; } - // Handle Shift+Enter (carriage return character) for new line - if (input === "\r" || input === "\\\r") { - const handled = textBuffer.handleInput("\n", key); - if (handled) { - const newText = textBuffer.text; - const newCursor = textBuffer.cursor; - setInputText(newText); - setCursorPosition(newCursor); - updateSlashCommandState(newText, newCursor); - updateFileSearchState(newText, newCursor); - } + // Handle Enter key + if (handleEnterKey(key)) { + return; + } + + // Handle Shift+Enter (new line) + if (handleNewLine(input, key)) { return; } @@ -415,17 +450,15 @@ const UserInput: React.FC = ({ const handled = textBuffer.handleInput(input, key); // Update React state to trigger re-render - if (handled) { - const newText = textBuffer.text; - const newCursor = textBuffer.cursor; - setInputText(newText); - setCursorPosition(newCursor); - updateSlashCommandState(newText, newCursor); - updateFileSearchState(newText, newCursor); - - // Reset history navigation when user starts typing - inputHistory.resetNavigation(); - } + updateTextBufferState({ + handled, + textBuffer, + setInputText, + setCursorPosition, + updateSlashCommandState, + updateFileSearchState, + inputHistory, + }); }); const renderInputText = () => { diff --git a/src/ui/components/ToolPreview.tsx b/src/ui/components/ToolPreview.tsx index e6c5e83d4..43145b6eb 100644 --- a/src/ui/components/ToolPreview.tsx +++ b/src/ui/components/ToolPreview.tsx @@ -51,7 +51,7 @@ export const ToolPreview: React.FC = ({ let message = `Will call ${getToolDisplayName(toolName)}`; const argCount = Object.keys(toolArgs || {}).length; if (argCount > 0) { - message += ` with ${argCount} argument${argCount !== 1 ? "s" : ""}`; + message += ` with ${argCount} argument${argCount === 1 ? "" : "s"}`; } return ( diff --git a/src/ui/hooks/useChat.helpers.ts b/src/ui/hooks/useChat.helpers.ts new file mode 100644 index 000000000..a0599bf7d --- /dev/null +++ b/src/ui/hooks/useChat.helpers.ts @@ -0,0 +1,357 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; + +import { initializeChatHistory } from "../../commands/chat.js"; +import { compactChatHistory } from "../../compaction.js"; +import { loadSession, saveSession } from "../../session.js"; +import { posthogService } from "../../telemetry/posthogService.js"; +import { telemetryService } from "../../telemetry/telemetryService.js"; +import { formatError } from "../../util/formatError.js"; +import { logger } from "../../util/logger.js"; +import { shouldAutoCompact } from "../../util/tokenizer.js"; +import { DisplayMessage } from "../types.js"; + +import { SlashCommandResult } from "./useChat.types.js"; + +/** + * Initialize chat history with proper system message + */ +export async function initChatHistory( + resume?: boolean, + additionalRules?: string[], +): Promise { + if (resume) { + const savedHistory = loadSession(); + if (savedHistory) { + return savedHistory; + } + } + + const history = await initializeChatHistory({ + resume, + rule: additionalRules, + }); + return history; +} + +/** + * Handle /org command + */ +export function handleOrgCommand(onShowOrgSelector: () => void): void { + posthogService.capture("useSlashCommand", { + name: "org", + }); + onShowOrgSelector(); +} + +/** + * Handle /config command + */ +export function handleConfigCommand(onShowConfigSelector: () => void): void { + posthogService.capture("useSlashCommand", { + name: "config", + }); + onShowConfigSelector(); +} + +interface HandleCompactCommandOptions { + chatHistory: ChatCompletionMessageParam[]; + model: any; + llmApi: any; + setChatHistory: React.Dispatch< + React.SetStateAction + >; + setMessages: React.Dispatch>; + setCompactionIndex: React.Dispatch>; +} + +/** + * Handle compaction command + */ +export async function handleCompactCommand({ + chatHistory, + model, + llmApi, + setChatHistory, + setMessages, + setCompactionIndex, +}: HandleCompactCommandOptions): Promise { + setMessages((prev) => [ + ...prev, + { + role: "system", + content: "Compacting chat history...", + messageType: "system" as const, + }, + ]); + + try { + const result = await compactChatHistory(chatHistory, model, llmApi); + + // Replace chat history with compacted version + setChatHistory(result.compactedHistory); + setCompactionIndex(result.compactionIndex); + + // Save the compacted session + saveSession(result.compactedHistory); + + setMessages((prev) => [ + ...prev, + { + role: "system", + content: "Chat history compacted successfully.", + messageType: "system" as const, + }, + ]); + } catch (error) { + logger.error("Compaction failed:", error); + setMessages((prev) => [ + ...prev, + { + role: "system", + content: `Compaction failed: ${formatError(error)}`, + messageType: "system" as const, + }, + ]); + } +} + +interface ProcessSlashCommandResultOptions { + result: SlashCommandResult; + chatHistory: ChatCompletionMessageParam[]; + setChatHistory: React.Dispatch< + React.SetStateAction + >; + setMessages: React.Dispatch>; + exit: () => void; + onShowConfigSelector: () => void; + onShowModelSelector?: () => void; +} + +/** + * Process slash command results + */ +export function processSlashCommandResult({ + result, + chatHistory, + setChatHistory, + setMessages, + exit, + onShowConfigSelector, + onShowModelSelector, +}: ProcessSlashCommandResultOptions): string | null { + if (result.exit) { + exit(); + return null; + } + + if (result.openConfigSelector) { + onShowConfigSelector(); + return null; + } + + if (result.openModelSelector && onShowModelSelector) { + onShowModelSelector(); + return null; + } + + if (result.clear) { + const systemMessage = chatHistory.find((msg) => msg.role === "system"); + const newHistory = systemMessage ? [systemMessage] : []; + setChatHistory(newHistory); + setMessages([]); + + if (result.output) { + setMessages([ + { + role: "system", + content: result.output, + messageType: "system" as const, + }, + ]); + } + return null; + } + + if (result.output) { + setMessages((prev) => [ + ...prev, + { + role: "system" as const, + content: result.output || "", + messageType: "system" as const, + } as DisplayMessage, + ]); + } + + return result.newInput || null; +} + +/** + * Format message with attached files + */ +export function formatMessageWithFiles( + message: string, + attachedFiles: Array<{ path: string; content: string }>, +): string { + if (attachedFiles.length === 0) { + return message; + } + + const fileContents = attachedFiles + .map((file) => `\n\n\n${file.content}\n`) + .join(""); + + return message + fileContents; +} + +/** + * Track telemetry for user message + */ +export function trackUserMessage(message: string, model?: any): void { + telemetryService.startActiveTime(); + telemetryService.logUserPrompt(message.length, message); + posthogService.capture("chat", { + model: model?.name, + provider: model?.provider, + }); +} + +interface HandleSpecialCommandsOptions { + message: string; + isRemoteMode: boolean; + remoteUrl?: string; + onShowOrgSelector: () => void; + onShowConfigSelector: () => void; + exit: () => void; + setMessages: React.Dispatch>; +} + +/** + * Handle special TUI commands + */ +export async function handleSpecialCommands({ + message, + isRemoteMode, + remoteUrl, + onShowOrgSelector, + onShowConfigSelector, + exit, + setMessages, +}: HandleSpecialCommandsOptions): Promise { + 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); + return true; + } + + // Handle /exit command in remote mode + if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") { + const { handleRemoteExit } = await import("./useChat.remote.helpers.js"); + await handleRemoteExit(remoteUrl, setMessages, exit); + return true; + } + + return false; +} + +interface HandleAutoCompactionOptions { + chatHistory: ChatCompletionMessageParam[]; + model: any; + llmApi: any; + compactionIndex: number | null; + setMessages: React.Dispatch>; + setChatHistory: React.Dispatch< + React.SetStateAction + >; + setCompactionIndex: React.Dispatch>; +} + +/** + * Handle auto-compaction when approaching context limit + */ +export async function handleAutoCompaction({ + chatHistory, + model, + llmApi, + compactionIndex, + setMessages, + setChatHistory, + setCompactionIndex, +}: HandleAutoCompactionOptions): Promise<{ + currentChatHistory: ChatCompletionMessageParam[]; + currentCompactionIndex: number | null; +}> { + if (!model || !shouldAutoCompact(chatHistory, model)) { + return { + currentChatHistory: chatHistory, + currentCompactionIndex: compactionIndex, + }; + } + + logger.info("Auto-compacting triggered in TUI mode"); + + setMessages((prev) => [ + ...prev, + { + role: "system", + content: "Approaching context limit. Auto-compacting chat history...", + messageType: "system" as const, + }, + ]); + + try { + if (!llmApi) { + throw new Error("LLM API is not available for auto-compaction"); + } + + // Compact the history WITHOUT the current user message + const result = await compactChatHistory(chatHistory, model, llmApi); + + // Update state + setChatHistory(result.compactedHistory); + setCompactionIndex(result.compactionIndex); + + // Save the compacted session + saveSession(result.compactedHistory); + + setMessages((prev) => [ + ...prev, + { + role: "system", + content: "✓ Chat history auto-compacted successfully.", + messageType: "system" as const, + }, + ]); + + return { + currentChatHistory: result.compactedHistory, + currentCompactionIndex: result.compactionIndex, + }; + } catch (error: any) { + const errorMessage = `Auto-compaction error: ${formatError(error)}`; + logger.error(errorMessage); + + setMessages((prev) => [ + ...prev, + { + role: "system", + content: `Warning: ${errorMessage}. Continuing without compaction...`, + messageType: "system" as const, + }, + ]); + + // Continue without compaction on error + return { + currentChatHistory: chatHistory, + currentCompactionIndex: compactionIndex, + }; + } +} diff --git a/src/ui/hooks/useChat.remote.helpers.ts b/src/ui/hooks/useChat.remote.helpers.ts new file mode 100644 index 000000000..32bafe57d --- /dev/null +++ b/src/ui/hooks/useChat.remote.helpers.ts @@ -0,0 +1,269 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; + +import { posthogService } from "../../telemetry/posthogService.js"; +import { logger } from "../../util/logger.js"; +import { DisplayMessage } from "../types.js"; + +import { RemoteServerState } from "./useChat.types.js"; + +/** + * Poll remote server for state updates + */ +async function pollRemoteServerState( + remoteUrl: string, +): Promise { + try { + const response = await fetch(`${remoteUrl}/state`); + if (!response.ok) { + throw new Error(`Failed to fetch state: ${response.statusText}`); + } + return await response.json(); + } catch (error) { + logger.error("Failed to poll server state:", error); + return null; + } +} + +interface SetupRemotePollingOptions { + remoteUrl: string; + setMessages: React.Dispatch>; + setChatHistory: React.Dispatch< + React.SetStateAction + >; + setIsWaitingForResponse: React.Dispatch>; + responseStartTime: number | null; + setResponseStartTime: React.Dispatch>; +} + +/** + * Setup remote mode polling + */ +export function setupRemotePolling({ + remoteUrl, + setMessages, + setChatHistory, + setIsWaitingForResponse, + responseStartTime, + setResponseStartTime, +}: SetupRemotePollingOptions): () => void { + let pollInterval: NodeJS.Timeout | null = null; + let isPolling = false; + let isMounted = true; + + const pollServerState = async () => { + if (!isMounted || isPolling) return; + isPolling = true; + + try { + const state = await pollRemoteServerState(remoteUrl); + if (state && isMounted) { + updateStateFromRemote({ + state, + setMessages, + setChatHistory, + setIsWaitingForResponse, + responseStartTime, + setResponseStartTime, + }); + } + } finally { + isPolling = false; + } + }; + + // Start polling immediately + pollServerState(); + + // Set up interval for continuous polling + pollInterval = setInterval(pollServerState, 500); + + return () => { + isMounted = false; + if (pollInterval !== null) { + clearInterval(pollInterval); + } + }; +} + +interface UpdateStateFromRemoteOptions { + state: RemoteServerState; + setMessages: React.Dispatch>; + setChatHistory: React.Dispatch< + React.SetStateAction + >; + setIsWaitingForResponse: React.Dispatch>; + responseStartTime: number | null; + setResponseStartTime: React.Dispatch>; +} + +/** + * Update local state from remote server state + */ +function updateStateFromRemote({ + state, + setMessages, + setChatHistory, + setIsWaitingForResponse, + responseStartTime, + setResponseStartTime, +}: UpdateStateFromRemoteOptions): void { + // Update messages from server + if (state.chatHistory) { + setMessages((prevMessages) => { + // Quick length check first + if (prevMessages.length !== state.chatHistory.length) { + return state.chatHistory as DisplayMessage[]; + } + + // Deep comparison - check if content actually changed + const hasChanged = state.chatHistory.some((msg: any, index: number) => { + const prevMsg = prevMessages[index]; + return ( + !prevMsg || + prevMsg.role !== msg.role || + prevMsg.content !== msg.content || + prevMsg.messageType !== msg.messageType || + prevMsg.toolName !== msg.toolName || + prevMsg.toolResult !== msg.toolResult + ); + }); + + // Only update if there are actual changes + return hasChanged + ? (state.chatHistory as DisplayMessage[]) + : prevMessages; + }); + + // Also update chat history for consistency + setChatHistory((prevChatHistory) => { + const newChatHistory = state.chatHistory.map((msg: any) => ({ + role: msg.role, + content: msg.content, + })); + + // Similar comparison for chat history + if (prevChatHistory.length !== newChatHistory.length) { + return newChatHistory; + } + + const hasChanged = newChatHistory.some((msg: any, index: number) => { + const prevMsg = prevChatHistory[index]; + return ( + !prevMsg || + prevMsg.role !== msg.role || + prevMsg.content !== msg.content + ); + }); + + return hasChanged ? newChatHistory : prevChatHistory; + }); + } + + // Update processing state + setIsWaitingForResponse(state.isProcessing || false); + if (state.isProcessing && !responseStartTime) { + setResponseStartTime(Date.now()); + } else if (!state.isProcessing && responseStartTime) { + setResponseStartTime(null); + } +} + +/** + * Handle /exit command in remote mode + */ +export async function handleRemoteExit( + remoteUrl: string, + setMessages: React.Dispatch>, + exit: () => void, +): Promise { + posthogService.capture("useSlashCommand", { + name: "exit", + }); + + try { + const response = await fetch(`${remoteUrl}/exit`, { + method: "POST", + }); + + if (response.ok) { + setMessages((prev) => [ + ...prev, + { + role: "system", + content: "Remote environment is shutting down...", + messageType: "system" as const, + }, + ]); + setTimeout(() => exit(), 1000); + } else { + const text = await response.text(); + logger.error("Remote shutdown failed:", text); + setMessages((prev) => [ + ...prev, + { + role: "system", + content: "Failed to shutdown remote environment", + messageType: "system" as const, + }, + ]); + } + } catch (error) { + logger.error("Failed to send exit request to remote server:", error); + setMessages((prev) => [ + ...prev, + { + role: "system", + content: "Error: Failed to connect to remote server for shutdown", + messageType: "system" as const, + }, + ]); + } +} + +interface HandleRemoteMessageOptions { + remoteUrl: string; + messageContent: string; + setMessages: React.Dispatch>; +} + +/** + * Send message to remote server + */ +export async function handleRemoteMessage({ + remoteUrl, + messageContent, + setMessages, +}: HandleRemoteMessageOptions): Promise { + try { + const response = await fetch(`${remoteUrl}/message`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ message: messageContent }), + }); + + if (!response.ok) { + const error = await response.json(); + setMessages((prev) => [ + ...prev, + { + role: "system", + content: `Error: ${error.error || "Failed to send message"}`, + messageType: "system" as const, + }, + ]); + } + // State will be updated by polling + } catch (error) { + logger.error("Failed to send message to remote server:", error); + setMessages((prev) => [ + ...prev, + { + role: "system", + content: `Error: Failed to connect to remote server`, + messageType: "system" as const, + }, + ]); + } +} diff --git a/src/ui/hooks/useChat.stream.helpers.ts b/src/ui/hooks/useChat.stream.helpers.ts new file mode 100644 index 000000000..810e849e5 --- /dev/null +++ b/src/ui/hooks/useChat.stream.helpers.ts @@ -0,0 +1,171 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; + +import { formatToolCall } from "../../tools/index.js"; +import { DisplayMessage } from "../types.js"; + +interface CreateStreamCallbacksOptions { + setMessages: React.Dispatch>; + setActivePermissionRequest: React.Dispatch>; +} + +/** + * Create stream callbacks for chat response + */ +export function createStreamCallbacks( + options: CreateStreamCallbacksOptions, + currentStreamingMessageRef: { current: any }, +): any { + const { setMessages, setActivePermissionRequest } = options; + + return { + onContent: (content: string) => { + if (!currentStreamingMessageRef.current) { + currentStreamingMessageRef.current = { + role: "assistant", + content: "", + isStreaming: true, + }; + } + currentStreamingMessageRef.current.content += content; + }, + onContentComplete: (content: string) => { + if (currentStreamingMessageRef.current) { + setMessages((prev) => [ + ...prev, + { + role: "assistant", + content: content, + isStreaming: false, + }, + ]); + currentStreamingMessageRef.current = null; + } + }, + onToolStart: (toolName: string, toolArgs?: any) => { + if ( + currentStreamingMessageRef.current && + currentStreamingMessageRef.current.content + ) { + const messageContent = currentStreamingMessageRef.current.content; + setMessages((prev) => [ + ...prev, + { + role: "assistant", + content: messageContent, + isStreaming: false, + }, + ]); + currentStreamingMessageRef.current = null; + } + + setMessages((prev) => [ + ...prev, + { + role: "system", + content: formatToolCall(toolName, toolArgs), + messageType: "tool-start", + toolName, + }, + ]); + }, + onToolResult: (result: string, toolName: string) => { + setMessages((prev) => { + const newMessages = [...prev]; + for (let i = newMessages.length - 1; i >= 0; i--) { + if ( + newMessages[i].messageType === "tool-start" && + newMessages[i].toolName === toolName + ) { + newMessages[i] = { + ...newMessages[i], + messageType: "tool-result", + toolResult: result, + }; + break; + } + } + return newMessages; + }); + }, + onToolError: (error: string, toolName?: string) => { + setMessages((prev) => [ + ...prev, + { + role: "system", + content: error, + messageType: "tool-error", + toolName, + }, + ]); + }, + onToolPermissionRequest: ( + toolName: string, + toolArgs: any, + requestId: string, + toolCallPreview?: any[], + ) => { + setActivePermissionRequest({ + toolName, + toolArgs, + requestId, + toolCallPreview, + }); + }, + }; +} + +interface ExecuteStreamingOptions { + newHistory: ChatCompletionMessageParam[]; + model: any; + llmApi: any; + controller: AbortController; + streamCallbacks: any; + currentCompactionIndex: number | null; +} + +/** + * Execute streaming chat response + */ +export async function executeStreaming({ + newHistory, + model, + llmApi, + controller, + streamCallbacks, + currentCompactionIndex, +}: ExecuteStreamingOptions): Promise { + const { getHistoryForLLM } = await import("../../compaction.js"); + const { streamChatResponse } = await import("../../streamChatResponse.js"); + + if (model && llmApi) { + if ( + currentCompactionIndex !== null && + currentCompactionIndex !== undefined + ) { + const historyForLLM = getHistoryForLLM( + newHistory, + currentCompactionIndex, + ); + const originalLength = historyForLLM.length; + + await streamChatResponse( + historyForLLM, + model, + llmApi, + controller, + streamCallbacks, + ); + + const newMessages = historyForLLM.slice(originalLength); + newHistory.push(...newMessages); + } else { + await streamChatResponse( + newHistory, + model, + llmApi, + controller, + streamCallbacks, + ); + } + } +} diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 6d634694b..ef965492f 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -1,47 +1,38 @@ -import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { BaseLlmApi } from "@continuedev/openai-adapters"; import { useApp } from "ink"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { useEffect, useState } from "react"; -import { initializeChatHistory } from "../../commands/chat.js"; -import { - compactChatHistory, - findCompactionIndex, - getHistoryForLLM, -} from "../../compaction.js"; +import { findCompactionIndex } from "../../compaction.js"; import { toolPermissionManager } from "../../permissions/permissionManager.js"; import { loadSession, saveSession } from "../../session.js"; import { handleSlashCommands } from "../../slashCommands.js"; -import { - StreamCallbacks, - streamChatResponse, -} from "../../streamChatResponse.js"; -import { posthogService } from "../../telemetry/posthogService.js"; import { telemetryService } from "../../telemetry/telemetryService.js"; -import { formatToolCall } from "../../tools/index.js"; -import { ToolCallPreview } from "../../tools/types.js"; import { formatError } from "../../util/formatError.js"; import { logger } from "../../util/logger.js"; -import { shouldAutoCompact } from "../../util/tokenizer.js"; import { DisplayMessage } from "../types.js"; -interface UseChatProps { - assistant?: AssistantUnrolled; - model?: ModelConfig; - llmApi?: BaseLlmApi; - initialPrompt?: string; - resume?: boolean; - additionalRules?: string[]; - onShowOrgSelector: () => void; - onShowConfigSelector: () => void; - onShowModelSelector?: () => void; - onLoginPrompt?: (promptText: string) => Promise; - onReload?: () => Promise; - // Remote mode props - isRemoteMode?: boolean; - remoteUrl?: string; -} +import { + handleCompactCommand, + initChatHistory, + processSlashCommandResult, + trackUserMessage, + handleAutoCompaction, + formatMessageWithFiles, + handleSpecialCommands, +} from "./useChat.helpers.js"; +import { + handleRemoteMessage, + setupRemotePolling, +} from "./useChat.remote.helpers.js"; +import { + createStreamCallbacks, + executeStreaming, +} from "./useChat.stream.helpers.js"; +import { + UseChatProps, + AttachedFile, + ActivePermissionRequest, +} from "./useChat.types.js"; export function useChat({ assistant, @@ -104,15 +95,9 @@ export function useChat({ // Capture initial rules to prevent re-initialization when rules change const [initialRules] = useState(additionalRules); - const [attachedFiles, setAttachedFiles] = useState< - Array<{ path: string; content: string }> - >([]); - const [activePermissionRequest, setActivePermissionRequest] = useState<{ - toolName: string; - toolArgs: any; - requestId: string; - toolCallPreview?: ToolCallPreview[]; - } | null>(null); + const [attachedFiles, setAttachedFiles] = useState([]); + const [activePermissionRequest, setActivePermissionRequest] = + useState(null); const [compactionIndex, setCompactionIndex] = useState(() => { // When resuming, check for compaction markers in the loaded history if (resume) { @@ -128,106 +113,14 @@ export function useChat({ useEffect(() => { if (!isRemoteMode || !remoteUrl || process.env.NODE_ENV === "test") return; - let pollInterval: NodeJS.Timeout | null = null; - let isPolling = false; - let isMounted = true; - - const pollServerState = async () => { - if (isPolling || !isMounted) return; // Prevent overlapping polls and check if still mounted - isPolling = true; - - try { - const response = await fetch(`${remoteUrl}/state`); - if (response.ok && isMounted) { - const state = await response.json(); - - // Update messages from server - if (state.chatHistory) { - // Only update if the chat history has actually changed - setMessages((prevMessages) => { - // Quick length check first - if (prevMessages.length !== state.chatHistory.length) { - return state.chatHistory; - } - - // Deep comparison - check if content actually changed - const hasChanged = state.chatHistory.some( - (msg: any, index: number) => { - const prevMsg = prevMessages[index]; - return ( - !prevMsg || - prevMsg.role !== msg.role || - prevMsg.content !== msg.content || - prevMsg.messageType !== msg.messageType || - prevMsg.toolName !== msg.toolName || - prevMsg.toolResult !== msg.toolResult - ); - }, - ); - - // Only update if there are actual changes - return hasChanged ? state.chatHistory : prevMessages; - }); - - // Also update chat history for consistency - setChatHistory((prevChatHistory) => { - const newChatHistory = state.chatHistory.map((msg: any) => ({ - role: msg.role, - content: msg.content, - })); - - // Similar comparison for chat history - if (prevChatHistory.length !== newChatHistory.length) { - return newChatHistory; - } - - const hasChanged = newChatHistory.some( - (msg: any, index: number) => { - const prevMsg = prevChatHistory[index]; - return ( - !prevMsg || - prevMsg.role !== msg.role || - prevMsg.content !== msg.content - ); - }, - ); - - return hasChanged ? newChatHistory : prevChatHistory; - }); - } - - // Update processing state - if (isMounted) { - setIsWaitingForResponse(state.isProcessing || false); - if (state.isProcessing && !responseStartTime) { - setResponseStartTime(Date.now()); - } else if (!state.isProcessing && responseStartTime) { - setResponseStartTime(null); - } - } - } - } catch (error) { - if (isMounted) { - logger.error("Failed to poll server state:", error); - } - } finally { - isPolling = false; - } - }; - - // Start polling immediately - pollServerState(); - - // Set up interval for continuous polling - pollInterval = setInterval(pollServerState, 500); // Poll every 500ms - - return () => { - isMounted = false; - if (pollInterval !== null) { - clearInterval(pollInterval); - pollInterval = null; - } - }; + return setupRemotePolling({ + remoteUrl, + setMessages, + setChatHistory, + setIsWaitingForResponse, + responseStartTime, + setResponseStartTime, + }); }, [isRemoteMode, remoteUrl, responseStartTime]); useEffect(() => { @@ -238,10 +131,7 @@ export function useChat({ const initializeHistory = async () => { // Only add system message if we don't have any messages yet if (chatHistory.length === 0) { - const history = await initializeChatHistory({ - resume, - rule: initialRules, - }); + const history = await initChatHistory(resume, initialRules); setChatHistory(history); } setIsChatHistoryInitialized(true); @@ -267,260 +157,83 @@ export function useChat({ }, [initialPrompt, isChatHistoryInitialized]); const handleUserMessage = async (message: string) => { - // Special handling for /org command in TUI - if (message.trim() === "/org") { - posthogService.capture("useSlashCommand", { - name: "org", - }); - onShowOrgSelector(); - return; - } + // Handle special commands + const handled = await handleSpecialCommands({ + message, + isRemoteMode, + remoteUrl, + onShowOrgSelector, + onShowConfigSelector, + exit, + setMessages, + }); - // Special handling for /config command in TUI - if (message.trim() === "/config") { - posthogService.capture("useSlashCommand", { - name: "config", - }); - onShowConfigSelector(); - return; - } - - // Handle /exit command in remote mode - if (isRemoteMode && remoteUrl && message.trim() === "/exit") { - posthogService.capture("useSlashCommand", { - name: "exit", - }); - try { - // Send POST request to /exit endpoint - const response = await fetch(`${remoteUrl}/exit`, { - method: "POST", - }); - - if (response.ok) { - setMessages((prev) => [ - ...prev, - { - role: "system", - content: "Remote environment is shutting down...", - messageType: "system" as const, - }, - ]); - - // Exit the local client after a brief delay - setTimeout(() => { - exit(); - }, 1000); - } else { - const text = await response.text(); - logger.error("Remote shutdown failed:", text); - setMessages((prev) => [ - ...prev, - { - role: "system", - content: "Failed to shut down remote environment", - messageType: "system" as const, - }, - ]); - } - } catch (error) { - logger.error("Failed to send exit request to remote server:", error); - setMessages((prev) => [ - ...prev, - { - role: "system", - content: "Error: Failed to connect to remote server for shutdown", - messageType: "system" as const, - }, - ]); - } - return; - } + if (handled) return; // Handle slash commands (skip in remote mode except for /exit which we handled above) if (!isRemoteMode && assistant) { const commandResult = await handleSlashCommands(message, assistant); if (commandResult) { - if (commandResult.exit) { - exit(); - return; - } - - if (commandResult.openConfigSelector) { - onShowConfigSelector(); - return; - } - - if (commandResult.openModelSelector && onShowModelSelector) { - onShowModelSelector(); - return; - } - - if (commandResult.clear) { - const systemMessage = chatHistory.find( - (msg) => msg.role === "system", - ); - const newHistory = systemMessage ? [systemMessage] : []; - setChatHistory(newHistory); - setMessages([]); - - if (commandResult.output) { - const output = commandResult.output; - setMessages([ - { - role: "system", - content: output, - messageType: "system" as const, - }, - ]); - } - return; - } - if (commandResult.compact) { - // Handle compact command - await handleCompactCommand(); + await handleCompactCommand({ + chatHistory, + model, + llmApi, + setChatHistory, + setMessages, + setCompactionIndex, + }); return; } - if (commandResult.output) { - const output = commandResult.output; - setMessages((prev) => [ - ...prev, - { - role: "system", - content: output, - messageType: "system" as const, - }, - ]); - } + const newInput = processSlashCommandResult({ + result: commandResult, + chatHistory, + setChatHistory, + setMessages, + exit, + onShowConfigSelector, + onShowModelSelector, + }); - if (commandResult.newInput) { - message = commandResult.newInput; + if (newInput) { + message = newInput; } else { return; } } } - // Start active time tracking for telemetry - telemetryService.startActiveTime(); - - // Track user prompt - telemetryService.logUserPrompt(message.length, message); - posthogService.capture("chat", { - model: model?.name, - provider: model?.provider, - }); + // Track telemetry + trackUserMessage(message, model); // Add user message to history and display - let messageContent = message; - + const messageContent = formatMessageWithFiles(message, attachedFiles); if (attachedFiles.length > 0) { - const fileContents = attachedFiles - .map( - (file) => `\n\n\n${file.content}\n`, - ) - .join(""); - messageContent = `${message}${fileContents}`; setAttachedFiles([]); } // In remote mode, send message to server instead of processing locally if (isRemoteMode && remoteUrl) { - try { - const response = await fetch(`${remoteUrl}/message`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ message: messageContent }), - }); - - if (!response.ok) { - const error = await response.json(); - setMessages((prev) => [ - ...prev, - { - role: "system", - content: `Error: ${error.error || "Failed to send message"}`, - messageType: "system" as const, - }, - ]); - } - // State will be updated by polling - } catch (error) { - logger.error("Failed to send message to remote server:", error); - setMessages((prev) => [ - ...prev, - { - role: "system", - content: `Error: Failed to connect to remote server`, - messageType: "system" as const, - }, - ]); - } + await handleRemoteMessage({ + remoteUrl, + messageContent, + setMessages, + }); return; } // Check if auto-compacting is needed BEFORE adding user message - let currentCompactionIndex = compactionIndex; - let currentChatHistory = chatHistory; - - if (model && shouldAutoCompact(chatHistory, model)) { - logger.info("Auto-compacting triggered in TUI mode"); - - setMessages((prev) => [ - ...prev, - { - role: "system", - content: "Approaching context limit. Auto-compacting chat history...", - messageType: "system" as const, - }, - ]); - - try { - if (!llmApi) { - throw new Error("LLM API is not available for auto-compaction"); - } - - // Compact the history WITHOUT the current user message - const result = await compactChatHistory(chatHistory, model, llmApi); - - // Update local variables immediately - currentChatHistory = result.compactedHistory; - currentCompactionIndex = result.compactionIndex; - - // Update state - setChatHistory(result.compactedHistory); - setCompactionIndex(result.compactionIndex); - - // Save the compacted session - saveSession(result.compactedHistory); - - setMessages((prev) => [ - ...prev, - { - role: "system", - content: "✓ Chat history auto-compacted successfully.", - messageType: "system" as const, - }, - ]); - } catch (error: any) { - const errorMessage = `Auto-compaction error: ${formatError(error)}`; - logger.error(errorMessage); - - setMessages((prev) => [ - ...prev, - { - role: "system", - content: `Warning: ${errorMessage}. Continuing without compaction...`, - messageType: "system" as const, - }, - ]); - - // Continue without compaction on error - } - } + const { currentChatHistory, currentCompactionIndex } = + await handleAutoCompaction({ + chatHistory, + model, + llmApi, + compactionIndex, + setMessages, + setChatHistory, + setCompactionIndex, + }); // NOW add user message to history and UI const newUserMessage: ChatCompletionMessageParam = { @@ -543,143 +256,29 @@ export function useChat({ }); try { - let currentStreamingMessage: DisplayMessage | null = null; - - const streamCallbacks: StreamCallbacks = { - onContent: (content: string) => { - if (!currentStreamingMessage) { - currentStreamingMessage = { - role: "assistant", - content: "", - isStreaming: true, - }; - } - currentStreamingMessage.content += content; - }, - onContentComplete: (content: string) => { - if (currentStreamingMessage) { - setMessages((prev) => [ - ...prev, - { - role: "assistant", - content: content, - isStreaming: false, - }, - ]); - currentStreamingMessage = null; - } - }, - onToolStart: (toolName: string, toolArgs?: any) => { - if (currentStreamingMessage && currentStreamingMessage.content) { - const messageContent = currentStreamingMessage.content; - setMessages((prev) => [ - ...prev, - { - role: "assistant", - content: messageContent, - isStreaming: false, - }, - ]); - currentStreamingMessage = null; - } - - setMessages((prev) => [ - ...prev, - { - role: "system", - content: formatToolCall(toolName, toolArgs), - messageType: "tool-start", - toolName, - }, - ]); - }, - onToolResult: (result: string, toolName: string) => { - setMessages((prev) => { - const newMessages = [...prev]; - for (let i = newMessages.length - 1; i >= 0; i--) { - if ( - newMessages[i].messageType === "tool-start" && - newMessages[i].toolName === toolName - ) { - newMessages[i] = { - ...newMessages[i], - messageType: "tool-result", - toolResult: result, - }; - break; - } - } - return newMessages; - }); - }, - onToolError: (error: string, toolName?: string) => { - setMessages((prev) => [ - ...prev, - { - role: "system", - content: error, - messageType: "tool-error", - toolName, - }, - ]); - }, - onToolPermissionRequest: ( - toolName: string, - toolArgs: any, - requestId: string, - toolCallPreview?: ToolCallPreview[], - ) => { - // Set the active permission request to show the selector - setActivePermissionRequest({ - toolName, - toolArgs, - requestId, - toolCallPreview, - }); - }, + const currentStreamingMessageRef = { + current: null as DisplayMessage | null, }; + const streamCallbacks = createStreamCallbacks( + { setMessages, setActivePermissionRequest }, + currentStreamingMessageRef, + ); - // Call streamChatResponse with the new history that includes the user message - // streamChatResponse modifies the history array in place, so we need to handle this carefully + // Execute streaming chat response + await executeStreaming({ + newHistory, + model, + llmApi, + controller, + streamCallbacks, + currentCompactionIndex, + }); - if (model && llmApi) { - // Use currentCompactionIndex which has the updated value after potential auto-compaction - if ( - currentCompactionIndex !== null && - currentCompactionIndex !== undefined - ) { - // When using compaction, we need to send a subset but capture the full history - const historyForLLM = getHistoryForLLM( - newHistory, - currentCompactionIndex, - ); - const originalLength = historyForLLM.length; - - await streamChatResponse( - historyForLLM, - model, - llmApi, - controller, - streamCallbacks, - ); - - // Append any new messages (assistant/tool) that were added by streamChatResponse - const newMessages = historyForLLM.slice(originalLength); - newHistory.push(...newMessages); - } else { - // No compaction - just pass the full history directly - await streamChatResponse( - newHistory, - model, - llmApi, - controller, - streamCallbacks, - ); - } - } - - if (currentStreamingMessage && (currentStreamingMessage as any).content) { - const messageContent = (currentStreamingMessage as any).content; + if ( + currentStreamingMessageRef.current && + currentStreamingMessageRef.current.content + ) { + const messageContent = currentStreamingMessageRef.current.content; setMessages((prev) => [ ...prev, { @@ -751,107 +350,15 @@ export function useChat({ } }; - const handleCompactCommand = async () => { - if (!model || !llmApi) { - setMessages((prev) => [ - ...prev, - { - role: "system", - content: "Error: No model configured for compaction", - messageType: "system" as const, - }, - ]); - return; - } - - setIsWaitingForResponse(true); - setInputMode(false); - - try { - let streamingContent = ""; - - const result = await compactChatHistory(chatHistory, model, llmApi, { - onStreamContent: (content: string) => { - streamingContent += content; - setMessages((prev) => { - const newMessages = [...prev]; - const lastMessage = newMessages[newMessages.length - 1]; - if ( - lastMessage && - lastMessage.role === "assistant" && - lastMessage.messageType === "compaction" && - lastMessage.isStreaming - ) { - lastMessage.content = streamingContent; - } else { - newMessages.push({ - role: "assistant", - content: streamingContent, - isStreaming: true, - messageType: "compaction", - }); - } - return newMessages; - }); - }, - onStreamComplete: () => { - setMessages((prev) => { - const newMessages = [...prev]; - const lastMessage = newMessages[newMessages.length - 1]; - if (lastMessage && lastMessage.isStreaming) { - lastMessage.isStreaming = false; - } - return newMessages; - }); - }, - onError: (error: Error) => { - logger.error("Compaction streaming error", error); - }, - }); - - // Update state with compacted history - setChatHistory(result.compactedHistory); - setCompactionIndex(result.compactionIndex); - - // Save the compacted session - saveSession(result.compactedHistory); - - // Add success message - setMessages((prev) => [ - ...prev, - { - role: "system", - content: - "Chat history compacted successfully. Future messages will use the compacted context.", - messageType: "system" as const, - }, - ]); - } catch (error: any) { - const errorMessage = `Compaction error: ${formatError(error)}`; - setMessages((prev) => [ - ...prev, - { - role: "system", - content: errorMessage, - messageType: "system" as const, - }, - ]); - } finally { - setAbortController(null); - setIsWaitingForResponse(false); - setInputMode(true); - } - }; - const handleFileAttached = (filePath: string, content: string) => { setAttachedFiles((prev) => [...prev, { path: filePath, content }]); }; const resetChatHistory = async () => { - const newHistory = await initializeChatHistory({ - resume: false, // Don't resume when resetting - rule: additionalRules, - }); + const newHistory = await initChatHistory( + false, // Don't resume when resetting + additionalRules, + ); setChatHistory(newHistory); setMessages([]); }; diff --git a/src/ui/hooks/useChat.types.ts b/src/ui/hooks/useChat.types.ts new file mode 100644 index 000000000..eddd686a1 --- /dev/null +++ b/src/ui/hooks/useChat.types.ts @@ -0,0 +1,60 @@ +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { ChatCompletionMessageParam } from "openai/resources.mjs"; + +import { ToolCallPreview } from "../../tools/types.js"; + +export interface UseChatProps { + assistant?: AssistantUnrolled; + model?: ModelConfig; + llmApi?: BaseLlmApi; + initialPrompt?: string; + resume?: boolean; + additionalRules?: string[]; + onShowOrgSelector: () => void; + onShowConfigSelector: () => void; + onShowModelSelector?: () => void; + onLoginPrompt?: (promptText: string) => Promise; + onReload?: () => Promise; + // Remote mode props + isRemoteMode?: boolean; + remoteUrl?: string; +} + +export interface AttachedFile { + path: string; + content: string; +} + +export interface ActivePermissionRequest { + toolName: string; + toolArgs: any; + requestId: string; + toolCallPreview?: ToolCallPreview[]; +} + +export interface RemoteServerState { + messages: Array<{ + role: string; + content?: string; + tool_calls?: any[]; + }>; + chatHistory: ChatCompletionMessageParam[]; + isProcessing: boolean; + activePermissionRequest?: { + toolName: string; + toolArgs: any; + requestId: string; + toolCallPreview?: any[]; + }; +} + +export interface SlashCommandResult { + output?: string; + exit?: boolean; + newInput?: string; + clear?: boolean; + openConfigSelector?: boolean; + openModelSelector?: boolean; + compact?: boolean; +} diff --git a/src/ui/hooks/useUserInput.ts b/src/ui/hooks/useUserInput.ts new file mode 100644 index 000000000..87a5553b6 --- /dev/null +++ b/src/ui/hooks/useUserInput.ts @@ -0,0 +1,66 @@ +import type { PermissionMode } from "../../permissions/types.js"; +import { logger } from "../../util/logger.js"; + +// Helper function to handle control keys +interface ControlKeysOptions { + input: string; + key: any; + exit: () => void; + showSlashCommands: boolean; + showFileSearch: boolean; + cycleModes: () => Promise; +} + +export function handleControlKeys(options: ControlKeysOptions): boolean { + const { input, key, exit, showSlashCommands, showFileSearch, cycleModes } = + options; + + // Handle Ctrl+C and Ctrl+D + if (key.ctrl && (input === "c" || input === "d")) { + exit(); + return true; + } + + // Handle Shift+Tab to cycle through modes + if (key.tab && key.shift && !showSlashCommands && !showFileSearch) { + cycleModes().catch((error) => { + logger.error("Failed to cycle modes:", error); + }); + return true; + } + + return false; +} + +// Helper to update text buffer state +interface TextBufferStateOptions { + handled: boolean; + textBuffer: any; + setInputText: (text: string) => void; + setCursorPosition: (pos: number) => void; + updateSlashCommandState: (text: string, cursor: number) => void; + updateFileSearchState: (text: string, cursor: number) => void; + inputHistory: any; +} + +export function updateTextBufferState(options: TextBufferStateOptions) { + const { + handled, + textBuffer, + setInputText, + setCursorPosition, + updateSlashCommandState, + updateFileSearchState, + inputHistory, + } = options; + + if (handled) { + const newText = textBuffer.text; + const newCursor = textBuffer.cursor; + setInputText(newText); + setCursorPosition(newCursor); + updateSlashCommandState(newText, newCursor); + updateFileSearchState(newText, newCursor); + inputHistory.resetNavigation(); + } +} diff --git a/src/ui/index.ts b/src/ui/index.ts index e64cb3091..12a88e303 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -9,20 +9,31 @@ import { AppRoot } from "./AppRoot.js"; export { MarkdownRenderer } from "./MarkdownRenderer.js"; -export async function startTUIChat( - initialPrompt?: string, - resume?: boolean, - configPath?: string, - organizationSlug?: string, - additionalRules?: string[], +interface StartTUIChatOptions { + initialPrompt?: string; + resume?: boolean; + configPath?: string; + organizationSlug?: string; + additionalRules?: string[]; toolPermissionOverrides?: { allow?: string[]; ask?: string[]; exclude?: string[]; mode?: PermissionMode; - }, - skipOnboarding?: boolean, -) { + }; + skipOnboarding?: boolean; +} + +export async function startTUIChat(options: StartTUIChatOptions) { + const { + initialPrompt, + resume, + configPath, + organizationSlug, + additionalRules, + toolPermissionOverrides, + skipOnboarding, + } = options; // Initialize services only if not already done (skipOnboarding means already initialized) if (!skipOnboarding) { initializeServices({ From 0a1a2e8b1475a1d6c4cab177b6591526106ea566 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 11 Aug 2025 17:42:52 -0700 Subject: [PATCH 4/4] Update shared-options.ts --- src/shared-options.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/shared-options.ts b/src/shared-options.ts index c3c2ed27c..6a68f29b1 100644 --- a/src/shared-options.ts +++ b/src/shared-options.ts @@ -4,8 +4,8 @@ import { Command } from "commander"; export function addCommonOptions(command: Command): Command { return command .option( - "--config ", - "Configuration file for the assistant (can be a file path or hub slug)" + "--config ", + "Configuration file for the assistant (can be a file path or hub slug)", ) .option( "--org ",