diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..761ef6eaa --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @continuedev/continue-code-reviewers \ No newline at end of file diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml index 912dd4d28..4564bfef1 100644 --- a/.github/workflows/beta-release.yml +++ b/.github/workflows/beta-release.yml @@ -51,6 +51,15 @@ jobs: DATE_SUFFIX=$(date -u +%Y%m%d) BETA_VERSION="${CURRENT_VERSION}-beta.${DATE_SUFFIX}" + # Check if this version already exists on npm + if npm view @continuedev/cli@$BETA_VERSION version --silent >/dev/null 2>&1; then + echo "Version $BETA_VERSION already exists, adding timestamp" + # Add hour and minute to make it unique + TIMESTAMP_SUFFIX=$(date -u +%Y%m%d.%H%M) + BETA_VERSION="${CURRENT_VERSION}-beta.${TIMESTAMP_SUFFIX}" + echo "Using timestamped version: $BETA_VERSION" + fi + echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT echo "date_suffix=$DATE_SUFFIX" >> $GITHUB_OUTPUT diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index 67bdc135e..52d245c51 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -197,8 +197,6 @@ jobs: reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.'; } - const comment = reviewContent; - // Get PR number let prNumber; if (context.payload.pull_request) { @@ -207,19 +205,48 @@ jobs: prNumber = context.payload.workflow_run.pull_requests[0].number; } - if (prNumber) { + if (!prNumber) { + console.log('Could not determine PR number for commenting'); + return; + } + + // Unique identifier for our bot comments + const botSignature = ''; + const newComment = `${botSignature}\n${reviewContent}`; + + // Get all comments on the PR + const { data: comments } = await github.rest.issues.listComments({ per_page: 100, + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + }); + + // Find existing Continue CLI review comment + const existingComment = comments.find(comment => + comment.body.includes(botSignature) + ); + + if (existingComment) { + // Update existing comment + await github.rest.issues.updateComment({ + comment_id: existingComment.id, + owner: context.repo.owner, + repo: context.repo.repo, + body: newComment + }); + console.log(`Successfully updated existing comment #${existingComment.id} on PR #${prNumber}`); + } else { + // Create new comment await github.rest.issues.createComment({ issue_number: prNumber, owner: context.repo.owner, repo: context.repo.repo, - body: comment + body: newComment }); - console.log(`Successfully posted comment on PR #${prNumber}`); - } else { - console.log('Could not determine PR number for commenting'); + console.log(`Successfully created new comment on PR #${prNumber}`); } } catch (error) { - console.log('Failed to post comment:', error.message); + console.log('Failed to post/update comment:', error.message); console.log('Error details:', error); } env: diff --git a/.github/workflows/pr_checks.yml b/.github/workflows/pr_checks.yml index 700498b82..3f8922952 100644 --- a/.github/workflows/pr_checks.yml +++ b/.github/workflows/pr_checks.yml @@ -43,6 +43,13 @@ jobs: - name: Install dependencies run: npm ci + - name: Debug environment info + run: | + echo "Node.js version: $(node --version)" + echo "npm version: $(npm --version)" + echo "Prettier version: $(npx prettier --version)" + echo "Platform: $(uname -a)" + - name: Check code formatting run: npm run format:check diff --git a/.gitignore b/.gitignore index 960cc97cf..dc3410527 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,5 @@ chat.log # Local config files (users should not commit their personal configs) config.yaml + +.continue-debug/ 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 a0b5722f4..49f2d240f 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", @@ -22,7 +22,7 @@ "format": "prettier --write .", "format:check": "prettier --check .", "typecheck": "tsc --noEmit", - "watch:logs": "tail -f ~/.continue/logs/cn.log", + "watch:logs": "touch ~/.continue/logs/cn.log && tail -f ~/.continue/logs/cn.log", "prepare": "npm run build", "semantic-release": "semantic-release", "semantic-release:dry-run": "semantic-release --dry-run" diff --git a/src/CLIPlatformClient.ts b/src/CLIPlatformClient.ts index 7b559bf40..2f7c2dbfe 100644 --- a/src/CLIPlatformClient.ts +++ b/src/CLIPlatformClient.ts @@ -38,8 +38,30 @@ export class CLIPlatformClient implements PlatformClient { } } + private findSecretInProcessEnv(fqsn: FQSN): SecretResult | undefined { + const secretValue = process.env[fqsn.secretName]; + if (secretValue) { + return { + found: true, + fqsn, + value: secretValue, + secretLocation: { + secretName: fqsn.secretName, + secretType: SecretType.LocalEnv, + }, + }; + } + return undefined; + } + private findSecretInLocalEnvFiles(fqsn: FQSN): SecretResult | undefined { - // Check in priority order: ~/.continue/.env, /.continue/.env, /.env + // First check process.env (highest priority) + const processEnvSecret = this.findSecretInProcessEnv(fqsn); + if (processEnvSecret) { + return processEnvSecret; + } + + // Then check in priority order: ~/.continue/.env, /.continue/.env, /.env const workspaceDir = process.cwd(); const envPaths = [ path.join(env.continueHome, ".env"), 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/__mocks__/systemMessage.ts b/src/__mocks__/systemMessage.ts new file mode 100644 index 000000000..0599a90db --- /dev/null +++ b/src/__mocks__/systemMessage.ts @@ -0,0 +1,7 @@ +import { vi } from "vitest"; + +export const constructSystemMessage = vi + .fn() + .mockResolvedValue( + "You are an agent in the Continue CLI. Given the user's prompt, you should use the tools available to you to answer the user's question.", + ); 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 84a7801e9..d6215bae8 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -25,7 +25,7 @@ import { posthogService } from "../telemetry/posthogService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { startTUIChat } from "../ui/index.js"; import { safeStdout } from "../util/consoleOverride.js"; -import { formatError } from "../util/formatError.js"; +import { formatAnthropicError, formatError } from "../util/formatError.js"; import { logger } from "../util/logger.js"; import { calculateContextUsagePercentage, @@ -103,9 +103,7 @@ export async function initializeChatHistory( // If no session loaded or not resuming, initialize with system message if (chatHistory.length === 0) { - const rulesSystemMessage = ""; // TODO //assistant.systemMessage; const systemMessage = await constructSystemMessage( - rulesSystemMessage, options.rule, options.format, options.headless, @@ -118,56 +116,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 +264,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; } } @@ -304,7 +336,13 @@ async function processMessage( saveSession(chatHistory); } catch (e: any) { const error = e instanceof Error ? e : new Error(String(e)); - logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`); + + if (model.provider === "anthropic") { + logger.error(`\n${chalk.red(`Error: ${formatAnthropicError(error)}`)}`); + } else { + logger.error(`\n${chalk.red(`Error: ${formatError(error)}`)}`); + } + sentryService.captureException(error, { context: "chat_response", isHeadless, @@ -367,16 +405,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) { @@ -423,15 +461,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.test.ts b/src/commands/serve.test.ts index 23c762460..502c8d2ef 100644 --- a/src/commands/serve.test.ts +++ b/src/commands/serve.test.ts @@ -115,4 +115,58 @@ describe("serve command", () => { // Skip for now to focus on removing top-level mocks expect(true).toBe(true); }); + + it("should pass the --org flag through to initializeServices", async () => { + // Import the services module to spy on + const servicesModule = await import("../services/index.js"); + + // Create spy on initializeServices + const initializeServicesSpy = vi.spyOn(servicesModule, "initializeServices") + .mockResolvedValue({ + config: { models: [] }, + llmApi: { chat: vi.fn() }, + model: { name: "test-model" } + } as any); + + // Create spy on getService + const getServiceSpy = vi.spyOn(servicesModule, "getService") + .mockResolvedValueOnce({ + config: { name: "test" }, + llmApi: { chat: vi.fn() }, + model: { provider: "test", model: "test" } + } as any) + .mockResolvedValueOnce({ + config: { name: "test" }, + llmApi: { chat: vi.fn() }, + model: { provider: "test", model: "test" } + } as any); + + // Import serve after setting up spies + const { serve } = await import("./serve.js"); + + // Call serve with --org flag + const testOptions = { + org: "test-organization-slug", + timeout: "60", + port: "9000" + }; + + try { + await serve("test prompt", testOptions); + } catch (error) { + // Expected to fail due to incomplete mocking + } + + // Check that initializeServices was called with organization option + expect(initializeServicesSpy).toHaveBeenCalled(); + expect(initializeServicesSpy).toHaveBeenCalledWith( + expect.objectContaining({ + organizationSlug: "test-organization-slug" + }) + ); + + // Clean up spies + initializeServicesSpy.mockRestore(); + getServiceSpy.mockRestore(); + }); }); \ No newline at end of file diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 6cf428e22..0aa535b19 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"; @@ -38,6 +36,7 @@ const execAsync = promisify(exec); interface ServeOptions extends ExtendedCommandOptions { timeout?: string; port?: string; + org?: string; } interface PendingPermission { @@ -73,6 +72,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { toolPermissionOverrides: permissionOverrides, configPath: options.config, rules: options.rule, + organizationSlug: options.org, headless: true, // Skip onboarding in serve mode }); @@ -122,7 +122,6 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { // Initialize chat history const chatHistory: ChatCompletionMessageParam[] = []; const systemMessage = await constructSystemMessage( - "", options.rule, undefined, true, 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/config.test.ts b/src/config.test.ts new file mode 100644 index 000000000..f61c46bf5 --- /dev/null +++ b/src/config.test.ts @@ -0,0 +1,56 @@ +import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml'; +import { describe, expect, test, vi, beforeEach } from 'vitest'; + +// Mock dependencies +vi.mock('./auth/workos.js'); + +import type { AuthConfig } from './auth/workos.js'; +import { getLlmApi } from './config.js'; + +describe('config', () => { + let mockAuthConfig: AuthConfig; + + beforeEach(() => { + vi.clearAllMocks(); + + mockAuthConfig = { + accessToken: 'test-token', + refreshToken: 'test-refresh', + userEmail: 'test@example.com', + userId: 'test-user', + organizationId: 'test-org', + expiresAt: Date.now() + 3600000, + }; + }); + + describe('getLlmApi()', () => { + test('should throw error when models array is empty', () => { + const assistant: AssistantUnrolled = { + name: 'test-assistant', + version: '1.0.0', + models: [], + }; + + expect(() => getLlmApi(assistant, mockAuthConfig)) + .toThrow('No models found in the configured assistant'); + }); + + test('should throw error when no chat models available', () => { + const assistant: AssistantUnrolled = { + name: 'test-assistant', + version: '1.0.0', + models: [ + { + provider: 'openai', + model: 'text-embedding-ada-002', + name: 'Ada Embeddings', + roles: ['embed'], + } as ModelConfig, + ], + }; + + expect(() => getLlmApi(assistant, mockAuthConfig)) + .toThrow('No models with the chat role found in the configured assistant'); + }); + }); +}); diff --git a/src/config.ts b/src/config.ts index 9737cec12..9140bfe31 100644 --- a/src/config.ts +++ b/src/config.ts @@ -23,6 +23,10 @@ export function getLlmApi( assistant: AssistantUnrolled, authConfig: AuthConfig, ): [BaseLlmApi, ModelConfig] { + if (!assistant.models || assistant.models.length === 0) { + throw new Error("No models found in the configured assistant"); + } + const model = assistant.models?.find( (model) => model?.roles?.includes("chat") || (model && model.roles === undefined), diff --git a/src/configLoader.ts b/src/configLoader.ts index 29b9555f7..44035b940 100644 --- a/src/configLoader.ts +++ b/src/configLoader.ts @@ -4,12 +4,14 @@ import * as path from "path"; import { AssistantUnrolled, + PackageIdentifier, RegistryClient, unrollAssistant, } from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; +import { uriToPath, uriToSlug } from "./auth/uriUtils.js"; import { AuthConfig, getAccessToken, @@ -17,8 +19,6 @@ import { getOrganizationId, isEnvironmentAuthConfig, updateConfigUri, - uriToPath, - uriToSlug, } from "./auth/workos.js"; import { CLIPlatformClient } from "./CLIPlatformClient.js"; import { env } from "./env.js"; @@ -93,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" } } @@ -276,20 +276,23 @@ async function loadDefaultAgent( } /** - * Loads a local YAML configuration file + * Common function to unroll an assistant with consistent configuration */ -async function loadConfigYaml( - filePath: string, +async function unrollAssistantWithConfig( + packageIdentifier: PackageIdentifier, accessToken: string | null, organizationId: string | null, apiClient: DefaultApiInterface, ): Promise { const unrollResult = await unrollAssistant( - { filePath, uriType: "file" }, + packageIdentifier, new RegistryClient({ accessToken: accessToken ?? undefined, apiBase: env.apiBase, - rootPath: dirname(filePath), + rootPath: + packageIdentifier.uriType === "file" + ? dirname(packageIdentifier.filePath) + : undefined, }), { currentUserSlug: "", @@ -303,7 +306,7 @@ async function loadConfigYaml( const errorDetails = unrollResult.errors; if (!unrollResult.config) { - throw new Error(`Failed to load config file:\n${errorDetails}`); + throw new Error(`Failed to load config:\n${errorDetails}`); } else if (errorDetails?.length) { const warnings = errorDetails?.length > 1 @@ -315,6 +318,23 @@ async function loadConfigYaml( return unrollResult.config; } +/** + * Loads a local YAML configuration file + */ +async function loadConfigYaml( + filePath: string, + accessToken: string | null, + organizationId: string | null, + apiClient: DefaultApiInterface, +): Promise { + return await unrollAssistantWithConfig( + { filePath, uriType: "file" }, + accessToken, + organizationId, + apiClient, + ); +} + /** * Loads an assistant by slug from the Continue platform */ @@ -330,6 +350,19 @@ async function loadAssistantSlug( ); } + // Unroll locally if not logged in + if (!(apiClient as any).configuration.apiKey) { + return await unrollAssistantWithConfig( + { + uriType: "slug", + fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" }, + }, + null, + organizationId, + apiClient, + ); + } + const resp = await apiClient.getAssistant({ ownerSlug, packageSlug, diff --git a/src/e2e/headless-anthropic-api-key.test.ts b/src/e2e/headless-anthropic-api-key.test.ts new file mode 100644 index 000000000..721a62b0d --- /dev/null +++ b/src/e2e/headless-anthropic-api-key.test.ts @@ -0,0 +1,115 @@ +import * as fs from "fs/promises"; +import * as path from "path"; + +import { + cleanupTestContext, + createTestContext, + runCLI, +} from "../test-helpers/cli-helpers.js"; +import { + cleanupMockLLMServer, + type MockLLMServer, + createMockLLMServer, +} from "../test-helpers/mock-llm-server.js"; + +describe("E2E: Headless Mode with ANTHROPIC_API_KEY", () => { + let context: any; + let mockServer: MockLLMServer; + + beforeEach(async () => { + context = await createTestContext(); + }); + + afterEach(async () => { + if (mockServer) { + await cleanupMockLLMServer(mockServer); + } + await cleanupTestContext(context); + }); + + it("should work when ANTHROPIC_API_KEY is set in environment", async () => { + // Create a mock LLM server using the same pattern as working tests + mockServer = await createMockLLMServer({ + response: "Hello! This is a response from Claude.", + }); + + // Use OpenAI provider pointing to mock server (same as working tests) + const configContent = `name: Test Assistant +version: 1.0.0 +schema: v1 +models: + - name: test-claude + model: claude-3-5-sonnet + provider: openai + apiKey: test-key + apiBase: ${mockServer.url} + roles: + - chat +`; + + const configPath = path.join(context.testDir, "test-config.yaml"); + await fs.writeFile(configPath, configContent); + context.configPath = configPath; + + // Create onboarding flag to skip onboarding + const onboardingFlagPath = path.join( + context.testDir, + ".continue", + ".onboarding_complete", + ); + await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true }); + await fs.writeFile(onboardingFlagPath, new Date().toISOString()); + + const result = await runCLI(context, { + args: ["-p", "--config", context.configPath, "Hi there"], + env: { + ANTHROPIC_API_KEY: "test-api-key-from-env" + }, + timeout: 15000, + }); + + // Verify the CLI successfully runs (even if not using env var in this test) + expect(result.stdout).toContain("Hello! This is a response from Claude."); + expect(result.exitCode).toBe(0); + expect(mockServer.requests).toHaveLength(1); + + // Find the user message in the request + const userMessage = mockServer.requests[0].body.messages.find( + (m: any) => m.role === "user" + ); + expect(userMessage.content).toBe("Hi there"); + }, 20000); + + it("should create config and work with ANTHROPIC_API_KEY when no config exists", async () => { + // This test verifies the main fix: CLI automatically creates config from ANTHROPIC_API_KEY + // when no config file exists in headless mode + + const result = await runCLI(context, { + args: ["-p", "test prompt"], + env: { + ANTHROPIC_API_KEY: "sk-test-invalid-key-format", + CONTINUE_GLOBAL_DIR: context.testDir + "/.continue" + }, + expectError: true, + timeout: 15000, + }); + + // Should fail with authentication error (not service initialization error) + // This proves the fix works and CLI reaches the API call stage + expect(result.stderr).toContain("authentication_error"); + + // Should NOT contain the old error about service initialization + expect(result.stderr).not.toContain("Failed to initialize ConfigService"); + + // Verify config.yaml was automatically created + const configPath = path.join(context.testDir, ".continue", "config.yaml"); + const configExists = await fs.stat(configPath).then(() => true).catch(() => false); + expect(configExists).toBe(true); + + if (configExists) { + const configContent = await fs.readFile(configPath, "utf-8"); + expect(configContent).toContain("anthropic/claude-4-sonnet"); + expect(configContent).toContain("ANTHROPIC_API_KEY: sk-test-invalid-key-format"); + } + }, 20000); +}); \ No newline at end of file diff --git a/src/mcp.ts b/src/mcp.ts index 9abc60c02..da1eda632 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -15,10 +15,10 @@ type MCPServerConfig = NonNullable< interface ServerConnection { config: MCPServerConfig; + status: MCPServerStatus; client: Client | null; prompts: Awaited>["prompts"]; tools: Awaited>["tools"]; - status: MCPServerStatus; error?: string; warnings: string[]; } @@ -75,132 +75,11 @@ export class MCPService { serverCount: assistant.mcpServers.length, }); - const connectionPromises = assistant.mcpServers.map( - async (serverConfig, index) => { - if (!serverConfig) return; - const serverName = serverConfig.name || `server-${index}`; - // Create placeholder connection with connecting state - const connection: ServerConnection = { - config: serverConfig, - client: null, - prompts: [], - tools: [], - status: "connecting", - warnings: [], - }; - this.connections.set(serverName, connection); - this.updateState(); - - try { - if (serverConfig.type && serverConfig.type !== "stdio") { - throw new Error( - `${serverConfig.type} MCP servers are not yet supported in the Continue CLI`, - ); - } - if (!serverConfig.command) { - throw new Error("MCP server command is not specified"); - } - - const client = new Client( - { name: "continue-cli-client", version: "1.0.0" }, - { capabilities: {} }, - ); - - const env: Record = serverConfig.env || {}; - if (process.env.PATH !== undefined) { - env.PATH = process.env.PATH; - } - - const transport = new StdioClientTransport({ - command: serverConfig.command, - args: serverConfig.args, - env, - stderr: "ignore", - }); - - logger.debug("Connecting to MCP server", { - name: serverName, - command: serverConfig.command, - }); - - await client.connect(transport, {}); - - // Ignore results from stale initializations - if (version !== this.initVersion) { - try { - await client.close(); - } catch {} - return; - } - - connection.client = client; - connection.status = "connected"; - - const capabilities = client.getServerCapabilities(); - logger.debug("MCP server capabilities", { - name: serverName, - hasPrompts: !!capabilities?.prompts, - hasTools: !!capabilities?.tools, - }); - - if (capabilities?.prompts) { - try { - connection.prompts = (await client.listPrompts()).prompts; - logger.debug("Loaded MCP prompts", { - name: serverName, - count: connection.prompts.length, - }); - } catch (error) { - const errorMessage = getErrorString(error); - connection.warnings.push( - `Failed to load prompts: ${errorMessage}`, - ); - logger.warn("Failed to load MCP prompts", { - name: serverName, - error: errorMessage, - }); - } - } - - if (capabilities?.tools) { - try { - connection.tools = (await client.listTools()).tools; - logger.debug("Loaded MCP tools", { - name: serverName, - count: connection.tools.length, - }); - } catch (error) { - const errorMessage = getErrorString(error); - connection.warnings.push( - `Failed to load tools: ${errorMessage}`, - ); - logger.warn("Failed to load MCP tools", { - name: serverName, - error: errorMessage, - }); - } - } - - logger.debug("MCP server connected", { - name: serverName, - command: serverConfig.command, - }); - this.updateState(); - } catch (error) { - if (version !== this.initVersion) { - return; - } - const errorMessage = getErrorString(error); - connection.status = "error"; - connection.error = errorMessage; - logger.error("MCP server connection failed", { - name: serverName, - error: errorMessage, - }); - this.updateState(); - } - }, - ); + const connectionPromises = assistant.mcpServers.map(async (config) => { + if (config) { + return await this.connectServer(config); + } + }); Promise.all(connectionPromises) .then(() => { @@ -297,23 +176,15 @@ export class MCPService { hasWarnings: boolean; } { const connections = Array.from(this.connections.values()); - - if (connections.length === 0) { - return { status: "idle", hasWarnings: false }; - } - - const hasConnecting = connections.some((c) => c.status === "connecting"); - const hasError = connections.some((c) => c.status === "error"); - const hasConnected = connections.some((c) => c.status === "connected"); const hasWarnings = connections.some((c) => c.warnings.length > 0); - if (hasConnecting) { + if (connections.some((c) => c.status === "connecting")) { return { status: "connecting", hasWarnings }; } - if (hasError) { + if (connections.some((c) => c.status === "error")) { return { status: "error", hasWarnings }; } - if (hasConnected) { + if (connections.some((c) => c.status === "connected")) { return { status: "connected", hasWarnings }; } @@ -423,7 +294,10 @@ export class MCPService { } this.connections.delete(serverName); } + await this.connectServer(serverConfig); + } + private async connectServer(serverConfig: MCPServerConfig) { const connection: ServerConnection = { config: serverConfig, client: null, @@ -432,10 +306,16 @@ export class MCPService { status: "connecting", warnings: [], }; + const serverName = serverConfig.name; this.connections.set(serverName, connection); this.updateState(); try { + if (serverConfig.type && serverConfig.type !== "stdio") { + throw new Error( + `${serverConfig.type} MCP servers are not yet supported in the Continue CLI`, + ); + } if (!serverConfig.command) { throw new Error("MCP server command is not specified"); } @@ -463,6 +343,7 @@ export class MCPService { }); await client.connect(transport, {}); + client.setLoggingLevel("critical"); connection.client = client; connection.status = "connected"; diff --git a/src/onboarding.ts b/src/onboarding.ts index 536ead963..88b20098d 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -78,7 +78,16 @@ export async function runOnboardingFlow( !process.stdin.isTTY; if (isTestEnv) { - // In test/CI environment, return a minimal working configuration + // In test/CI environment, check for ANTHROPIC_API_KEY first + if (process.env.ANTHROPIC_API_KEY) { + console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); + await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); + console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); + const result = await initialize(authConfig, CONFIG_PATH); + return { ...result, wasOnboarded: false }; + } + + // Otherwise return a minimal working configuration const result = await initialize(authConfig, undefined); return { ...result, wasOnboarded: false }; } diff --git a/src/permissions/defaultPolicies.test.ts b/src/permissions/defaultPolicies.test.ts new file mode 100644 index 000000000..5c39db1c7 --- /dev/null +++ b/src/permissions/defaultPolicies.test.ts @@ -0,0 +1,43 @@ +import { describe, it, expect } from "vitest"; + +import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; + +describe("defaultPolicies", () => { + it("should have correct permissions for read-only tools", () => { + const readOnlyTools = ["Read", "List", "Search", "Fetch", "Exit", "Diff", "Checklist"]; + + for (const tool of readOnlyTools) { + const policy = DEFAULT_TOOL_POLICIES.find(p => p.tool === tool); + expect(policy, `Policy should exist for ${tool}`).toBeDefined(); + expect(policy?.permission, `${tool} should be allowed`).toBe("allow"); + } + }); + + it("should have correct permissions for write tools", () => { + const writeTools = ["Write", "Edit", "MultiEdit", "Bash"]; + + for (const tool of writeTools) { + const policy = DEFAULT_TOOL_POLICIES.find(p => p.tool === tool); + expect(policy, `Policy should exist for ${tool}`).toBeDefined(); + expect(policy?.permission, `${tool} should require confirmation`).toBe("ask"); + } + }); + + it("should have a catch-all policy", () => { + const catchAllPolicy = DEFAULT_TOOL_POLICIES.find(p => p.tool === "*"); + expect(catchAllPolicy).toBeDefined(); + expect(catchAllPolicy?.permission).toBe("ask"); + }); + + it("should include MultiEdit policy", () => { + const multiEditPolicy = DEFAULT_TOOL_POLICIES.find(p => p.tool === "MultiEdit"); + expect(multiEditPolicy).toBeDefined(); + expect(multiEditPolicy?.permission).toBe("ask"); + }); + + it("should have policies in correct order", () => { + // The catch-all policy should be last + const catchAllIndex = DEFAULT_TOOL_POLICIES.findIndex(p => p.tool === "*"); + expect(catchAllIndex).toBe(DEFAULT_TOOL_POLICIES.length - 1); + }); +}); \ No newline at end of file diff --git a/src/permissions/defaultPolicies.ts b/src/permissions/defaultPolicies.ts index 33cdfba08..90cf1fb02 100644 --- a/src/permissions/defaultPolicies.ts +++ b/src/permissions/defaultPolicies.ts @@ -14,6 +14,7 @@ export const DEFAULT_TOOL_POLICIES: ToolPermissionPolicy[] = [ // Write operations should require confirmation { tool: "Write", permission: "ask" }, { tool: "Edit", permission: "ask" }, + { tool: "MultiEdit", permission: "ask" }, // Write to a checklist { tool: "Checklist", permission: "allow" }, diff --git a/src/permissions/permissionsYamlLoader.test.ts b/src/permissions/permissionsYamlLoader.test.ts index 90f97be79..da08ea1df 100644 --- a/src/permissions/permissionsYamlLoader.test.ts +++ b/src/permissions/permissionsYamlLoader.test.ts @@ -19,7 +19,7 @@ describe("permissionsYamlLoader", () => { ]); }); - it("should normalize tool names", () => { + it("should use exact tool names without normalization", () => { const config = { allow: ["read", "READ", "Read"], }; @@ -27,8 +27,8 @@ describe("permissionsYamlLoader", () => { const policies = yamlConfigToPolicies(config); expect(policies).toEqual([ - { tool: "Read", permission: "allow" }, - { tool: "Read", permission: "allow" }, + { tool: "read", permission: "allow" }, + { tool: "READ", permission: "allow" }, { tool: "Read", permission: "allow" }, ]); }); @@ -79,7 +79,7 @@ describe("permissionsYamlLoader", () => { { tool: "Fetch", permission: "exclude" }, { tool: "Exit", permission: "exclude" }, { tool: "Write", permission: "ask" }, - { tool: "Bash", permission: "ask" }, + { tool: "Terminal", permission: "ask" }, { tool: "Read", permission: "allow" }, { tool: "List", permission: "allow" }, ]); @@ -183,14 +183,14 @@ describe("permissionsYamlLoader", () => { expect(() => parseToolPattern("Write(unclosed", "allow")).toThrow("Invalid tool pattern: Write(unclosed"); }); - it("should normalize tool names in patterns", () => { + it("should use exact tool names in patterns", () => { const policy = parseToolPattern("write(**/*.ts)", "allow"); expect(policy).toEqual({ - tool: "Write", + tool: "write", permission: "allow", argumentMatches: { - file_path: "**/*.ts" + pattern: "**/*.ts" } }); }); diff --git a/src/permissions/permissionsYamlLoader.ts b/src/permissions/permissionsYamlLoader.ts index 9d48015d7..449154cbd 100644 --- a/src/permissions/permissionsYamlLoader.ts +++ b/src/permissions/permissionsYamlLoader.ts @@ -1,12 +1,11 @@ -import * as fs from "fs"; -import * as path from "path"; +import fs from "fs"; +import path from "path"; -import * as yaml from "yaml"; +import YAML from "yaml"; import { env } from "../env.js"; import { logger } from "../util/logger.js"; -import { normalizeToolName } from "./toolNameMapping.js"; import { PermissionPolicy, ToolPermissionPolicy } from "./types.js"; export const PERMISSIONS_YAML_PATH = path.resolve( @@ -33,7 +32,7 @@ export function loadPermissionsYaml(): PermissionsYamlConfig | null { } const content = fs.readFileSync(PERMISSIONS_YAML_PATH, "utf-8"); - const parsed = yaml.parse(content) as PermissionsYamlConfig; + const parsed = YAML.parse(content) as PermissionsYamlConfig; // Validate the structure if (parsed && typeof parsed === "object") { @@ -85,7 +84,7 @@ export function parseToolPattern( } const [, toolName, args] = match; - const normalizedName = normalizeToolName(toolName.trim()); + const normalizedName = toolName.trim(); const policy: ToolPermissionPolicy = { tool: normalizedName, diff --git a/src/permissions/policyWriter.test.ts b/src/permissions/policyWriter.test.ts index bf5f83596..0274594f8 100644 --- a/src/permissions/policyWriter.test.ts +++ b/src/permissions/policyWriter.test.ts @@ -28,11 +28,11 @@ describe("policyWriter", () => { expect(generatePolicyRule("Bash", { command: " " })).toBe("Bash"); }); - it("should handle tool name normalization", () => { - expect(generatePolicyRule("bash", { command: "ls" })).toBe("Bash(ls*)"); - expect(generatePolicyRule("BASH", { command: "pwd" })).toBe("Bash(pwd*)"); - expect(generatePolicyRule("read", { file_path: "/test" })).toBe("Read"); - expect(generatePolicyRule("write", { file_path: "/test", content: "test" })).toBe("Write"); + it("should use exact tool names without normalization", () => { + expect(generatePolicyRule("bash", { command: "ls" })).toBe("bash"); + expect(generatePolicyRule("BASH", { command: "pwd" })).toBe("BASH"); + expect(generatePolicyRule("read", { file_path: "/test" })).toBe("read"); + expect(generatePolicyRule("write", { file_path: "/test", content: "test" })).toBe("write"); }); }); }); \ No newline at end of file diff --git a/src/permissions/policyWriter.ts b/src/permissions/policyWriter.ts index 6ba079896..adda2688f 100644 --- a/src/permissions/policyWriter.ts +++ b/src/permissions/policyWriter.ts @@ -1,6 +1,6 @@ -import * as fs from "fs"; +import fs from "fs"; -import * as yaml from "yaml"; +import YAML from "yaml"; import { logger } from "../util/logger.js"; @@ -9,7 +9,6 @@ import { PermissionsYamlConfig, loadPermissionsYaml, } from "./permissionsYamlLoader.js"; -import { normalizeToolName, getDisplayName } from "./toolNameMapping.js"; /** * Generates a policy rule for a given tool call @@ -17,7 +16,7 @@ import { normalizeToolName, getDisplayName } from "./toolNameMapping.js"; * For Bash tool, generates command-specific patterns like "Bash(ls*)" */ export function generatePolicyRule(toolName: string, toolArgs: any): string { - const normalizedName = normalizeToolName(toolName); + const normalizedName = toolName; // For Bash tool, create command-specific policies if (normalizedName === "Bash" && toolArgs?.command) { @@ -32,7 +31,7 @@ export function generatePolicyRule(toolName: string, toolArgs: any): string { } // For all other tools, return the display name - return getDisplayName(normalizedName); + return normalizedName; } /** @@ -49,11 +48,13 @@ 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 - const yamlContent = yaml.stringify(config); + const yamlContent = YAML.stringify(config); // Add header comment const finalContent = `# Continue CLI Permissions Configuration @@ -64,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/permissions/policyWriter.verify.test.ts b/src/permissions/policyWriter.verify.test.ts index a3d3feed1..9af031514 100644 --- a/src/permissions/policyWriter.verify.test.ts +++ b/src/permissions/policyWriter.verify.test.ts @@ -15,9 +15,9 @@ describe("policyWriter verification", () => { expect(generatePolicyRule("Bash", { command: "ls -la" })).toBe("Bash(ls*)"); }); - it("should handle mixed case tool names", () => { - expect(generatePolicyRule("edit", { filepath: "test.txt" })).toBe("Edit"); - expect(generatePolicyRule("EDIT", { filepath: "test.txt" })).toBe("Edit"); + it("should use exact tool names without case normalization", () => { + expect(generatePolicyRule("edit", { filepath: "test.txt" })).toBe("edit"); + expect(generatePolicyRule("EDIT", { filepath: "test.txt" })).toBe("EDIT"); expect(generatePolicyRule("Edit", { filepath: "test.txt" })).toBe("Edit"); }); }); \ No newline at end of file diff --git a/src/permissions/precedenceResolver.test.ts b/src/permissions/precedenceResolver.test.ts index 736f844af..36dc3f8dd 100644 --- a/src/permissions/precedenceResolver.test.ts +++ b/src/permissions/precedenceResolver.test.ts @@ -44,7 +44,7 @@ describe("precedenceResolver", () => { ]); }); - it("should normalize tool names in command line flags", () => { + it("should use exact tool names from command line flags", () => { const policies = resolvePermissionPrecedence({ commandLineFlags: { allow: ["Read", "write", "BASH"], @@ -55,8 +55,8 @@ describe("precedenceResolver", () => { expect(policies).toEqual([ { tool: "Read", permission: "allow" }, - { tool: "Write", permission: "allow" }, - { tool: "Bash", permission: "allow" }, + { tool: "write", permission: "allow" }, + { tool: "BASH", permission: "allow" }, ]); }); diff --git a/src/permissions/precedenceResolver.ts b/src/permissions/precedenceResolver.ts index 65a769ec9..c559a0362 100644 --- a/src/permissions/precedenceResolver.ts +++ b/src/permissions/precedenceResolver.ts @@ -5,8 +5,7 @@ import { loadPermissionsYaml, yamlConfigToPolicies, } from "./permissionsYamlLoader.js"; -import { normalizeToolName } from "./toolNameMapping.js"; -import { ToolPermissionPolicy } from "./types.js"; +import { type ToolPermissionPolicy } from "./types.js"; export interface PermissionSources { /** Command line flags - highest precedence */ @@ -107,21 +106,21 @@ function commandLineFlagsToPolicies(flags: { // Order matters for CLI flags too if (flags.exclude) { for (const tool of flags.exclude) { - const normalizedName = normalizeToolName(tool); + const normalizedName = tool; policies.push({ tool: normalizedName, permission: "exclude" }); } } if (flags.ask) { for (const tool of flags.ask) { - const normalizedName = normalizeToolName(tool); + const normalizedName = tool; policies.push({ tool: normalizedName, permission: "ask" }); } } if (flags.allow) { for (const tool of flags.allow) { - const normalizedName = normalizeToolName(tool); + const normalizedName = tool; policies.push({ tool: normalizedName, permission: "allow" }); } } diff --git a/src/permissions/runtimeOverrides.ts b/src/permissions/runtimeOverrides.ts index d776d2b9f..d27ee1f7d 100644 --- a/src/permissions/runtimeOverrides.ts +++ b/src/permissions/runtimeOverrides.ts @@ -3,7 +3,6 @@ * This ensures they're available immediately, before services are initialized */ -import { normalizeToolName } from "./toolNameMapping.js"; import { ToolPermissionPolicy } from "./types.js"; let runtimeOverrides: ToolPermissionPolicy[] | null = null; @@ -23,21 +22,21 @@ export function setRuntimePermissionOverrides(overrides: { // Convert runtime overrides to policies if (overrides.exclude) { for (const tool of overrides.exclude) { - const normalizedName = normalizeToolName(tool); + const normalizedName = tool; policies.push({ tool: normalizedName, permission: "exclude" }); } } if (overrides.ask) { for (const tool of overrides.ask) { - const normalizedName = normalizeToolName(tool); + const normalizedName = tool; policies.push({ tool: normalizedName, permission: "ask" }); } } if (overrides.allow) { for (const tool of overrides.allow) { - const normalizedName = normalizeToolName(tool); + const normalizedName = tool; policies.push({ tool: normalizedName, permission: "allow" }); } } diff --git a/src/permissions/toolNameMapping.ts b/src/permissions/toolNameMapping.ts deleted file mode 100644 index 0c32befa4..000000000 --- a/src/permissions/toolNameMapping.ts +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Maps common variations to standardized tool names - */ -const TOOL_NAME_MAPPINGS: Record = { - // Standard tool names (passthrough) - Read: "Read", - Write: "Write", - List: "List", - Search: "Search", - Bash: "Bash", - Fetch: "Fetch", - Exit: "Exit", - Diff: "Diff", - Edit: "Edit", - Checklist: "Checklist", - - // Common variations (case insensitive) - read: "Read", - write: "Write", - list: "List", - search: "Search", - bash: "Bash", - terminal: "Bash", - Terminal: "Bash", - cmd: "Bash", - command: "Bash", - fetch: "Fetch", - exit: "Exit", - diff: "Diff", - edit: "Edit", - checklist: "Checklist", -}; - -/** - * Normalizes a tool name from various formats (variations, legacy names) to the standardized tool name - */ -export function normalizeToolName(input: string): string { - // First try exact match (case sensitive) - if (TOOL_NAME_MAPPINGS[input]) { - return TOOL_NAME_MAPPINGS[input]; - } - - // Try case insensitive match - const lowerInput = input.toLowerCase(); - for (const [key, value] of Object.entries(TOOL_NAME_MAPPINGS)) { - if (key.toLowerCase() === lowerInput) { - return value; - } - } - - // If no mapping found, return as-is (might be an MCP tool or future tool) - return input; -} - -/** - * Gets the display name for a tool name - * Since we now use display names as the primary names, this mostly returns the input - * but handles any remaining edge cases - */ -export function getDisplayName(toolName: string): string { - // Simply normalize and return - the tool name is already the display name - return normalizeToolName(toolName); -} diff --git a/src/permissions/yamlPermissions.test.ts b/src/permissions/yamlPermissions.test.ts index 67af0a898..029f28ff6 100644 --- a/src/permissions/yamlPermissions.test.ts +++ b/src/permissions/yamlPermissions.test.ts @@ -62,20 +62,12 @@ exclude: []`; expect(result3.permission).toBe('ask'); // Should not match, falls back to ask }); - it('should check what normalizeToolName returns for Edit variations', async () => { - const { normalizeToolName } = await import('./toolNameMapping.js'); +it('should use exact tool names without normalization', () => { + // Tools are now used exactly as they are named, no normalization + const editName = "Edit"; + const multiEditName = "MultiEdit"; - console.log('normalizeToolName("Edit"):', normalizeToolName("Edit")); - console.log('normalizeToolName("edit"):', normalizeToolName("edit")); - console.log('normalizeToolName("edit_file"):', normalizeToolName("edit_file")); - console.log('normalizeToolName("search_and_replace_in_file"):', normalizeToolName("search_and_replace_in_file")); - - // Only proper names and case variations should normalize - expect(normalizeToolName("Edit")).toBe("Edit"); - expect(normalizeToolName("edit")).toBe("Edit"); - - // Legacy snake_case names should not normalize anymore - expect(normalizeToolName("edit_file")).toBe("edit_file"); - expect(normalizeToolName("search_and_replace_in_file")).toBe("search_and_replace_in_file"); + expect(editName).toBe("Edit"); + expect(multiEditName).toBe("MultiEdit"); }); }); \ No newline at end of file diff --git a/src/services/BaseService.ts b/src/services/BaseService.ts index b29ec7b1c..4d4f88b84 100644 --- a/src/services/BaseService.ts +++ b/src/services/BaseService.ts @@ -38,7 +38,7 @@ export abstract class BaseService extends EventEmitter { this.emit("initialized", state); return state; } catch (error: any) { - logger.error(`Failed to initialize ${this.serviceName}:`, error); + logger.debug(`Failed to initialize ${this.serviceName}:`, error); if (this.listenerCount("error") > 0) { this.emit("error", error); } 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.test.ts b/src/services/ModelService.test.ts index 4600079ce..6a2bd43c1 100644 --- a/src/services/ModelService.test.ts +++ b/src/services/ModelService.test.ts @@ -22,7 +22,7 @@ describe('ModelService', () => { beforeEach(() => { vi.clearAllMocks(); service = new ModelService(); - + mockAssistant = { name: 'test-assistant', version: '1.0.0', @@ -92,24 +92,6 @@ describe('ModelService', () => { expect(state.model).toBe(mockAssistant.models![0]); }); - - test('should throw error when no chat models available', async () => { - mockAssistant.models = [ - { - provider: 'openai', - model: 'text-embedding-ada-002', - name: 'Ada Embeddings', - roles: ['embed'], - } as ModelConfig, - ]; - - vi.mocked(config.getLlmApi).mockImplementation(() => { - throw new Error('No models with the chat role found in the configured assistant'); - }); - - await expect(service.initialize(mockAssistant, mockAuthConfig)) - .rejects.toThrow('No models with the chat role found in the configured assistant'); - }); }); describe('update()', () => { @@ -147,12 +129,12 @@ describe('ModelService', () => { test('should switch to a different model by index', async () => { vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]); await service.initialize(mockAssistant, mockAuthConfig); - + const newLlmApi = { complete: vi.fn(), stream: vi.fn() }; vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(newLlmApi as any); - + const state = await service.switchModel(1); - + expect(state).toEqual({ llmApi: newLlmApi, model: mockAssistant.models![1] @@ -163,7 +145,7 @@ describe('ModelService', () => { test('should throw error for invalid model index', async () => { vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]); await service.initialize(mockAssistant, mockAuthConfig); - + await expect(service.switchModel(5)).rejects.toThrow('Invalid model index: 5. Available models: 0-1'); await expect(service.switchModel(-1)).rejects.toThrow('Invalid model index: -1. Available models: 0-1'); }); @@ -180,7 +162,7 @@ describe('ModelService', () => { apiKeyLocation: 'env.PROXY_KEY', roles: ['chat'], } as ModelConfig; - + mockAssistant.models = [proxyModel]; vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, proxyModel]); await service.initialize(mockAssistant, mockAuthConfig); @@ -208,9 +190,9 @@ describe('ModelService', () => { test('should return only models with chat role', async () => { vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]); await service.initialize(mockAssistant, mockAuthConfig); - + const models = service.getAvailableChatModels(); - + expect(models).toHaveLength(2); expect(models[0]).toEqual({ provider: 'openai', @@ -229,9 +211,9 @@ describe('ModelService', () => { test('should return correct index of current model', async () => { vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]); await service.initialize(mockAssistant, mockAuthConfig); - + expect(service.getCurrentModelIndex()).toBe(0); - + vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any); await service.switchModel(1); expect(service.getCurrentModelIndex()).toBe(1); @@ -316,13 +298,13 @@ describe('ModelService', () => { await service.switchModel(1); expect(listener).toHaveBeenCalledWith( - expect.objectContaining({ + expect.objectContaining({ model: mockAssistant.models![1], - llmApi: newLlmApi + llmApi: newLlmApi }), - expect.objectContaining({ + expect.objectContaining({ model: mockAssistant.models![0], - llmApi: mockLlmApi + llmApi: mockLlmApi }) ); }); @@ -335,7 +317,7 @@ describe('ModelService', () => { service.on('error', errorListener); vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(null as any); - + await expect(service.switchModel(1)).rejects.toThrow('Failed to initialize LLM'); expect(errorListener).toHaveBeenCalledWith(expect.any(Error)); }); 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/ServiceContainer.ts b/src/services/ServiceContainer.ts index bb3054d15..adaaa1072 100644 --- a/src/services/ServiceContainer.ts +++ b/src/services/ServiceContainer.ts @@ -151,7 +151,7 @@ export class ServiceContainer extends EventEmitter { return value; } catch (error: any) { - logger.error(`Failed to load service '${serviceName}':`, error); + logger.debug(`Failed to load service '${serviceName}':`, error); this.setServiceError(serviceName, error); throw error; } @@ -252,7 +252,7 @@ export class ServiceContainer extends EventEmitter { await Promise.all( serviceNames.map((name) => this.load(name).catch((error) => { - logger.error(`Failed to initialize service ${name}:`, error); + logger.debug(`Failed to initialize service ${name}:`, error); // Don't throw - let individual services fail without breaking others }), ), diff --git a/src/services/index.test.ts b/src/services/index.test.ts index f89b34a84..533191dc5 100644 --- a/src/services/index.test.ts +++ b/src/services/index.test.ts @@ -8,6 +8,7 @@ import { initializeServices } from "./index.js"; // Mock the onboarding module vi.mock("../onboarding.js", () => ({ initializeWithOnboarding: vi.fn().mockResolvedValue({ wasOnboarded: false }), + createOrUpdateConfig: vi.fn().mockResolvedValue(undefined), })); // Mock auth module diff --git a/src/services/index.ts b/src/services/index.ts index d6bc426e2..9d4d9bc1e 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -47,6 +47,23 @@ export async function initializeServices( wasOnboarded = onboardingResult.wasOnboarded; } + // Handle ANTHROPIC_API_KEY in headless mode when no config path is provided + if ( + options.headless && + !options.configPath && + process.env.ANTHROPIC_API_KEY + ) { + const { createOrUpdateConfig } = await import("../onboarding.js"); + const { env } = await import("../env.js"); + const path = await import("path"); + + const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); + await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); + + // Update options to use the created config + options.configPath = CONFIG_PATH; + } + // Initialize mode service with tool permission overrides if (options.toolPermissionOverrides) { const overrides = { ...options.toolPermissionOverrides }; @@ -135,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); @@ -190,7 +206,6 @@ export async function initializeServices( if (!configState.config) { throw new Error("Config not available for MCP service"); } - return mcpService.initialize(configState.config); }, [SERVICE_NAMES.CONFIG], // Depends on config 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/shared-options.ts b/src/shared-options.ts index a3fe38772..6a68f29b1 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 ", + "Configuration file for the assistant (can be a file path or hub slug)", + ) .option( "--org ", "Organization slug to use for this session (supported only in headless mode)", diff --git a/src/slashCommands.ts b/src/slashCommands.ts index 57e7ac80f..2fb4dff8a 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -9,6 +9,194 @@ import { import { getAllSlashCommands } from "./commands/commands.js"; import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; import { posthogService } from "./telemetry/posthogService.js"; +import { SlashCommandResult } from "./ui/hooks/useChat.types.js"; + +// 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 | SlashCommandResult; + +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 }; + }, + mcp: () => { + posthogService.capture("useSlashCommand", { name: "mcp" }); + return { openMcpSelector: true }; + }, + org: handleOrg, +}; export async function handleSlashCommands( input: string, @@ -24,195 +212,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 "mcp": - posthogService.capture("useSlashCommand", { - name: "mcp", - }); - // Open MCP management UI - return { openMCPSelector: 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 8fb522dd9..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 @@ -337,6 +337,59 @@ describe("processStreamingResponse - content preservation", () => { '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}' ); }); + + it("handles malformed chunk with empty choices array without crashing", async () => { + // This reproduces the exact bug from the logs: + // {"chunk":{"choices":[],"usage":{"completion_tokens":96,"prompt_tokens":711,"total_tokens":807,"prompt_tokens_details":{"cached_tokens":3353}},"created":1754927672408,"id":"","model":"claude-sonnet-4-20250514","object":"chat.completion.chunk"}} + const malformedChunk: ChatCompletionChunk = { + id: "", + object: "chat.completion.chunk", + created: 1754927672408, + model: "claude-sonnet-4-20250514", + choices: [], // Empty choices array - this causes the bug + usage: { + completion_tokens: 96, + prompt_tokens: 711, + total_tokens: 807, + prompt_tokens_details: { + cached_tokens: 3353 + } + } + }; + + chunks = [ + malformedChunk, // Put malformed chunk first to trigger the bug more clearly + contentChunk("Hello "), + contentChunk("world!") + ]; + + // This should not throw an error: "Cannot read properties of undefined (reading 'delta')" + let caughtError: any = null; + try { + await processStreamingResponse({ + chatHistory, + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); + } catch (error) { + caughtError = error; + } + + // Should NOT throw error about reading 'delta' property + expect(caughtError).toBeNull(); + + const result = await processStreamingResponse({ + chatHistory, + model: mockModel, + llmApi: mockLlmApi, + abortController: mockAbortController, + }); + + expect(result.content).toBe("Hello world!"); + expect(result.toolCalls.length).toBe(0); + expect(result.finalContent).toBe("Hello world!"); + }); }); // Tests for preprocessStreamedToolCalls function diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 568926e18..5d9d40914 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -1,38 +1,33 @@ -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 { - checkToolPermission, - filterExcludedTools, - ToolCallRequest, -} from "./permissions/index.js"; -import { toolPermissionManager } from "./permissions/permissionManager.js"; +import { filterExcludedTools } from "./permissions/index.js"; import { getServiceSync, MCPServiceState, SERVICE_NAMES, - serviceContainer, } 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, @@ -41,17 +36,100 @@ import { logger } from "./util/logger.js"; dotenv.config(); -export async function getAllTools() { +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(); const builtinToolNames = allBuiltinTools.map((tool) => tool.name); - const mcpState = await serviceContainer.get( - SERVICE_NAMES.MCP, - ); - if (!mcpState?.mcpService) { + const mcpState = getServiceSync(SERVICE_NAMES.MCP); + + if (!mcpState?.value?.mcpService) { throw new Error("MCP Service not initialized"); } - const mcpTools = mcpState.mcpService?.getTools() ?? []; + const mcpTools = mcpState.value?.mcpService?.getTools() ?? []; const mcpToolNames = mcpTools.map((t) => t.name); const allToolNames = [...builtinToolNames, ...mcpToolNames]; @@ -129,47 +207,90 @@ export async 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 () => { @@ -211,20 +332,6 @@ export async function processStreamingResponse( logger.debug("Received chunk", { chunkCount, chunk }); - // 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, - ); - } - // Track token usage if available if (chunk.usage) { inputTokens = chunk.usage.prompt_tokens || 0; @@ -237,122 +344,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 + 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, @@ -367,12 +389,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"); @@ -413,262 +435,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[], @@ -702,7 +468,7 @@ export async function streamChatResponse( // Get response from LLM const { content, toolCalls, shouldContinue } = - await processStreamingResponse( + await processStreamingResponse({ chatHistory, model, llmApi, @@ -710,74 +476,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/systemMessage.test.ts b/src/systemMessage.test.ts index 680179e06..52ff9630d 100644 --- a/src/systemMessage.test.ts +++ b/src/systemMessage.test.ts @@ -1,19 +1,35 @@ -import { constructSystemMessage } from "./systemMessage.js"; +import { describe, expect, it, vi } from "vitest"; + +// Use the actual implementation instead of the mocked one +vi.unmock("./systemMessage.js"); +const { constructSystemMessage } = await import("./systemMessage.js"); + +// Mock the service container to avoid "No factory registered for service 'config'" error +vi.mock("./services/ServiceContainer.js", () => ({ + serviceContainer: { + get: vi.fn().mockResolvedValue({ config: { rules: [] } }) + } +})); + +// Mock processRule to avoid file system operations in tests +vi.mock("./args.js", () => ({ + processRule: vi.fn().mockImplementation((rule: string) => Promise.resolve(rule)) +})); describe("constructSystemMessage", () => { - it("should return base system message with rules when rulesSystemMessage is provided", async () => { - const rulesMessage = "These are the rules for the assistant."; - const result = await constructSystemMessage(rulesMessage); + it("should return base system message with rules when additionalRules is provided", async () => { + const rules = ["These are the rules for the assistant."]; + const result = await constructSystemMessage(rules); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); - expect(result).toContain(rulesMessage); + expect(result).toContain(rules[0]); expect(result).toContain(""); }); it("should return base system message with agent content when no rules but agent file exists", async () => { // The implementation checks for agent files like AGENTS.md which exists in this project - const result = await constructSystemMessage(""); + const result = await constructSystemMessage(); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); @@ -21,7 +37,7 @@ describe("constructSystemMessage", () => { }); it("should include base system message components", async () => { - const result = await constructSystemMessage(""); + const result = await constructSystemMessage(); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(""); @@ -30,27 +46,27 @@ describe("constructSystemMessage", () => { }); it("should handle whitespace-only rules message", async () => { - const result = await constructSystemMessage(" "); + const result = await constructSystemMessage([" "]); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain(''); }); it("should include working directory information", async () => { - const result = await constructSystemMessage(""); + const result = await constructSystemMessage(); expect(result).toContain("Working directory:"); expect(result).toContain(""); }); it("should include platform information", async () => { - const result = await constructSystemMessage(""); + const result = await constructSystemMessage(); expect(result).toContain("Platform:"); }); it("should include current date", async () => { - const result = await constructSystemMessage(""); + const result = await constructSystemMessage(); expect(result).toContain("Today's date:"); expect(result).toContain(new Date().toISOString().split("T")[0]); @@ -58,7 +74,7 @@ describe("constructSystemMessage", () => { it("should format rules section correctly", async () => { const rulesMessage = "Rule 1: Do this\nRule 2: Do that"; - const result = await constructSystemMessage(rulesMessage); + const result = await constructSystemMessage([rulesMessage]); expect(result).toContain(''); expect(result).toContain(rulesMessage); @@ -69,7 +85,7 @@ describe("constructSystemMessage", () => { const rulesMessage = `Rule 1: First rule Rule 2: Second rule Rule 3: Third rule`; - const result = await constructSystemMessage(rulesMessage); + const result = await constructSystemMessage([rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -78,7 +94,7 @@ Rule 3: Third rule`; it("should handle special characters in rules message", async () => { const rulesMessage = "Rule with characters & symbols!"; - const result = await constructSystemMessage(rulesMessage); + const result = await constructSystemMessage([rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -86,7 +102,7 @@ Rule 3: Third rule`; it("should handle very long rules message", async () => { const rulesMessage = "A".repeat(1000); - const result = await constructSystemMessage(rulesMessage); + const result = await constructSystemMessage([rulesMessage]); expect(result).toContain(rulesMessage); expect(result).toContain(''); @@ -94,7 +110,7 @@ Rule 3: Third rule`; it("should combine rules and agent content when both are present", async () => { const rulesMessage = "These are the rules."; - const result = await constructSystemMessage(rulesMessage); + const result = await constructSystemMessage([rulesMessage]); expect(result).toContain(''); expect(result).toContain(rulesMessage); @@ -103,7 +119,7 @@ Rule 3: Third rule`; }); it("should add headless mode instructions when headless is true", async () => { - const result = await constructSystemMessage("", undefined, undefined, true); + const result = await constructSystemMessage(undefined, undefined, true); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).toContain("IMPORTANT: You are running in headless mode"); @@ -112,7 +128,7 @@ Rule 3: Third rule`; }); it("should not add headless mode instructions when headless is false", async () => { - const result = await constructSystemMessage("", undefined, undefined, false); + const result = await constructSystemMessage(undefined, undefined, false); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain("IMPORTANT: You are running in headless mode"); @@ -120,7 +136,7 @@ Rule 3: Third rule`; }); it("should not add headless mode instructions when headless is undefined", async () => { - const result = await constructSystemMessage(""); + const result = await constructSystemMessage(); expect(result).toContain("You are an agent in the Continue CLI"); expect(result).not.toContain("IMPORTANT: You are running in headless mode"); diff --git a/src/systemMessage.ts b/src/systemMessage.ts index cb947a27f..1f09ff5c6 100644 --- a/src/systemMessage.ts +++ b/src/systemMessage.ts @@ -6,6 +6,8 @@ import pkg from "ignore-walk"; import { Minimatch } from "minimatch"; import { processRule } from "./args.js"; +import { serviceContainer } from "./services/ServiceContainer.js"; +import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js"; const { WalkerSync } = pkg; /** @@ -95,6 +97,23 @@ ${getDirectoryStructure()} ${getGitStatus()} `; +async function getConfigYamlRules(): Promise { + const configState = await serviceContainer.get( + SERVICE_NAMES.CONFIG, + ); + if (configState.config?.rules) { + // Extract systemMessage from the config if it exists + const rules = configState.config.rules; + return rules + .map((rule) => { + return typeof rule === "string" ? rule : rule?.rule; + }) + .filter((rule): rule is string => !!rule); + } + + return []; +} + /** * Load and construct a comprehensive system message with base message and rules section * @param rulesSystemMessage - The rules system message from the assistant @@ -104,7 +123,6 @@ ${getGitStatus()} * @returns The comprehensive system message with base message and rules section */ export async function constructSystemMessage( - rulesSystemMessage: string, additionalRules?: string[], format?: "json", headless?: boolean, @@ -142,6 +160,9 @@ export async function constructSystemMessage( } } + const configYamlRules = await getConfigYamlRules(); + processedRules.push(...configYamlRules); + // Construct the comprehensive system message let systemMessage = baseSystemMessage; @@ -165,21 +186,16 @@ Example response format: } // Add rules section if we have any rules or agent content - if (rulesSystemMessage || agentContent || processedRules.length > 0) { + if (agentContent || processedRules.length > 0) { systemMessage += '\n\n'; - if (rulesSystemMessage) { - systemMessage += `\n${rulesSystemMessage}`; - } - if (agentContent) { - const separator = rulesSystemMessage ? "\n\n" : "\n"; - systemMessage += `${separator}${agentContent}`; + systemMessage += `\n${agentContent}`; } // Add processed rules from --rule flags if (processedRules.length > 0) { - const separator = rulesSystemMessage || agentContent ? "\n\n" : "\n"; + const separator = agentContent ? "\n\n" : "\n"; systemMessage += `${separator}${processedRules.join("\n\n")}`; } diff --git a/src/telemetry/posthogService.test.ts b/src/telemetry/posthogService.test.ts index b82cceebe..9a4e7f98f 100644 --- a/src/telemetry/posthogService.test.ts +++ b/src/telemetry/posthogService.test.ts @@ -11,9 +11,15 @@ vi.mock("../auth/workos.js", () => ({ isAuthenticatedConfig: vi.fn(), })); -vi.mock("node-machine-id", () => ({ - machineIdSync: vi.fn(() => "test-machine-id"), -})); +vi.mock("node-machine-id", () => { + const mockFn = vi.fn(() => "test-machine-id"); + return { + default: { + machineIdSync: mockFn, + }, + machineIdSync: mockFn, + }; +}); // Import after mocks are set up import { loadAuthConfig, isAuthenticatedConfig } from "../auth/workos.js"; diff --git a/src/telemetry/posthogService.ts b/src/telemetry/posthogService.ts index bfbef6ec8..8eb694aea 100644 --- a/src/telemetry/posthogService.ts +++ b/src/telemetry/posthogService.ts @@ -1,11 +1,11 @@ import os from "node:os"; -import * as node_machine_id from 'node-machine-id'; +import node_machine_id from "node-machine-id"; import type { PostHog as PostHogType } from "posthog-node"; -import { loadAuthConfig, isAuthenticatedConfig } from "../auth/workos.js"; +import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js"; - export class PosthogService { +export class PosthogService { private os: string | undefined; private uniqueId: string; 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/edit.test.ts b/src/tools/edit.test.ts new file mode 100644 index 000000000..1ad8f7d23 --- /dev/null +++ b/src/tools/edit.test.ts @@ -0,0 +1,208 @@ +import * as fs from "fs"; + +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; + +import { editTool, markFileAsRead, readFilesSet } from "./edit.js"; + +// Mock the dependencies +vi.mock("../telemetry/telemetryService.js"); +vi.mock("../telemetry/utils.js", () => ({ + calculateLinesOfCodeDiff: vi.fn().mockReturnValue({ added: 1, removed: 0 }), + getLanguageFromFilePath: vi.fn().mockReturnValue("javascript"), +})); +vi.mock("./writeFile.js", () => ({ + generateDiff: vi.fn().mockReturnValue("mocked diff"), +})); +vi.mock("fs", async () => { + const actual = await vi.importActual("fs"); + return { + ...actual, + existsSync: vi.fn(), + readFileSync: vi.fn(), + writeFileSync: vi.fn(), + unlinkSync: vi.fn(), + }; +}); + +describe("editTool", () => { + const testFilePath = "/tmp/test-edit-file.txt"; + const originalContent = "Hello world\nThis is a test file\nGoodbye world"; + + beforeEach(() => { + vi.clearAllMocks(); + // Mock fs functions to simulate file operations + vi.mocked(fs.existsSync).mockReturnValue(true); + vi.mocked(fs.readFileSync).mockReturnValue(originalContent); + vi.mocked(fs.writeFileSync).mockImplementation(() => {}); + }); + + afterEach(() => { + vi.clearAllMocks(); + readFilesSet.clear(); + }); + + describe("preprocess", () => { + it("should throw error if file has not been read", async () => { + const args = { + file_path: testFilePath, + old_string: "Hello world", + new_string: "Hi there", + }; + + await expect(editTool.preprocess!(args)).rejects.toThrow( + `You must use the Read tool to read ${testFilePath} before editing it.` + ); + }); + + it("should throw error if file does not exist", async () => { + const nonExistentFile = "/tmp/non-existent-file.txt"; + markFileAsRead(nonExistentFile); + vi.mocked(fs.existsSync).mockReturnValue(false); + + const args = { + file_path: nonExistentFile, + old_string: "Hello", + new_string: "Hi", + }; + + await expect(editTool.preprocess!(args)).rejects.toThrow( + `File ${nonExistentFile} does not exist` + ); + }); + + it("should throw error if old_string is not found", async () => { + markFileAsRead(testFilePath); + vi.mocked(fs.readFileSync).mockReturnValue("Different content"); + + const args = { + file_path: testFilePath, + old_string: "Not found", + new_string: "Hi there", + }; + + await expect(editTool.preprocess!(args)).rejects.toThrow( + "String not found in file: Not found" + ); + }); + + it("should throw error if old_string appears multiple times and replace_all is false", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + old_string: "world", + new_string: "universe", + replace_all: false, + }; + + await expect(editTool.preprocess!(args)).rejects.toThrow( + 'String "world" appears 2 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.' + ); + }); + + it("should throw error if old_string and new_string are the same", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + old_string: "Hello world", + new_string: "Hello world", + }; + + await expect(editTool.preprocess!(args)).rejects.toThrow( + "old_string and new_string must be different" + ); + }); + + it("should successfully preprocess valid single replacement", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + old_string: "Hello world", + new_string: "Hi there", + }; + + const result = await editTool.preprocess!(args); + + expect(result.args).toEqual({ + file_path: testFilePath, + newContent: "Hi there\nThis is a test file\nGoodbye world", + oldContent: originalContent, + }); + expect(result.preview).toHaveLength(2); + expect(result.preview?.[0]).toEqual({ + type: "text", + content: "Will make the following changes:", + }); + expect(result.preview?.[1]).toEqual({ + type: "diff", + content: "mocked diff", + }); + }); + + it("should successfully preprocess replace_all", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + old_string: "world", + new_string: "universe", + replace_all: true, + }; + + const result = await editTool.preprocess!(args); + + expect(result.args.newContent).toBe( + "Hello universe\nThis is a test file\nGoodbye universe" + ); + }); + }); + + describe("run", () => { + it("should successfully write file and return success message", async () => { + const newContent = "Hi there\nThis is a test file\nGoodbye world"; + const args = { + file_path: testFilePath, + newContent, + oldContent: originalContent, + }; + + const result = await editTool.run(args); + + expect(result).toBe(`Successfully edited ${testFilePath}`); + expect(fs.writeFileSync).toHaveBeenCalledWith(testFilePath, newContent, "utf-8"); + }); + + it("should throw error if file write fails", async () => { + vi.mocked(fs.writeFileSync).mockImplementation(() => { + throw new Error("Write failed"); + }); + + const args = { + file_path: testFilePath, + newContent: "new content", + oldContent: originalContent, + }; + + await expect(editTool.run(args)).rejects.toThrow( + `Error: failed to edit ${testFilePath}: Write failed` + ); + }); + }); + + describe("markFileAsRead", () => { + it("should allow editing after marking file as read", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + old_string: "Hello world", + new_string: "Hi there", + }; + + const result = await editTool.preprocess!(args); + expect(result.args.newContent).toContain("Hi there"); + }); + }); +}); \ No newline at end of file diff --git a/src/tools/edit.ts b/src/tools/edit.ts new file mode 100644 index 000000000..9b073adfe --- /dev/null +++ b/src/tools/edit.ts @@ -0,0 +1,195 @@ +import * as fs from "fs"; + +import { telemetryService } from "../telemetry/telemetryService.js"; +import { + calculateLinesOfCodeDiff, + getLanguageFromFilePath, +} from "../telemetry/utils.js"; + +import { Tool } from "./types.js"; +import { generateDiff } from "./writeFile.js"; + +export interface EditArgs { + file_path: string; + old_string: string; + new_string: string; + replace_all?: boolean; +} + +// Track files that have been read in the current session +export const readFilesSet = new Set(); + +export const editTool: Tool = { + name: "Edit", + displayName: "Edit", + readonly: false, + isBuiltIn: true, + description: `Performs exact string replacements in files. + + +Usage: + +- You must use your \`Read\` tool at least once in the conversation before +editing. This tool will error if you attempt an edit without reading the file. + +- When editing text from Read tool output, ensure you preserve the exact +indentation (tabs/spaces) as it appears AFTER the line number prefix. The line +number prefix format is: spaces + line number + tab. Everything after that tab +is the actual file content to match. Never include any part of the line number +prefix in the old_string or new_string. + +- ALWAYS prefer editing existing files in the codebase. NEVER write new files +unless explicitly required. + +- Only use emojis if the user explicitly requests it. Avoid adding emojis to +files unless asked. + +- The edit will FAIL if \`old_string\` is not unique in the file. Either provide +a larger string with more surrounding context to make it unique or use +\`replace_all\` to change every instance of \`old_string\`. + +- Use \`replace_all\` for replacing and renaming strings across the file. This +parameter is useful if you want to rename a variable for instance.`, + parameters: { + file_path: { + type: "string", + description: "The absolute path to the file to modify", + required: true, + }, + old_string: { + type: "string", + description: "The text to replace", + required: true, + }, + new_string: { + type: "string", + description: + "The text to replace it with (must be different from old_string)", + required: true, + }, + replace_all: { + type: "boolean", + description: "Replace all occurences of old_string (default false)", + required: false, + }, + }, + preprocess: async (args) => { + const { + file_path, + old_string, + new_string, + replace_all = false, + } = args as EditArgs; + + // Check if file has been read + if (!readFilesSet.has(file_path)) { + throw new Error( + `You must use the Read tool to read ${file_path} before editing it.`, + ); + } + + // Validate arguments + if (!file_path) { + throw new Error("file_path is required"); + } + if (!old_string) { + throw new Error("old_string is required"); + } + if (new_string === undefined) { + throw new Error("new_string is required"); + } + if (old_string === new_string) { + throw new Error("old_string and new_string must be different"); + } + + // Check if file exists + if (!fs.existsSync(file_path)) { + throw new Error(`File ${file_path} does not exist`); + } + + // Read current file content + const oldContent = fs.readFileSync(file_path, "utf-8"); + + // Check if old_string exists in the file + if (!oldContent.includes(old_string)) { + throw new Error(`String not found in file: ${old_string}`); + } + + let newContent: string; + + if (replace_all) { + // Replace all occurrences + newContent = oldContent.split(old_string).join(new_string); + } else { + // Replace only the first occurrence + const occurrences = oldContent.split(old_string).length - 1; + if (occurrences > 1) { + throw new Error( + `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 = oldContent.replace(old_string, new_string); + } + + // Generate diff for preview + const diff = generateDiff(oldContent, newContent, file_path); + + return { + args: { + file_path, + newContent, + oldContent, + }, + preview: [ + { + type: "text", + content: "Will make the following changes:", + }, + { + type: "diff", + content: diff, + }, + ], + }; + }, + run: async (args: { + file_path: string; + newContent: string; + oldContent: string; + }) => { + try { + fs.writeFileSync(args.file_path, args.newContent, "utf-8"); + + // Get lines for telemetry + const { added, removed } = calculateLinesOfCodeDiff( + args.oldContent, + args.newContent, + ); + const language = getLanguageFromFilePath(args.file_path); + + if (added > 0) { + telemetryService.recordLinesOfCodeModified("added", added, language); + } + if (removed > 0) { + telemetryService.recordLinesOfCodeModified( + "removed", + removed, + language, + ); + } + + return `Successfully edited ${args.file_path}`; + } catch (error) { + throw new Error( + `Error: failed to edit ${args.file_path}: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + }, +}; + +// Function to mark a file as read (to be called from the read tool) +export function markFileAsRead(filePath: string) { + readFilesSet.add(filePath); +} diff --git a/src/tools/index.ts b/src/tools/index.ts index 43e76e790..66ac320b3 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -8,13 +8,14 @@ import type { ToolPermissionServiceState } from "../services/ToolPermissionServi import { telemetryService } from "../telemetry/telemetryService.js"; import { logger } from "../util/logger.js"; +import { editTool } from "./edit.js"; import { exitTool } from "./exit.js"; import { fetchTool } from "./fetch.js"; import { formatToolArgument } from "./formatters.js"; import { listFilesTool } from "./listFiles.js"; +import { multiEditTool } from "./multiEdit.js"; import { readFileTool } from "./readFile.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; -import { searchAndReplaceInFileTool } from "./searchAndReplace/index.js"; import { searchCodeTool } from "./searchCode.js"; import { type Tool, @@ -30,8 +31,10 @@ export type { Tool, ToolCall, ToolParameters }; // Base tools that are always available const BASE_BUILTIN_TOOLS: Tool[] = [ readFileTool, + editTool, + multiEditTool, writeFileTool, - searchAndReplaceInFileTool, + // searchAndReplaceInFileTool, listFilesTool, searchCodeTool, runTerminalCommandTool, @@ -157,15 +160,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, @@ -177,15 +177,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.test.ts b/src/tools/multiEdit.test.ts new file mode 100644 index 000000000..80463fe3b --- /dev/null +++ b/src/tools/multiEdit.test.ts @@ -0,0 +1,398 @@ +import * as fs from "fs"; + +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; + +import { multiEditTool, markFileAsRead } from "./multiEdit.js"; + +// Mock the dependencies +vi.mock("../telemetry/telemetryService.js"); +vi.mock("../telemetry/utils.js", () => ({ + calculateLinesOfCodeDiff: vi.fn().mockReturnValue({ added: 1, removed: 0 }), + getLanguageFromFilePath: vi.fn().mockReturnValue("javascript"), +})); +vi.mock("./writeFile.js", () => ({ + generateDiff: vi.fn().mockReturnValue("mocked diff"), +})); +vi.mock("fs", async () => { + const actual = await vi.importActual("fs"); + return { + ...actual, + existsSync: vi.fn(), + readFileSync: vi.fn(), + writeFileSync: vi.fn(), + unlinkSync: vi.fn(), + }; +}); + +describe("multiEditTool", () => { + const testFilePath = "/tmp/test-multi-edit-file.txt"; + const originalContent = "Hello world\nThis is a test file\nGoodbye world"; + + beforeEach(() => { + vi.clearAllMocks(); + // Mock fs functions to simulate file operations + vi.mocked(fs.existsSync).mockReturnValue(true); + vi.mocked(fs.readFileSync).mockReturnValue(originalContent); + vi.mocked(fs.writeFileSync).mockImplementation(() => {}); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + describe("preprocess", () => { + it("should throw error if file has not been read", async () => { + const args = { + file_path: testFilePath, + edits: [ + { + old_string: "Hello world", + new_string: "Hi there", + }, + ], + }; + + await expect(multiEditTool.preprocess!(args)).rejects.toThrow( + `You must use the Read tool to read ${testFilePath} before editing it.` + ); + }); + + it("should throw error if file does not exist", async () => { + const nonExistentFile = "/tmp/non-existent-file.txt"; + markFileAsRead(nonExistentFile); + vi.mocked(fs.existsSync).mockReturnValue(false); + + const args = { + file_path: nonExistentFile, + edits: [ + { + old_string: "Hello", + new_string: "Hi", + }, + ], + }; + + await expect(multiEditTool.preprocess!(args)).rejects.toThrow( + `File ${nonExistentFile} does not exist` + ); + }); + + it("should throw error if edits array is empty", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + edits: [], + }; + + await expect(multiEditTool.preprocess!(args)).rejects.toThrow( + "edits array is required and must contain at least one edit" + ); + }); + + it("should throw error if edit has missing old_string", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + edits: [ + { + old_string: undefined as any, + new_string: "Hi there", + }, + ], + }; + + await expect(multiEditTool.preprocess!(args)).rejects.toThrow( + "Edit 1: old_string is required" + ); + }); + + it("should throw error if edit has missing new_string", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + edits: [ + { + old_string: "Hello world", + new_string: undefined as any, + }, + ], + }; + + await expect(multiEditTool.preprocess!(args)).rejects.toThrow( + "Edit 1: new_string is required" + ); + }); + + it("should throw error if old_string and new_string are the same", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + edits: [ + { + old_string: "Hello world", + new_string: "Hello world", + }, + ], + }; + + await expect(multiEditTool.preprocess!(args)).rejects.toThrow( + "Edit 1: old_string and new_string must be different" + ); + }); + + it("should throw error if old_string is not found", async () => { + markFileAsRead(testFilePath); + vi.mocked(fs.readFileSync).mockReturnValue("Different content"); + + const args = { + file_path: testFilePath, + edits: [ + { + old_string: "Not found", + new_string: "Hi there", + }, + ], + }; + + await expect(multiEditTool.preprocess!(args)).rejects.toThrow( + 'Edit 1: String not found in file: "Not found"' + ); + }); + + it("should throw error if old_string appears multiple times and replace_all is false", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + edits: [ + { + old_string: "world", + new_string: "universe", + replace_all: false, + }, + ], + }; + + await expect(multiEditTool.preprocess!(args)).rejects.toThrow( + 'Edit 1: String "world" appears 2 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.' + ); + }); + + it("should successfully preprocess single edit", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + edits: [ + { + old_string: "Hello world", + new_string: "Hi there", + }, + ], + }; + + const result = await multiEditTool.preprocess!(args); + + expect(result.args).toEqual({ + file_path: testFilePath, + newContent: "Hi there\nThis is a test file\nGoodbye world", + originalContent: originalContent, + isCreatingNewFile: false, + editCount: 1, + }); + expect(result.preview).toHaveLength(2); + expect(result.preview?.[0]).toEqual({ + type: "text", + content: "Will apply 1 edit to modify /tmp/test-multi-edit-file.txt:", + }); + expect(result.preview?.[1]).toEqual({ + type: "diff", + content: "mocked diff", + }); + }); + + it("should successfully preprocess multiple edits", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + edits: [ + { + old_string: "Hello world", + new_string: "Hi there", + }, + { + old_string: "Goodbye world", + new_string: "See you later", + }, + ], + }; + + const result = await multiEditTool.preprocess!(args); + + expect(result.args.newContent).toBe( + "Hi there\nThis is a test file\nSee you later" + ); + expect(result.args.editCount).toBe(2); + expect(result.preview?.[0]?.content).toContain("Will apply 2 edits"); + }); + + it("should successfully preprocess replace_all edit", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + edits: [ + { + old_string: "world", + new_string: "universe", + replace_all: true, + }, + ], + }; + + const result = await multiEditTool.preprocess!(args); + + expect(result.args.newContent).toBe( + "Hello universe\nThis is a test file\nGoodbye universe" + ); + }); + + it("should handle new file creation with empty old_string", async () => { + const newFilePath = "/tmp/new-file.txt"; + vi.mocked(fs.existsSync).mockImplementation((path) => { + // Parent directory exists, but file doesn't + if (path === "/tmp") return true; + if (path === newFilePath) return false; + return true; + }); + + const args = { + file_path: newFilePath, + edits: [ + { + old_string: "", + new_string: "New file content\nSecond line", + }, + ], + }; + + const result = await multiEditTool.preprocess!(args); + + expect(result.args.newContent).toBe("New file content\nSecond line"); + expect(result.args.isCreatingNewFile).toBe(true); + expect(result.preview?.[0]?.content).toContain("create"); + }); + + it("should apply edits sequentially", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + edits: [ + { + old_string: "Hello world", + new_string: "Hi universe", + }, + { + old_string: "Hi universe", + new_string: "Greetings cosmos", + }, + ], + }; + + const result = await multiEditTool.preprocess!(args); + + expect(result.args.newContent).toBe( + "Greetings cosmos\nThis is a test file\nGoodbye world" + ); + }); + }); + + describe("run", () => { + it("should successfully write file and return success message", async () => { + const newContent = "Hi there\nThis is a test file\nGoodbye world"; + const args = { + file_path: testFilePath, + newContent, + originalContent: originalContent, + isCreatingNewFile: false, + editCount: 1, + }; + + const result = await multiEditTool.run(args); + + expect(result).toBe(`Successfully edited ${testFilePath} with 1 edit`); + expect(fs.writeFileSync).toHaveBeenCalledWith(testFilePath, newContent, "utf-8"); + }); + + it("should return correct message for multiple edits", async () => { + const args = { + file_path: testFilePath, + newContent: "New content", + originalContent: originalContent, + isCreatingNewFile: false, + editCount: 3, + }; + + const result = await multiEditTool.run(args); + + expect(result).toBe(`Successfully edited ${testFilePath} with 3 edits`); + }); + + it("should return correct message for new file creation", async () => { + const args = { + file_path: "/tmp/new-file.txt", + newContent: "New file content", + originalContent: "", + isCreatingNewFile: true, + editCount: 1, + }; + + const result = await multiEditTool.run(args); + + expect(result).toBe(`Successfully created /tmp/new-file.txt with 1 edit`); + }); + + it("should throw error if file write fails", async () => { + vi.mocked(fs.writeFileSync).mockImplementation(() => { + throw new Error("Write failed"); + }); + + const args = { + file_path: testFilePath, + newContent: "new content", + originalContent: originalContent, + isCreatingNewFile: false, + editCount: 1, + }; + + await expect(multiEditTool.run(args)).rejects.toThrow( + `Error: failed to edit ${testFilePath}: Write failed` + ); + }); + }); + + describe("markFileAsRead", () => { + it("should allow editing after marking file as read", async () => { + markFileAsRead(testFilePath); + + const args = { + file_path: testFilePath, + edits: [ + { + old_string: "Hello world", + new_string: "Hi there", + }, + ], + }; + + const result = await multiEditTool.preprocess!(args); + expect(result.args.newContent).toContain("Hi there"); + }); + }); +}); \ No newline at end of file diff --git a/src/tools/multiEdit.ts b/src/tools/multiEdit.ts new file mode 100644 index 000000000..5326172ab --- /dev/null +++ b/src/tools/multiEdit.ts @@ -0,0 +1,314 @@ +import * as fs from "fs"; +import * as path from "path"; + +import { telemetryService } from "../telemetry/telemetryService.js"; +import { + calculateLinesOfCodeDiff, + getLanguageFromFilePath, +} from "../telemetry/utils.js"; + +import { readFilesSet, markFileAsRead } from "./edit.js"; +import { Tool } from "./types.js"; +import { generateDiff } from "./writeFile.js"; + +export { markFileAsRead }; + +export interface EditOperation { + old_string: string; + new_string: string; + replace_all?: boolean; +} + +export interface MultiEditArgs { + file_path: string; + edits: EditOperation[]; +} + +// Function to check if file has been read (shared with edit tool) +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", + readonly: false, + isBuiltIn: true, + description: `This is a tool for making multiple edits to a single file in one operation. It +is built on top of the Edit tool and allows you to perform multiple +find-and-replace operations efficiently. Prefer this tool over the Edit tool +when you need to make multiple edits to the same file. + + +Before using this tool: + + +1. Use the Read tool to understand the file's contents and context + +2. Verify the directory path is correct + + +To make multiple file edits, provide the following: + +1. file_path: The absolute path to the file to modify (must be absolute, not +relative) + +2. edits: An array of edit operations to perform, where each edit contains: + - old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation) + - new_string: The edited text to replace the old_string + - replace_all: Replace all occurences of old_string. This parameter is optional and defaults to false. + +IMPORTANT: + +- All edits are applied in sequence, in the order they are provided + +- Each edit operates on the result of the previous edit + +- All edits must be valid for the operation to succeed - if any edit fails, +none will be applied + +- This tool is ideal when you need to make several changes to different parts +of the same file + +- For Jupyter notebooks (.ipynb files), use the NotebookEdit instead + + +CRITICAL REQUIREMENTS: + +1. All edits follow the same requirements as the single Edit tool + +2. The edits are atomic - either all succeed or none are applied + +3. Plan your edits carefully to avoid conflicts between sequential operations + + +WARNING: + +- The tool will fail if edits.old_string doesn't match the file contents +exactly (including whitespace) + +- The tool will fail if edits.old_string and edits.new_string are the same + +- Since edits are applied in sequence, ensure that earlier edits don't affect +the text that later edits are trying to find + + +When making edits: + +- Ensure all edits result in idiomatic, correct code + +- Do not leave the code in a broken state + +- Always use absolute file paths (starting with /) + +- Only use emojis if the user explicitly requests it. Avoid adding emojis to +files unless asked. + +- Use replace_all for replacing and renaming strings across the file. This +parameter is useful if you want to rename a variable for instance. + + +If you want to create a new file, use: + +- A new file path, including dir name if needed + +- First edit: empty old_string and the new file's contents as new_string + +- Subsequent edits: normal edit operations on the created content`, + parameters: { + file_path: { + type: "string", + description: "The absolute path to the file to modify", + required: true, + }, + edits: { + type: "array", + description: + "Array of edit operations to perform sequentially on the file", + required: true, + }, + }, + preprocess: async (args) => { + // Validate and extract arguments + const { file_path, edits } = validateMultiEditArgs(args); + + // Validate each edit operation + validateEdits(edits); + + // Check if this is creating a new file (first edit has empty old_string) + const isCreatingNewFile = edits[0].old_string === ""; + + // Validate file access + validateFileAccess(file_path, isCreatingNewFile); + + // Read current file content (or start with empty for new files) + let currentContent = ""; + if (!isCreatingNewFile) { + currentContent = fs.readFileSync(file_path, "utf-8"); + } + + const originalContent = currentContent; + let newContent = currentContent; + + // Apply all edits sequentially + for (let i = 0; i < edits.length; i++) { + const isFirstEditOfNewFile = i === 0 && isCreatingNewFile; + newContent = applyEdit(newContent, edits[i], i, isFirstEditOfNewFile); + } + + // Generate diff for preview + const diff = generateDiff(originalContent, newContent, file_path); + + return { + args: { + file_path, + newContent, + originalContent, + isCreatingNewFile, + editCount: edits.length, + }, + preview: [ + { + type: "text", + content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${file_path}:`, + }, + { + type: "diff", + content: diff, + }, + ], + }; + }, + run: async (args: { + file_path: string; + newContent: string; + originalContent: string; + isCreatingNewFile: boolean; + editCount: number; + }) => { + try { + fs.writeFileSync(args.file_path, args.newContent, "utf-8"); + + // Get lines for telemetry + const { added, removed } = calculateLinesOfCodeDiff( + args.originalContent, + args.newContent, + ); + const language = getLanguageFromFilePath(args.file_path); + + if (added > 0) { + telemetryService.recordLinesOfCodeModified("added", added, language); + } + if (removed > 0) { + telemetryService.recordLinesOfCodeModified( + "removed", + removed, + language, + ); + } + + const action = args.isCreatingNewFile ? "created" : "edited"; + return `Successfully ${action} ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}`; + } catch (error) { + throw new Error( + `Error: failed to edit ${args.file_path}: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + }, +}; diff --git a/src/tools/readFile.ts b/src/tools/readFile.ts index 3600b5966..69e55efec 100644 --- a/src/tools/readFile.ts +++ b/src/tools/readFile.ts @@ -1,5 +1,6 @@ import * as fs from "fs"; +import { markFileAsRead } from "./edit.js"; import { formatToolArgument } from "./formatters.js"; import { Tool } from "./types.js"; @@ -33,6 +34,8 @@ export const readFileTool: Tool = { return `Error: File does not exist: ${args.filepath}`; } const content = fs.readFileSync(args.filepath, "utf-8"); + // Mark this file as read for the edit tool + markFileAsRead(args.filepath); return `Content of ${args.filepath}:\n${content}`; } catch (error) { return `Error reading file: ${ 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 f1d501cb2..9db6b2960 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"; @@ -14,9 +14,13 @@ import { import { getGitRemoteUrl, isGitRepo } from "../util/git.js"; 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"; @@ -25,15 +29,157 @@ import { useConfigSelector } from "./hooks/useConfigSelector.js"; import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; import { useModelSelector } from "./hooks/useModelSelector.js"; import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; -import { IntroMessage } from "./IntroMessage.js"; import { LoadingAnimation } from "./LoadingAnimation.js"; -import {MCPSelector} from "./MCPSelector.js"; +import { MCPSelector } from "./MCPSelector.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; @@ -45,6 +191,204 @@ 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 ( + + ); + } + + if (isScreenActive("mcp")) { + 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, @@ -57,25 +401,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<{ @@ -94,25 +420,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(() => { @@ -122,44 +445,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 @@ -201,26 +486,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 @@ -243,19 +510,15 @@ const TUIChat: React.FC = ({ /> )} */} - {/* Show intro message when ready */} - {showIntroMessage && - !isRemoteMode && - services.config?.config && - services.model?.model && - services.mcp?.mcpService && ( - - )} - {messages.map(renderMessage)} + {/* Chat content with intro message and messages in static container */} + {/* Fixed bottom section */} @@ -270,134 +533,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") && ( - - )} - - {/* MCP selector - shows above input when active */} - {isScreenActive("mcp") && ( - - )} - - {/* 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/StaticChatContent.tsx b/src/ui/components/StaticChatContent.tsx new file mode 100644 index 000000000..1575b21f9 --- /dev/null +++ b/src/ui/components/StaticChatContent.tsx @@ -0,0 +1,78 @@ +import type { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { Static } from "ink"; +import React from "react"; + +import type { MCPService } from "../../mcp.js"; +import { useTerminalSize } from "../hooks/useTerminalSize.js"; +import { IntroMessage } from "../IntroMessage.js"; +import type { DisplayMessage } from "../types.js"; + +interface StaticChatContentProps { + showIntroMessage: boolean; + config?: AssistantUnrolled; + model?: ModelConfig; + mcpService?: MCPService; + messages: DisplayMessage[]; + renderMessage: (message: DisplayMessage, index: number) => React.ReactElement; +} + +export const StaticChatContent: React.FC = ({ + showIntroMessage, + config, + model, + mcpService, + messages, + renderMessage, +}) => { + const { columns } = useTerminalSize(); + // Create a combined array of items to render + const staticItems = React.useMemo(() => { + const items: Array<{ + type: "intro" | "message"; + data: DisplayMessage | null; + index?: number; + }> = []; + + // Add intro message as first item if it should be shown + if (showIntroMessage && config && model && mcpService) { + items.push({ type: "intro", data: null }); + } + + // Add all chat messages + messages.forEach((message, index) => { + items.push({ type: "message", data: message, index }); + }); + + return items; + }, [showIntroMessage, config, model, mcpService, messages]); + + return ( + + {(item) => { + if (item.type === "intro" && config && model && mcpService) { + return ( + + ); + } else if ( + item.type === "message" && + item.data && + item.index !== undefined + ) { + return renderMessage(item.data, item.index); + } + return null; + }} + + ); +}; 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..b2b0687e3 --- /dev/null +++ b/src/ui/hooks/useChat.helpers.ts @@ -0,0 +1,364 @@ +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; + onShowMCPSelector?: () => void; +} + +/** + * Process slash command results + */ +export function processSlashCommandResult({ + result, + chatHistory, + setChatHistory, + setMessages, + exit, + onShowConfigSelector, + onShowModelSelector, + onShowMCPSelector, +}: ProcessSlashCommandResultOptions): string | null { + if (result.exit) { + exit(); + return null; + } + + if (result.openMcpSelector) { + onShowMCPSelector?.(); + 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 840a2e9e7..af9db6b3a 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -1,48 +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; - onShowMCPSelector?: () => 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, @@ -106,15 +96,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) { @@ -130,106 +114,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(() => { @@ -240,10 +132,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); @@ -269,265 +158,84 @@ 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.openMCPSelector && onShowMCPSelector) { - onShowMCPSelector(); - 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, + onShowMCPSelector, + }); - 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 = { @@ -550,143 +258,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, { @@ -758,107 +352,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..b5e0ba6d0 --- /dev/null +++ b/src/ui/hooks/useChat.types.ts @@ -0,0 +1,63 @@ +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; + onShowMCPSelector: () => 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; + openMcpSelector?: boolean; + compact?: boolean; + model?: string; +} 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({ diff --git a/src/util/exponentialBackoff.test.ts b/src/util/exponentialBackoff.test.ts index 05fd9f30a..bd0e96c4d 100644 --- a/src/util/exponentialBackoff.test.ts +++ b/src/util/exponentialBackoff.test.ts @@ -13,7 +13,9 @@ function isRetryableError(error: any): boolean { if ( error.code === "ECONNRESET" || error.code === "ENOTFOUND" || - error.code === "ETIMEDOUT" + error.code === "ETIMEDOUT" || + error.code === "EPIPE" || + error.code === "ECONNREFUSED" ) { return true; } @@ -30,6 +32,21 @@ function isRetryableError(error: any): boolean { return true; } + // Anthropic specific errors + const lower = error.message?.toLowerCase(); + if (lower?.includes("overloaded")) { + return true; + } + + // Check for premature close errors by message content + if (lower?.includes("premature close") || + lower?.includes("premature end") || + lower?.includes("connection reset") || + lower?.includes("socket hang up") || + lower?.includes("aborted")) { + return true; + } + return false; } @@ -96,6 +113,51 @@ describe("exponentialBackoff utilities", () => { expect(isRetryableError(error)).toBe(true); }); + it("should return true for EPIPE errors", () => { + const error = { code: "EPIPE" }; + expect(isRetryableError(error)).toBe(true); + }); + + it("should return true for ECONNREFUSED errors", () => { + const error = { code: "ECONNREFUSED" }; + expect(isRetryableError(error)).toBe(true); + }); + + it("should return true for Anthropic overloaded errors", () => { + const error = { message: "The service is overloaded" }; + expect(isRetryableError(error)).toBe(true); + }); + + it("should return true for premature close errors", () => { + const error = { message: "Error: Premature close" }; + expect(isRetryableError(error)).toBe(true); + }); + + it("should return true for premature end errors", () => { + const error = { message: "Premature end of response" }; + expect(isRetryableError(error)).toBe(true); + }); + + it("should return true for connection reset errors", () => { + const error = { message: "Connection reset by peer" }; + expect(isRetryableError(error)).toBe(true); + }); + + it("should return true for socket hang up errors", () => { + const error = { message: "socket hang up" }; + expect(isRetryableError(error)).toBe(true); + }); + + it("should return true for aborted connection errors", () => { + const error = { message: "Request aborted" }; + expect(isRetryableError(error)).toBe(true); + }); + + it("should handle case insensitive error messages", () => { + const error = { message: "PREMATURE CLOSE" }; + expect(isRetryableError(error)).toBe(true); + }); + it("should return false for 400 Bad Request", () => { const error = { status: 400 }; expect(isRetryableError(error)).toBe(false); diff --git a/src/util/exponentialBackoff.ts b/src/util/exponentialBackoff.ts index d594b488c..cff81418f 100644 --- a/src/util/exponentialBackoff.ts +++ b/src/util/exponentialBackoff.ts @@ -30,34 +30,75 @@ const DEFAULT_OPTIONS: Required = { hiddenRetries: 2, }; +/** + * Checks if the error is a network-related error + */ +function isNetworkError(error: any): boolean { + const networkCodes = [ + "ECONNRESET", + "ENOTFOUND", + "ETIMEDOUT", + "EPIPE", + "ECONNREFUSED", + ]; + return networkCodes.includes(error.code); +} + +/** + * Checks if the HTTP status code is retryable + */ +function isRetryableHttpStatus(status: number): boolean { + // 429 (Too Many Requests), 502 (Bad Gateway), 503 (Service Unavailable), 504 (Gateway Timeout) + return status === 429 || status === 502 || status === 503 || status === 504; +} + +/** + * Checks if the error type indicates a server issue + */ +function isServerError(error: any): boolean { + return error.type === "server_error" || error.type === "rate_limit_exceeded"; +} + +/** + * Checks if the error message indicates a connection issue + */ +function isConnectionError(errorMessage: string): boolean { + const connectionErrorPatterns = [ + "premature close", + "premature end", + "connection reset", + "socket hang up", + "aborted", + "overloaded", + ]; + + return connectionErrorPatterns.some((pattern) => + errorMessage.includes(pattern), + ); +} + /** * Determines if an error is retryable based on the error type and status code */ function isRetryableError(error: any): boolean { // Network errors are retryable - if ( - error.code === "ECONNRESET" || - error.code === "ENOTFOUND" || - error.code === "ETIMEDOUT" - ) { + if (isNetworkError(error)) { return true; } // HTTP status codes that are retryable - if (error.status) { - const status = error.status; - // 429 (Too Many Requests), 502 (Bad Gateway), 503 (Service Unavailable), 504 (Gateway Timeout) - return status === 429 || status === 502 || status === 503 || status === 504; - } - - // OpenAI specific errors - if (error.type === "server_error" || error.type === "rate_limit_exceeded") { + if (error.status && isRetryableHttpStatus(error.status)) { return true; } - // Anthropic specific errors - const lower = error.message?.toLowerCase(); - if (lower?.includes("overloaded")) { + // OpenAI/API specific errors + if (isServerError(error)) { + return true; + } + + // Check for connection issues by message content + const errorMessage = error.message?.toLowerCase(); + if (errorMessage && isConnectionError(errorMessage)) { return true; } diff --git a/src/util/formatError.test.ts b/src/util/formatError.test.ts index db60d8637..8b38a98e1 100644 --- a/src/util/formatError.test.ts +++ b/src/util/formatError.test.ts @@ -1,4 +1,4 @@ -import { formatError } from './formatError.js'; +import { formatError, formatAnthropicError } from './formatError.js'; describe('formatError', () => { it('should format Error objects correctly', () => { @@ -32,33 +32,33 @@ describe('formatError', () => { }); it('should format API errors with status and message', () => { - const error = { - status: 404, - error: { message: 'Not found' } + const error = { + status: 404, + error: { message: 'Not found' } }; // The actual implementation prioritizes nested error.message over status formatting expect(formatError(error)).toBe('Not found'); }); it('should format network errors with code and syscall', () => { - const error = { - code: 'ECONNREFUSED', - syscall: 'connect' + const error = { + code: 'ECONNREFUSED', + syscall: 'connect' }; expect(formatError(error)).toBe('Network error: ECONNREFUSED in connect'); }); it('should join error arrays', () => { - const error = { - errors: ['First error', 'Second error', 'Third error'] + const error = { + errors: ['First error', 'Second error', 'Third error'] }; expect(formatError(error)).toBe('First error, Second error, Third error'); }); it('should JSON stringify complex objects', () => { - const error = { - code: 'CUSTOM_ERROR', - data: { id: 123, name: 'test' } + const error = { + code: 'CUSTOM_ERROR', + data: { id: 123, name: 'test' } }; expect(formatError(error)).toBe('{"code":"CUSTOM_ERROR","data":{"id":123,"name":"test"}}'); }); @@ -66,7 +66,7 @@ describe('formatError', () => { it('should handle objects that cannot be JSON stringified', () => { const circular: any = { name: 'circular' }; circular.self = circular; - + const result = formatError(circular); expect(result).toBe('An error occurred: [object Object]'); }); @@ -97,7 +97,7 @@ describe('formatError', () => { }); it('should prioritize message over other properties', () => { - const error = { + const error = { message: 'Primary message', description: 'Secondary description', details: 'Tertiary details' @@ -106,7 +106,7 @@ describe('formatError', () => { }); it('should prioritize error property over details', () => { - const error = { + const error = { error: 'Nested error', details: 'Error details' }; @@ -114,21 +114,38 @@ describe('formatError', () => { }); it('should handle deeply nested error structures', () => { - const error = { - error: { - error: { - message: 'Deep nested error' - } - } + const error = { + error: { + error: { + message: 'Deep nested error' + } + } }; expect(formatError(error)).toBe('Deep nested error'); }); it('should format API errors with status only when no nested error message', () => { - const error = { - status: 404, - error: { code: 'NOT_FOUND' } + const error = { + status: 404, + error: { code: 'NOT_FOUND' } }; expect(formatError(error)).toBe('{"code":"NOT_FOUND"}'); }); -}); \ No newline at end of file +}); + +describe('formatAnthropicError', () => { + it('should format invalid API key authentication errors', () => { + const error = new Error('{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}'); + expect(formatAnthropicError(error)).toBe('Anthropic: Invalid API key'); + }); + + it('should handle error objects in general', () => { + const error = new Error('some error'); // some error we haven't catalogued yet + console.log(formatAnthropicError(error)) + expect(formatAnthropicError(error)).toBe('Anthropic: some error'); + }); + + it('should handle undefined values', () => { + expect(formatAnthropicError(undefined)).toBe('Anthropic: undefined'); + }); +}); diff --git a/src/util/formatError.ts b/src/util/formatError.ts index 177ac2ef0..f806cfca9 100644 --- a/src/util/formatError.ts +++ b/src/util/formatError.ts @@ -51,3 +51,21 @@ export function formatError(error: any): string { return String(error); } + +// Anthropic errors are stringfied JSON objects, format them to be more user friendly +export function formatAnthropicError(error: any): string { + const prefix = "Anthropic:"; + + if (error instanceof Error) { + if ( + error.message.includes("authentication_error") && + error.message.includes("invalid x-api-key") + ) { + return `${prefix} Invalid API key`; + } + + return `${prefix} ${error.message}`; + } + + return `${prefix} ${String(error)}`; +} diff --git a/src/util/inputHistory.test.ts b/src/util/inputHistory.test.ts new file mode 100644 index 000000000..d5b4c571e --- /dev/null +++ b/src/util/inputHistory.test.ts @@ -0,0 +1,88 @@ +import { vi } from 'vitest'; + +import { InputHistory } from './inputHistory.js'; + +// Mock fs to avoid creating actual files during tests +vi.mock('fs', () => ({ + default: { + existsSync: vi.fn(), + readFileSync: vi.fn(), + writeFileSync: vi.fn(), + mkdirSync: vi.fn() + }, + existsSync: vi.fn(), + readFileSync: vi.fn(), + writeFileSync: vi.fn(), + mkdirSync: vi.fn() +})); + +describe('InputHistory', () => { + let inputHistory: InputHistory; + + beforeEach(async () => { + // Reset mocks and set up default behavior + vi.clearAllMocks(); + const fs = await import('fs'); + vi.mocked(fs.existsSync).mockReturnValue(false); + vi.mocked(fs.readFileSync).mockReturnValue('[]'); + + inputHistory = new InputHistory(); + }); + + describe('navigation with typed input preservation', () => { + beforeEach(() => { + // Add some history entries + inputHistory.addEntry('first command'); + inputHistory.addEntry('second command'); + }); + + it('should preserve typed input when navigating history', () => { + const typedInput = 'user typed this'; + + // User types something then presses up arrow + const historyEntry1 = inputHistory.navigateUp(typedInput); + expect(historyEntry1).toBe('second command'); + + // Then presses down arrow - should get back their typed input + const returnedInput = inputHistory.navigateDown(); + expect(returnedInput).toBe('user typed this'); + }); + + it('should handle multiple up/down navigation cycles', () => { + const typedInput = 'hello world'; + + // Navigate up twice, then back down twice + inputHistory.navigateUp(typedInput); + inputHistory.navigateUp(typedInput); + inputHistory.navigateDown(); // Go back one in history + const result = inputHistory.navigateDown(); // Go back to original + + expect(result).toBe('hello world'); + }); + }); + + describe('basic navigation functionality', () => { + beforeEach(() => { + inputHistory.addEntry('command1'); + inputHistory.addEntry('command2'); + inputHistory.addEntry('command3'); + }); + + it('should navigate up through history in reverse order', () => { + const result1 = inputHistory.navigateUp('current'); + expect(result1).toBe('command3'); // Most recent first + + const result2 = inputHistory.navigateUp('current'); + expect(result2).toBe('command2'); + + const result3 = inputHistory.navigateUp('current'); + expect(result3).toBe('command1'); + }); + + it('should handle navigation with no history', () => { + const emptyHistory = new InputHistory(); + const result = emptyHistory.navigateUp('test'); + expect(result).toBe(null); + }); + }); +}); \ No newline at end of file diff --git a/src/util/inputHistory.ts b/src/util/inputHistory.ts index 7c076bf1f..32cc2a9f0 100644 --- a/src/util/inputHistory.ts +++ b/src/util/inputHistory.ts @@ -93,8 +93,9 @@ export class InputHistory { return this.history[this.currentIndex]?.text || null; } else { // Return to original input + const originalInput = this.originalInput; this.resetNavigation(); - return this.originalInput; + return originalInput; } } diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts new file mode 100644 index 000000000..53d6d8210 --- /dev/null +++ b/vitest.e2e.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + globals: true, + environment: "node", + setupFiles: ["./vitest.setup.ts"], + include: ["src/e2e/**/*.test.ts"], + testTimeout: 30000, + hookTimeout: 30000, + }, + resolve: { + extensions: [".js", ".ts", ".tsx", ".json"], + }, +}); diff --git a/vitest.setup.ts b/vitest.setup.ts index 0a8dd66dc..c7ad30ec3 100644 --- a/vitest.setup.ts +++ b/vitest.setup.ts @@ -10,6 +10,15 @@ vi.mock("open", () => ({ default: vi.fn().mockResolvedValue(undefined), })); +// Mock constructSystemMessage to avoid service container issues in tests +vi.mock("./src/systemMessage.js", () => ({ + constructSystemMessage: vi + .fn() + .mockResolvedValue( + "You are an agent in the Continue CLI. Given the user's prompt, you should use the tools available to you to answer the user's question.", + ), +})); + // Set up global afterEach hook to clear all timers and reset console afterEach(() => { // Clear vitest timers