diff --git a/.github/actions/run-jetbrains-tests/action.yml b/.github/actions/run-jetbrains-tests/action.yml index e05437f77..77f6ceff3 100644 --- a/.github/actions/run-jetbrains-tests/action.yml +++ b/.github/actions/run-jetbrains-tests/action.yml @@ -44,6 +44,7 @@ runs: - name: Setup FFmpeg uses: AnimMouse/setup-ffmpeg@v1 with: + version: 7.1 token: ${{ inputs.github-token }} - name: Setup Gradle @@ -135,14 +136,22 @@ runs: shell: bash run: | cd extensions/intellij - mv video build/reports + if [ -d "video" ]; then + mv video build/reports + else + echo "No video directory found to move" + fi - name: Copy logs if: ${{ failure() }} shell: bash run: | cd extensions/intellij - mv build/idea-sandbox/system/log/ build/reports + if [ -d "build/idea-sandbox/system/log/" ]; then + mv build/idea-sandbox/system/log/ build/reports + else + echo "No log directory found to copy" + fi - name: Save fails report if: ${{ failure() }} diff --git a/.github/actions/track-rerun/action.yml b/.github/actions/track-rerun/action.yml new file mode 100644 index 000000000..d9bcb2423 --- /dev/null +++ b/.github/actions/track-rerun/action.yml @@ -0,0 +1,19 @@ +name: Track Workflow Rerun +description: Track when GitHub Actions workflows are rerun (attempt > 1) + +runs: + using: composite + steps: + # Eventually we can start logging this to monitor codebase health (e.g. to Slack, PostHog, etc.) + - name: Track workflow rerun + if: github.run_attempt > 1 + shell: bash + run: | + echo "🔄 Workflow rerun detected - Attempt #${{ github.run_attempt }}" + echo "📊 Workflow: ${{ github.workflow }}" + echo "🔀 PR: ${{ github.event.pull_request.number || 'N/A' }}" + echo "📝 Commit: ${{ github.sha }}" + echo "👤 Actor: ${{ github.actor }}" + echo "⏰ Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "" + echo "::notice title=Workflow Rerun Detected::This is attempt #${{ github.run_attempt }} of workflow '${{ github.workflow }}'" diff --git a/.github/workflows/cli-pr-checks.yml b/.github/workflows/cli-pr-checks.yml index b08207074..8dd195305 100644 --- a/.github/workflows/cli-pr-checks.yml +++ b/.github/workflows/cli-pr-checks.yml @@ -12,6 +12,14 @@ permissions: issues: write jobs: + track-rerun: + runs-on: ubuntu-latest + if: github.run_attempt > 1 + steps: + - uses: actions/checkout@v4 + - name: Track workflow rerun + uses: ./.github/actions/track-rerun + lint: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index cf276f360..785044868 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -9,7 +9,7 @@ on: publish_build: description: "Whether or not to publish the built extension to the VS Code marketplace" required: true - default: false + default: "false" jobs: check_release_name: diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index fb91e8d97..e37127d1f 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -11,6 +11,14 @@ on: - main jobs: + track-rerun: + runs-on: ubuntu-latest + if: github.run_attempt > 1 + steps: + - uses: actions/checkout@v5 + - name: Track workflow rerun + uses: ./.github/actions/track-rerun + prettier-check: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 289381034..7e054eb59 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -9,7 +9,7 @@ on: publish_build: description: "Whether or not to publish the built extension to the VS Code marketplace" required: true - default: false + default: "false" jobs: check_release_name: diff --git a/extensions/cli/build.mjs b/extensions/cli/build.mjs index 8cf88d40d..f5f20778c 100644 --- a/extensions/cli/build.mjs +++ b/extensions/cli/build.mjs @@ -1,8 +1,8 @@ #!/usr/bin/env node import * as esbuild from "esbuild"; -import { writeFileSync, chmodSync } from "fs"; -import { resolve, dirname } from "path"; +import { chmodSync, writeFileSync } from "fs"; +import { dirname, resolve } from "path"; import { fileURLToPath } from "url"; const __dirname = dirname(fileURLToPath(import.meta.url)); @@ -59,9 +59,15 @@ try { __dirname, "../../packages/config-types/dist/index.js", ), - "core": resolve(__dirname, "../../core"), - "@continuedev/fetch": resolve(__dirname, "../../packages/fetch/dist/index.js"), - "@continuedev/llm-info": resolve(__dirname, "../../packages/llm-info/dist/index.js"), + core: resolve(__dirname, "../../core"), + "@continuedev/fetch": resolve( + __dirname, + "../../packages/fetch/dist/index.js", + ), + "@continuedev/llm-info": resolve( + __dirname, + "../../packages/llm-info/dist/index.js", + ), }, // Add banner to create require for CommonJS packages @@ -76,7 +82,7 @@ const require = createRequire(import.meta.url);`, // Create wrapper script with shebang writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');"); - + // Make the wrapper script executable chmodSync("dist/cn.js", 0o755); diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index c3177a10a..fe4dafc0d 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -159,7 +159,7 @@ async function handleManualCompaction( } } -// Helper function to handle auto-compaction +// Helper function to handle auto-compaction for headless mode async function handleAutoCompaction( chatHistory: ChatCompletionMessageParam[], model: ModelConfig, @@ -167,64 +167,71 @@ async function handleAutoCompaction( isHeadless: boolean, format?: "json", ): Promise { - logger.info("Auto-compacting triggered due to context limit"); + const { handleAutoCompaction: coreAutoCompaction } = await import( + "../streamChatResponse.autoCompaction.js" + ); - 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", - ); - } + // Custom callbacks for headless mode console output + const callbacks = { + onSystemMessage: (message: string) => { + if ( + message.includes("Auto-compacting") || + message.includes("Approaching") + ) { + if (!isHeadless) { + console.info(chalk.yellow(`\n${message}`)); + } else if (format === "json") { + safeStdout( + JSON.stringify({ + status: "info", + message: "Auto-compacting triggered", + contextUsage: + calculateContextUsagePercentage( + countChatHistoryTokens(chatHistory), + model, + ) + "%", + }) + "\n", + ); + } + } else if (message.includes("✓")) { + if (!isHeadless) { + console.info(chalk.green(message)); + } else if (format === "json") { + safeStdout( + JSON.stringify({ + status: "success", + message: "Auto-compacted successfully", + historyLength: chatHistory.length, + }) + "\n", + ); + } + } else if (message.includes("Warning:")) { + if (!isHeadless) { + console.error(chalk.red(message)); + console.info(chalk.yellow("Continuing without compaction...")); + } else if (format === "json") { + safeStdout( + JSON.stringify({ + status: "warning", + message: "Auto-compaction failed, continuing without compaction", + }) + "\n", + ); + } + } + }, + }; - try { - const result = await compactChatHistory(chatHistory, model, llmApi); - chatHistory.length = 0; - chatHistory.push(...result.compactedHistory); - saveSession(chatHistory); + const result = await coreAutoCompaction(chatHistory, model, llmApi, { + isHeadless, + format, + callbacks, + }); - 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 the original array reference for headless mode + chatHistory.length = 0; + chatHistory.push(...result.chatHistory); - 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; - } + return result.compactionIndex; } interface ProcessMessageOptions { diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts index 07e893935..d1e6325e9 100644 --- a/extensions/cli/src/commands/commands.ts +++ b/extensions/cli/src/commands/commands.ts @@ -4,9 +4,9 @@ import { type AssistantConfig } from "@continuedev/sdk"; export { chat } from "./chat.js"; export { login } from "./login.js"; export { logout } from "./logout.js"; +export { listSessionsCommand } from "./ls.js"; export { remote } from "./remote.js"; export { serve } from "./serve.js"; -export { listSessionsCommand } from "./ls.js"; export interface SlashCommand { name: string; @@ -45,6 +45,11 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ description: "Check who you're currently logged in as", category: "system", }, + { + name: "info", + description: "Show session information", + category: "system", + }, { name: "model", description: "Switch between available chat models", diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts new file mode 100644 index 000000000..c0f1127cd --- /dev/null +++ b/extensions/cli/src/compaction.infiniteLoop.test.ts @@ -0,0 +1,138 @@ +import { ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { describe, it, expect, vi } from "vitest"; + +import { compactChatHistory } from "./compaction.js"; +import { streamChatResponse } from "./streamChatResponse.js"; + +// Mock the dependencies +vi.mock("./streamChatResponse.js", () => ({ + streamChatResponse: vi.fn(), +})); + +vi.mock("./util/tokenizer.js", () => ({ + countChatHistoryTokens: vi.fn(), + getModelContextLimit: vi.fn(), +})); + +describe("compaction infinite loop prevention", () => { + const mockModel: ModelConfig = { + name: "test-model", + provider: "test", + model: "test-model", + defaultCompletionOptions: { + maxTokens: 1000, + contextLength: 4000, + }, + } as ModelConfig; + + const mockLlmApi = {} as BaseLlmApi; + + it("should not loop infinitely when pruning doesn't reduce history size", async () => { + const { countChatHistoryTokens, getModelContextLimit } = await import( + "./util/tokenizer.js" + ); + const mockStreamResponse = vi.mocked(streamChatResponse); + const mockCountTokens = vi.mocked(countChatHistoryTokens); + const mockGetContextLimit = vi.mocked(getModelContextLimit); + + // Setup mocks + mockGetContextLimit.mockReturnValue(4000); + mockCountTokens.mockReturnValue(5000); // Always too big + mockStreamResponse.mockImplementation( + async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.("Summary"); + return "Summary"; + }, + ); + + // History that can't be pruned further (only system message) + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System message" }, + ]; + + // This should not hang - it should break out of the loop + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); + + // Should complete successfully even though token count is still too high + expect(result.compactedHistory).toBeDefined(); + expect(mockCountTokens).toHaveBeenCalled(); + }); + + it("should not loop infinitely with history ending in assistant message", async () => { + const { countChatHistoryTokens, getModelContextLimit } = await import( + "./util/tokenizer.js" + ); + const mockStreamResponse = vi.mocked(streamChatResponse); + const mockCountTokens = vi.mocked(countChatHistoryTokens); + const mockGetContextLimit = vi.mocked(getModelContextLimit); + + // Setup mocks + mockGetContextLimit.mockReturnValue(4000); + mockCountTokens.mockReturnValue(5000); // Always too big + mockStreamResponse.mockImplementation( + async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.("Summary"); + return "Summary"; + }, + ); + + // History that ends with assistant - pruning won't change it + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System message" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]; + + // This should not hang + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); + + expect(result.compactedHistory).toBeDefined(); + }); + + it("should successfully prune when pruning actually reduces size", async () => { + const { countChatHistoryTokens, getModelContextLimit } = await import( + "./util/tokenizer.js" + ); + const mockStreamResponse = vi.mocked(streamChatResponse); + const mockCountTokens = vi.mocked(countChatHistoryTokens); + const mockGetContextLimit = vi.mocked(getModelContextLimit); + + // Setup mocks + mockGetContextLimit.mockReturnValue(4000); + + // Mock token counting to show reduction after pruning + let callCount = 0; + mockCountTokens.mockImplementation(() => { + callCount++; + if (callCount === 1) return 5000; // Initial too big + if (callCount === 2) return 3000; // After pruning, fits + return 2000; // Subsequent calls + }); + + mockStreamResponse.mockImplementation( + async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.("Summary"); + return "Summary"; + }, + ); + + // History that can be successfully pruned + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System message" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + { role: "user", content: "Another question" }, + ]; + + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); + + expect(result.compactedHistory).toBeDefined(); + // The function will call countTokens multiple times during the process + expect(mockCountTokens).toHaveBeenCalled(); + }); +}); diff --git a/extensions/cli/src/compaction.pruneLastMessage.test.ts b/extensions/cli/src/compaction.pruneLastMessage.test.ts new file mode 100644 index 000000000..40e10949d --- /dev/null +++ b/extensions/cli/src/compaction.pruneLastMessage.test.ts @@ -0,0 +1,185 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { describe, it, expect } from "vitest"; + +import { pruneLastMessage } from "./compaction.js"; + +describe("pruneLastMessage", () => { + it("should return empty array for empty input", () => { + const result = pruneLastMessage([]); + expect(result).toEqual([]); + }); + + it("should remove single user message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "user", content: "Hello" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should return empty array for single system message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should return empty array for single assistant message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "assistant", content: "Hello" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should return empty array for single tool message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "tool", content: "Tool output", tool_call_id: "1" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should remove last message when second-to-last is user", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([{ role: "system", content: "System" }]); + }); + + it("should remove assistant+tool sequence when second-to-last is assistant with tool calls", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Run command" }, + { + role: "assistant", + content: "Running...", + tool_calls: [{ id: "1" } as any], + }, + { role: "tool", content: "Command output", tool_call_id: "1" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Run command" }, + ]); + }); + + it("should prune last message when second-to-last is not user or assistant with tool calls", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "assistant", content: "Hi there" }, + { role: "user", content: "Another question" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "assistant", content: "Hi there" }, + ]); + }); + + it("should handle multiple user messages by removing two at a time", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Question 1" }, + { role: "user", content: "Question 2" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([{ role: "system", content: "System" }]); + }); + + it("should handle tool call sequences by removing user after tool", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Do something" }, + { + role: "assistant", + content: "I'll help", + tool_calls: [{ id: "1" } as any], + }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + { role: "user", content: "Follow up question" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Do something" }, + { + role: "assistant", + content: "I'll help", + tool_calls: [{ id: "1" } as any], + }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + ]); + }); + + it("should remove both user messages when consecutive", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "user", content: "Hello" }, + { role: "user", content: "Another message" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should handle complex conversation flow", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Request 1" }, + { role: "assistant", content: "Response 1" }, + { role: "user", content: "Request 2" }, + { + role: "assistant", + content: "Using tool", + tool_calls: [{ id: "1" } as any], + }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + { role: "assistant", content: "Final response" }, + { role: "user", content: "Follow up 1" }, + { role: "user", content: "Follow up 2" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Request 1" }, + { role: "assistant", content: "Response 1" }, + { role: "user", content: "Request 2" }, + { + role: "assistant", + content: "Using tool", + tool_calls: [{ id: "1" } as any], + }, + { role: "tool", content: "Tool result", tool_call_id: "1" }, + { role: "assistant", content: "Final response" }, + ]); + }); + + it("should handle history starting with non-system message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi" }, + { role: "user", content: "Follow up" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi" }, + ]); + }); +}); diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index c60f814a7..920f754d7 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -5,6 +5,10 @@ import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { streamChatResponse } from "./streamChatResponse.js"; import { StreamCallbacks } from "./streamChatResponse.types.js"; import { logger } from "./util/logger.js"; +import { + countChatHistoryTokens, + getModelContextLimit, +} from "./util/tokenizer.js"; export const COMPACTION_MARKER = "[COMPACTED HISTORY]"; @@ -41,8 +45,39 @@ export async function compactChatHistory( "Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.", }; - // Get the current history for compaction - const historyForCompaction = [...chatHistory, compactionPrompt]; + // Check if the history with compaction prompt is too long, prune if necessary + let historyToUse = chatHistory; + let historyForCompaction = [...historyToUse, compactionPrompt]; + + const contextLimit = getModelContextLimit(model); + const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; + const reservedForOutput = + maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); + const availableForInput = contextLimit - reservedForOutput; + + // Check if we need to prune to fit within context + while ( + countChatHistoryTokens(historyForCompaction) > availableForInput && + historyToUse.length > 0 + ) { + logger.debug("Compaction history too long, pruning last message", { + tokenCount: countChatHistoryTokens(historyForCompaction), + availableForInput, + historyLength: historyToUse.length, + }); + const prunedHistory = pruneLastMessage(historyToUse); + + // Break if pruning didn't change the history (prevents infinite loop) + if (prunedHistory.length === historyToUse.length) { + logger.warn( + "Cannot prune history further while maintaining valid conversation structure", + ); + break; + } + + historyToUse = prunedHistory; + historyForCompaction = [...historyToUse, compactionPrompt]; + } // Stream the compaction response const controller = new AbortController(); @@ -121,6 +156,39 @@ export function findCompactionIndex( * @param compactionIndex The index of the compaction message, if any * @returns The history to send to the LLM */ +/** + * Prunes chat history by removing messages from the end while ensuring + * the history ends with either an assistant message or a tool result message + * @param chatHistory The chat history to prune + * @returns The pruned chat history ending with assistant or tool message + */ +export function pruneLastMessage( + chatHistory: ChatCompletionMessageParam[], +): ChatCompletionMessageParam[] { + if (chatHistory.length === 0) { + return chatHistory; + } + + if (chatHistory.length === 1) { + // Only one message - always return empty array + return []; + } + + const secondToLastIndex = chatHistory.length - 2; + const secondToLastMessage = chatHistory[secondToLastIndex]; + + if ( + secondToLastMessage.role === "assistant" && + secondToLastMessage.tool_calls?.length + ) { + return chatHistory.slice(0, -2); + } else if (secondToLastMessage.role === "user") { + return chatHistory.slice(0, -2); + } + + return chatHistory.slice(0, -1); +} + export function getHistoryForLLM( fullHistory: ChatCompletionMessageParam[], compactionIndex: number | null, diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts index f843218a6..11e39ccc7 100644 --- a/extensions/cli/src/session.ts +++ b/extensions/cli/src/session.ts @@ -180,7 +180,7 @@ function getSessionDir(): string { /** * Get the session file path for the current session */ -function getSessionFilePath(): string { +export function getSessionFilePath(): string { const sessionId = getSessionId(); const sessionDir = getSessionDir(); return path.join(sessionDir, `${sessionId}.json`); diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index 986ed17ee..50185cf33 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -1,147 +1,231 @@ -// Import after mocking -import { AssistantUnrolled } from "@continuedev/config-yaml"; -import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import type { AssistantUnrolled } from "@continuedev/config-yaml"; +import { + describe, + it, + expect, + vi, + beforeEach, + type MockedFunction, +} from "vitest"; -import * as workos from "./auth/workos.js"; -import * as commands from "./commands/commands.js"; -import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; -import type { AuthServiceState } from "./services/types.js"; +import type { AuthConfig, AuthenticatedConfig } from "./auth/workos.js"; +import type { ConfigServiceState } from "./services/types.js"; import { handleSlashCommands } from "./slashCommands.js"; -// The imports are already mocked via vitest.setup.ts, so we can use them directly +// Mock the services +vi.mock("./services/index.js", () => ({ + services: { + config: { + getState: vi.fn(), + }, + }, + reloadService: vi.fn(), + SERVICE_NAMES: { + AUTH: "AUTH", + }, +})); -// Mock console to avoid output during tests -const originalConsole = console; -const mockConsole = { - info: vi.fn(), - error: vi.fn(), - log: vi.fn(), -}; +// Mock auth functions +vi.mock("./auth/workos.js", () => ({ + isAuthenticated: vi.fn(), + isAuthenticatedConfig: vi.fn(), + loadAuthConfig: vi.fn(), +})); -describe("handleSlashCommands", () => { +// Mock telemetry +vi.mock("./telemetry/posthogService.js", () => ({ + posthogService: { + capture: vi.fn(), + }, +})); + +// Mock commands +vi.mock("./commands/commands.js", () => ({ + getAllSlashCommands: vi.fn(() => []), +})); + +// Mock os and path +vi.mock("os", () => ({ + default: { + homedir: vi.fn(() => "/home/test"), + }, +})); + +vi.mock("path", () => ({ + default: { + join: vi.fn((...parts) => parts.join("/")), + }, + join: vi.fn((...parts) => parts.join("/")), +})); + +// Mock session functions +vi.mock("./session.js", () => ({ + getSessionFilePath: vi.fn( + () => "/home/test/.continue/cli-sessions/continue-cli-pid-12345.json", + ), + hasSession: vi.fn(() => false), +})); + +describe("slashCommands", () => { const mockAssistant: AssistantUnrolled = { name: "test-assistant", version: "1.0.0", - prompts: [{ name: "test", prompt: "Test prompt: " }], }; beforeEach(() => { - Object.assign(console, mockConsole); vi.clearAllMocks(); - - // Since the mock already returns the required value, we don't need to set it - // Just verify it returns what we expect - expect(commands.getAllSlashCommands(mockAssistant)).toEqual( - expect.arrayContaining([ - expect.objectContaining({ name: "help" }), - expect.objectContaining({ name: "login" }), - ]), - ); }); - afterEach(() => { - Object.assign(console, originalConsole); - }); + describe("handleSlashCommands", () => { + it("should handle /info command when not authenticated", async () => { + const { isAuthenticated } = await import("./auth/workos.js"); + const { services } = await import("./services/index.js"); - describe("Automatic Service Cascade Reloading", () => { - test.skip("login command should trigger automatic cascade reload via auth service", async () => { - const newAuthState: AuthServiceState = { - authConfig: { userEmail: "test@example.com" } as any, - isAuthenticated: true, + ( + isAuthenticated as MockedFunction + ).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ + config: null, + configPath: "/test/config.yaml", + } as ConfigServiceState); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result).toBeDefined(); + expect(result?.output).toContain("Authentication:"); + expect(result?.output).toContain("Not logged in"); + expect(result?.output).toContain("Configuration:"); + expect(result?.output).toContain("/test/config.yaml"); + expect(result?.output).toContain("Session History:"); + expect(result?.output).toContain(".json"); + expect(result?.exit).toBe(false); + }); + + it("should handle /info command when authenticated via environment", async () => { + const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } = + await import("./auth/workos.js"); + const { services } = await import("./services/index.js"); + + ( + isAuthenticated as MockedFunction + ).mockReturnValue(true); + (loadAuthConfig as MockedFunction).mockReturnValue( + {} as AuthConfig, + ); + (isAuthenticatedConfig as any).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ + config: null, + configPath: undefined, + } as ConfigServiceState); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result).toBeDefined(); + expect(result?.output).toContain("Authentication:"); + expect(result?.output).toContain( + "Authenticated via environment variable", + ); + expect(result?.output).toContain("Configuration:"); + expect(result?.output).toContain("Config not found"); + expect(result?.exit).toBe(false); + }); + + it("should handle /info command when authenticated with user config", async () => { + const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } = + await import("./auth/workos.js"); + const { services } = await import("./services/index.js"); + + const mockAuthConfig: AuthenticatedConfig = { + userId: "test-user-id", + userEmail: "test@example.com", + accessToken: "test-token", + refreshToken: "test-refresh-token", + expiresAt: Date.now() + 3600000, + organizationId: "test-org-id", }; - (services.auth.login as any).mockResolvedValue(newAuthState); - (workos.isAuthenticatedConfig as any).mockReturnValue(true); - (reloadService as any).mockResolvedValue(undefined); + ( + isAuthenticated as MockedFunction + ).mockReturnValue(true); + (loadAuthConfig as MockedFunction).mockReturnValue( + mockAuthConfig, + ); + (isAuthenticatedConfig as any).mockReturnValue(true); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ + config: null, + configPath: "/custom/config.yaml", + } as ConfigServiceState); - const result = await handleSlashCommands("/login", mockAssistant); + const result = await handleSlashCommands("/info", mockAssistant); - expect(result).not.toBeNull(); - expect(result?.output).toContain( - "Login successful! All services updated automatically.", + expect(result).toBeDefined(); + expect(result?.output).toContain("Authentication:"); + expect(result?.output).toContain("test@example.com"); + expect(result?.output).toContain("(no org)"); + expect(result?.output).toContain("Configuration:"); + expect(result?.output).toContain("/custom/config.yaml"); + expect(result?.exit).toBe(false); + }); + + it("should handle config service errors gracefully", async () => { + const { isAuthenticated } = await import("./auth/workos.js"); + const { services } = await import("./services/index.js"); + + ( + isAuthenticated as MockedFunction + ).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockImplementation(() => { + throw new Error("Service not ready"); + }); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result).toBeDefined(); + expect(result?.output).toContain("Configuration service not available"); + }); + + it("should use test session directory when in test mode", async () => { + const { isAuthenticated } = await import("./auth/workos.js"); + const { services } = await import("./services/index.js"); + const { getSessionFilePath } = await import("./session.js"); + + // Mock the session path for this specific test + (getSessionFilePath as any).mockReturnValue( + "/test-home/.continue/cli-sessions/continue-cli-test-123.json", ); - // Verify auth service login was called - expect(services.auth.login).toHaveBeenCalledTimes(1); + ( + isAuthenticated as MockedFunction + ).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ + config: null, + configPath: undefined, + } as ConfigServiceState); - // Verify automatic cascade reload was triggered - only auth service reload needed - expect(reloadService).toHaveBeenCalledTimes(1); - expect(reloadService).toHaveBeenCalledWith(SERVICE_NAMES.AUTH); + const result = await handleSlashCommands("/info", mockAssistant); - // Verify manual service reloads are NOT called - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.API_CLIENT); - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.CONFIG); - }); - - test.skip("login failure should not trigger any reloads", async () => { - const loginError = new Error("Login failed"); - (services.auth.login as any).mockRejectedValue(loginError); - - const result = await handleSlashCommands("/login", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.output).toContain("Login failed: Login failed"); - - // Verify NO reload was triggered on failure - expect(reloadService).not.toHaveBeenCalled(); - }); - }); - - describe("Other Commands (unchanged behavior)", () => { - test("help command should work normally", async () => { - const result = await handleSlashCommands("/help", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.output).toContain("Slash commands:"); - expect(result?.output).toContain("/help: Show help"); - expect(result?.output).toContain("/login: Authenticate"); - }); - - test.skip("logout command should exit", async () => { - const logoutState: AuthServiceState = { - authConfig: null, - isAuthenticated: false, - }; - (services.auth.logout as any).mockResolvedValue(logoutState); - - const result = await handleSlashCommands("/logout", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.exit).toBe(true); - expect(result?.output).toContain("Logged out successfully"); - }); - - test("clear command should work normally", async () => { - const result = await handleSlashCommands("/clear", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.clear).toBe(true); - expect(result?.output).toBe("Chat history cleared"); - }); - - test("compact command should work normally", async () => { - const result = await handleSlashCommands("/compact", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.compact).toBe(true); - }); - - test("resume command should open session selector", async () => { - const result = await handleSlashCommands("/resume", mockAssistant); - - expect(result).not.toBeNull(); - expect(result?.openSessionSelector).toBe(true); - }); - - test("non-slash input should return null", async () => { - const result = await handleSlashCommands("regular input", mockAssistant); - expect(result).toBeNull(); - }); - - test("unknown slash command should return null", async () => { - const result = await handleSlashCommands("/unknown", mockAssistant); - - expect(result).toBeNull(); + expect(result?.output).toContain("/test-home/.continue/cli-sessions/"); + expect(result?.output).toContain(".json"); }); }); }); diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index c88d8f13f..dc24c30bc 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -8,6 +8,7 @@ import { } from "./auth/workos.js"; import { getAllSlashCommands } from "./commands/commands.js"; import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; +import { getSessionFilePath } from "./session.js"; import { posthogService } from "./telemetry/posthogService.js"; import { SlashCommandResult } from "./ui/hooks/useChat.types.js"; @@ -96,6 +97,63 @@ function handleWhoami() { } } +async function handleInfo() { + posthogService.capture("useSlashCommand", { name: "info" }); + + const infoLines = []; + + // Auth info + if (isAuthenticated()) { + const config = loadAuthConfig(); + if (config && isAuthenticatedConfig(config)) { + const email = config.userEmail || config.userId; + const org = "(no org)"; // Organization info not available in AuthenticatedConfig + infoLines.push(chalk.white("Authentication:")); + infoLines.push(` Email: ${chalk.green(email)}`); + infoLines.push(` Organization: ${chalk.cyan(org)}`); + } else { + infoLines.push(chalk.white("Authentication:")); + infoLines.push( + ` ${chalk.yellow("Authenticated via environment variable")}`, + ); + } + } else { + infoLines.push(chalk.white("Authentication:")); + infoLines.push(` ${chalk.red("Not logged in")}`); + } + + // Config info + try { + const configState = services.config.getState(); + infoLines.push(""); + infoLines.push(chalk.white("Configuration:")); + if (configState.config) { + infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`); + } else { + infoLines.push(` ${chalk.red(`Config not found`)}`); + } + if (configState.configPath) { + infoLines.push(` Path: ${chalk.blue(configState.configPath)}`); + } + } catch { + infoLines.push(""); + infoLines.push(chalk.white("Configuration:")); + infoLines.push(` ${chalk.red("Configuration service not available")}`); + } + + // Session history path + infoLines.push(""); + infoLines.push(chalk.white("Session History:")); + const sessionFilePath = getSessionFilePath(); + + infoLines.push(` File: ${chalk.blue(sessionFilePath)}`); + + return { + exit: false, + output: infoLines.join("\n"), + }; +} + const commandHandlers: Record = { help: handleHelp, clear: () => { @@ -113,6 +171,7 @@ const commandHandlers: Record = { login: handleLogin, logout: handleLogout, whoami: handleWhoami, + info: handleInfo, model: () => ({ openModelSelector: true }), compact: () => { posthogService.capture("useSlashCommand", { name: "compact" }); diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/streamChatResponse.autoCompaction.test.ts new file mode 100644 index 000000000..bfc9daae6 --- /dev/null +++ b/extensions/cli/src/streamChatResponse.autoCompaction.test.ts @@ -0,0 +1,225 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; + +// Mock dependencies +vi.mock("./compaction.js", () => ({ + compactChatHistory: vi.fn(), +})); + +vi.mock("./session.js", () => ({ + saveSession: vi.fn(), +})); + +vi.mock("./util/tokenizer.js", () => ({ + shouldAutoCompact: vi.fn(), + getAutoCompactMessage: vi.fn(), +})); + +vi.mock("./util/formatError.js", () => ({ + formatError: vi.fn((error) => error.message || String(error)), +})); + +vi.mock("./util/logger.js", () => ({ + logger: { + info: vi.fn(), + debug: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +describe("handleAutoCompaction", () => { + const mockModel = { + provider: "openai", + name: "gpt-4", + model: "gpt-4", + defaultCompletionOptions: { + contextLength: 8192, + maxTokens: 2048, + }, + } as any; + + const mockLlmApi = {} as any; + const mockChatHistory: ChatCompletionMessageParam[] = [ + { role: "system", content: "You are a helpful assistant." }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there!" }, + ]; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("should return original history when auto-compaction is not needed", async () => { + const { shouldAutoCompact } = await import("./util/tokenizer.js"); + vi.mocked(shouldAutoCompact).mockReturnValue(false); + + const result = await handleAutoCompaction( + mockChatHistory, + mockModel, + mockLlmApi, + {}, + ); + + expect(result).toEqual({ + chatHistory: mockChatHistory, + compactionIndex: null, + }); + + expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel); + }); + + it("should perform auto-compaction when context limit is approaching", async () => { + const { shouldAutoCompact, getAutoCompactMessage } = await import( + "./util/tokenizer.js" + ); + const { compactChatHistory } = await import("./compaction.js"); + const { saveSession } = await import("./session.js"); + + vi.mocked(shouldAutoCompact).mockReturnValue(true); + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); + + const mockCompactionResult = { + compactedHistory: [ + { + role: "system", + content: "You are a helpful assistant.", + } as ChatCompletionMessageParam, + { + role: "assistant", + content: "[COMPACTED HISTORY]\nConversation summary...", + } as ChatCompletionMessageParam, + ], + compactionIndex: 1, + compactionContent: "Conversation summary...", + }; + + vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult); + + const mockCallbacks = { + onSystemMessage: vi.fn(), + }; + + const result = await handleAutoCompaction( + mockChatHistory, + mockModel, + mockLlmApi, + { + isHeadless: false, + callbacks: mockCallbacks, + }, + ); + + expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel); + expect(getAutoCompactMessage).toHaveBeenCalledWith(mockModel); + expect(compactChatHistory).toHaveBeenCalledWith( + mockChatHistory, + mockModel, + mockLlmApi, + expect.any(Object), + ); + expect(saveSession).toHaveBeenCalledWith( + mockCompactionResult.compactedHistory, + ); + + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( + "Auto-compacting...", + ); + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( + "✓ Chat history auto-compacted successfully.", + ); + + expect(result).toEqual({ + chatHistory: mockCompactionResult.compactedHistory, + compactionIndex: mockCompactionResult.compactionIndex, + }); + }); + + it("should handle compaction errors gracefully", async () => { + const { shouldAutoCompact, getAutoCompactMessage } = await import( + "./util/tokenizer.js" + ); + const { compactChatHistory } = await import("./compaction.js"); + const { logger } = await import("./util/logger.js"); + + vi.mocked(shouldAutoCompact).mockReturnValue(true); + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); + vi.mocked(compactChatHistory).mockRejectedValue( + new Error("Compaction failed"), + ); + + const mockCallbacks = { + onSystemMessage: vi.fn(), + }; + + const result = await handleAutoCompaction( + mockChatHistory, + mockModel, + mockLlmApi, + { + isHeadless: false, + callbacks: mockCallbacks, + }, + ); + + expect(logger.error).toHaveBeenCalledWith( + expect.stringContaining("Auto-compaction error"), + ); + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( + expect.stringContaining("Warning: Auto-compaction error"), + ); + + // Should return original history on error + expect(result).toEqual({ + chatHistory: mockChatHistory, + compactionIndex: null, + }); + }); + + it("should not call system message callback in headless mode", async () => { + const { shouldAutoCompact, getAutoCompactMessage } = await import( + "./util/tokenizer.js" + ); + const { compactChatHistory } = await import("./compaction.js"); + + vi.mocked(shouldAutoCompact).mockReturnValue(true); + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); + + const mockCompactionResult = { + compactedHistory: [ + { role: "system", content: "System" } as ChatCompletionMessageParam, + ], + compactionIndex: 0, + compactionContent: "Summary", + }; + + vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult); + + const mockCallbacks = { + onSystemMessage: vi.fn(), + }; + + await handleAutoCompaction(mockChatHistory, mockModel, mockLlmApi, { + isHeadless: true, + callbacks: mockCallbacks, + }); + + expect(mockCallbacks.onSystemMessage).not.toHaveBeenCalled(); + }); + + it("should handle missing model gracefully", async () => { + const result = await handleAutoCompaction( + mockChatHistory, + null as any, + mockLlmApi, + {}, + ); + + expect(result).toEqual({ + chatHistory: mockChatHistory, + compactionIndex: null, + }); + }); +}); diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.ts b/extensions/cli/src/streamChatResponse.autoCompaction.ts new file mode 100644 index 000000000..ee9336250 --- /dev/null +++ b/extensions/cli/src/streamChatResponse.autoCompaction.ts @@ -0,0 +1,180 @@ +import { ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import type { ChatCompletionMessageParam } from "openai/resources.mjs"; +import React from "react"; + +import { compactChatHistory } from "./compaction.js"; +import { saveSession } from "./session.js"; +import { DisplayMessage } from "./ui/types.js"; +import { formatError } from "./util/formatError.js"; +import { logger } from "./util/logger.js"; +import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js"; + +interface AutoCompactionCallbacks { + // For streaming mode + onSystemMessage?: (message: string) => void; + onContent?: (content: string) => void; + + // For TUI mode + setMessages?: React.Dispatch>; + setChatHistory?: React.Dispatch< + React.SetStateAction + >; + setCompactionIndex?: React.Dispatch>; + + // For headless mode - no callbacks needed, just return values +} + +interface AutoCompactionOptions { + isHeadless?: boolean; + format?: "json"; + callbacks?: AutoCompactionCallbacks; +} + +/** + * Notify user about compaction start + */ +function notifyCompactionStart( + message: string, + isHeadless: boolean, + callbacks?: AutoCompactionCallbacks, +) { + if (isHeadless) return; + + if (callbacks?.onSystemMessage) { + callbacks.onSystemMessage(message); + } else if (callbacks?.setMessages) { + callbacks.setMessages((prev) => [ + ...prev, + { + role: "system", + content: message, + messageType: "system" as const, + }, + ]); + } +} + +/** + * Handle successful compaction state updates + */ +function handleCompactionSuccess( + result: any, + isHeadless: boolean, + callbacks?: AutoCompactionCallbacks, +) { + if (isHeadless) return; + + const successMessage = "✓ Chat history auto-compacted successfully."; + + if (callbacks?.onSystemMessage) { + callbacks.onSystemMessage(successMessage); + } else if ( + callbacks?.setMessages && + callbacks?.setChatHistory && + callbacks?.setCompactionIndex + ) { + callbacks.setChatHistory(result.compactedHistory); + callbacks.setCompactionIndex(result.compactionIndex); + callbacks.setMessages((prev) => [ + ...prev, + { + role: "system", + content: successMessage, + messageType: "system" as const, + }, + ]); + } +} + +/** + * Handle compaction error notification + */ +function handleCompactionError( + error: any, + isHeadless: boolean, + callbacks?: AutoCompactionCallbacks, +) { + const errorMessage = `Auto-compaction error: ${formatError(error)}`; + logger.error(errorMessage); + + if (isHeadless) return; + + const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`; + + if (callbacks?.onSystemMessage) { + callbacks.onSystemMessage(warningMessage); + } else if (callbacks?.setMessages) { + callbacks.setMessages((prev) => [ + ...prev, + { + role: "system", + content: warningMessage, + messageType: "system" as const, + }, + ]); + } +} + +/** + * Unified auto-compaction handler for all modes (streaming, TUI, headless) + * @param chatHistory Current chat history + * @param model Model configuration + * @param llmApi LLM API instance + * @param options Configuration options for different usage contexts + * @returns Updated chat history and compaction index, or original if no compaction needed + */ +export async function handleAutoCompaction( + chatHistory: ChatCompletionMessageParam[], + model: ModelConfig, + llmApi: BaseLlmApi, + options: AutoCompactionOptions = {}, +): Promise<{ + chatHistory: ChatCompletionMessageParam[]; + compactionIndex: number | null; +}> { + const { isHeadless = false, callbacks } = options; + + if (!model || !shouldAutoCompact(chatHistory, model)) { + return { chatHistory, compactionIndex: null }; + } + + logger.info( + `Auto-compaction triggered${isHeadless ? " in headless mode" : ""}`, + ); + + // Notify about compaction start + notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks); + + try { + // Compact the history + const result = await compactChatHistory( + chatHistory, + model, + llmApi, + isHeadless + ? undefined + : { + onStreamContent: callbacks?.onContent, + onStreamComplete: () => {}, + }, + ); + + // Save the compacted session + saveSession(result.compactedHistory); + + // Handle success notification + handleCompactionSuccess(result, isHeadless, callbacks); + + return { + chatHistory: result.compactedHistory, + compactionIndex: result.compactionIndex, + }; + } catch (error: any) { + // Handle error notification + handleCompactionError(error, isHeadless, callbacks); + + // Continue without compaction on error + return { chatHistory, compactionIndex: null }; + } +} diff --git a/extensions/cli/src/streamChatResponse.ts b/extensions/cli/src/streamChatResponse.ts index fd8cf4b96..ab9d0c507 100644 --- a/extensions/cli/src/streamChatResponse.ts +++ b/extensions/cli/src/streamChatResponse.ts @@ -15,6 +15,7 @@ import { SERVICE_NAMES, } from "./services/index.js"; import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; +import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; import { executeStreamedToolCalls, preprocessStreamedToolCalls, @@ -513,6 +514,24 @@ export async function streamChatResponse( return finalResponse || content || fullResponse; } + // Check for auto-compaction after tool execution + if (shouldContinue) { + const { chatHistory: updatedChatHistory, compactionIndex } = + await handleAutoCompaction(chatHistory, model, llmApi, { + isHeadless, + callbacks: { + onSystemMessage: callbacks?.onSystemMessage, + onContent: callbacks?.onContent, + }, + }); + + // Only update chat history if compaction actually occurred + if (compactionIndex !== null && updatedChatHistory !== chatHistory) { + chatHistory.length = 0; + chatHistory.push(...updatedChatHistory); + } + } + // Check if we should continue if (!shouldContinue) { break; diff --git a/extensions/cli/src/streamChatResponse.types.ts b/extensions/cli/src/streamChatResponse.types.ts index 6519e0e48..ff273872a 100644 --- a/extensions/cli/src/streamChatResponse.types.ts +++ b/extensions/cli/src/streamChatResponse.types.ts @@ -15,6 +15,7 @@ export interface StreamCallbacks { requestId: string, preview?: ToolCallPreview[], ) => void; + onSystemMessage?: (message: string) => void; } export function getDefaultCompletionOptions( diff --git a/extensions/cli/src/test-helpers/ui-test-context.ts b/extensions/cli/src/test-helpers/ui-test-context.ts index 5eeda611d..a8eae59f3 100644 --- a/extensions/cli/src/test-helpers/ui-test-context.ts +++ b/extensions/cli/src/test-helpers/ui-test-context.ts @@ -72,7 +72,7 @@ export function createUITestContext( responseStartTime: null, inputMode: true, attachedFiles: [], - handleUserMessage: vi.fn(), + handleUserMessage: vi.fn().mockResolvedValue(undefined), handleInterrupt: vi.fn(), handleFileAttached: vi.fn(), resetChatHistory: vi.fn(), diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index f7258a3bf..80a6bbe62 100644 --- a/extensions/cli/src/tools/readFile.ts +++ b/extensions/cli/src/tools/readFile.ts @@ -39,6 +39,13 @@ export const readFileTool: Tool = { const content = fs.readFileSync(args.filepath, "utf-8"); // Mark this file as read for the edit tool markFileAsRead(args.filepath); + + const lines = content.split("\n"); + if (lines.length > 5000) { + const truncatedContent = lines.slice(0, 5000).join("\n"); + return `Content of ${args.filepath} (truncated to first 5000 lines of ${lines.length} total):\n${truncatedContent}`; + } + return `Content of ${args.filepath}:\n${content}`; } catch (error) { return `Error reading file: ${ diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 9649fac02..b8d77e028 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -7,7 +7,6 @@ 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"; @@ -278,13 +277,13 @@ interface HandleAutoCompactionOptions { } /** - * Handle auto-compaction when approaching context limit + * Handle auto-compaction when approaching context limit - TUI wrapper */ export async function handleAutoCompaction({ chatHistory, model, llmApi, - compactionIndex, + compactionIndex: _compactionIndex, setMessages, setChatHistory, setCompactionIndex, @@ -292,69 +291,21 @@ export async function handleAutoCompaction({ currentChatHistory: ChatCompletionMessageParam[]; currentCompactionIndex: number | null; }> { - if (!model || !shouldAutoCompact(chatHistory, model)) { - return { - currentChatHistory: chatHistory, - currentCompactionIndex: compactionIndex, - }; - } + const { handleAutoCompaction: coreAutoCompaction } = await import( + "../../streamChatResponse.autoCompaction.js" + ); - 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, + const result = await coreAutoCompaction(chatHistory, model, llmApi, { + isHeadless: false, + callbacks: { + setMessages, + setChatHistory, + setCompactionIndex, }, - ]); + }); - 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, - }; - } + return { + currentChatHistory: result.chatHistory, + currentCompactionIndex: result.compactionIndex, + }; } diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 810e849e5..d88177811 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -111,6 +111,16 @@ export function createStreamCallbacks( toolCallPreview, }); }, + onSystemMessage: (message: string) => { + setMessages((prev) => [ + ...prev, + { + role: "system", + content: message, + messageType: "system" as const, + }, + ]); + }, }; } diff --git a/extensions/cli/src/util/tokenizer.test.ts b/extensions/cli/src/util/tokenizer.test.ts new file mode 100644 index 000000000..97ed9418a --- /dev/null +++ b/extensions/cli/src/util/tokenizer.test.ts @@ -0,0 +1,292 @@ +import { ModelConfig } from "@continuedev/config-yaml"; +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { logger } from "./logger.js"; +import { + AUTO_COMPACT_THRESHOLD, + calculateContextUsagePercentage, + countChatHistoryTokens, + countMessageTokens, + getModelContextLimit, + shouldAutoCompact, +} from "./tokenizer.js"; + +// Mock the logger +vi.mock("./logger.js", () => ({ + logger: { + debug: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); + +// Mock gpt-tokenizer +vi.mock("gpt-tokenizer", () => ({ + encode: (text: string) => new Array(Math.ceil(text.length / 4)), // Rough 4 chars per token +})); + +describe("tokenizer", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("getModelContextLimit", () => { + it("should return contextLength from model config", () => { + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + defaultCompletionOptions: { + contextLength: 8192, + }, + }; + + expect(getModelContextLimit(model)).toBe(8192); + }); + + it("should return default when no contextLength specified", () => { + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + }; + + expect(getModelContextLimit(model)).toBe(200_000); + }); + }); + + describe("countMessageTokens", () => { + it("should count tokens for string content", () => { + const message: ChatCompletionMessageParam = { + role: "user", + content: "Hello world", // 11 chars -> ~3 tokens + 2 for role = 5 + }; + + const tokenCount = countMessageTokens(message); + expect(tokenCount).toBeGreaterThan(0); + expect(tokenCount).toBe(5); // 3 content tokens + 2 role tokens + }); + + it("should count tokens for array content", () => { + const message: ChatCompletionMessageParam = { + role: "user", + content: [ + { type: "text", text: "Hello" }, // 5 chars -> ~2 tokens + { type: "image_url", image_url: { url: "test.jpg" } }, // +85 tokens + ], + }; + + const tokenCount = countMessageTokens(message); + expect(tokenCount).toBe(89); // 2 + 85 + 2 role tokens + }); + + it("should count tokens for tool calls", () => { + const message: ChatCompletionMessageParam = { + role: "assistant", + content: "I'll help you", + tool_calls: [ + { + id: "call_1", + type: "function", + function: { + name: "test_function", // ~3 tokens + 10 overhead + arguments: '{"param": "value"}', // ~5 tokens + }, + }, + ], + }; + + const tokenCount = countMessageTokens(message); + expect(tokenCount).toBeGreaterThan(20); + }); + + it("should handle errors gracefully", () => { + // We'll skip this test for now since mocking gpt-tokenizer is complex + // The error handling is tested implicitly by the fallback behavior + expect(true).toBe(true); + }); + }); + + describe("countChatHistoryTokens", () => { + it("should count tokens for multiple messages", () => { + const chatHistory: ChatCompletionMessageParam[] = [ + { role: "system", content: "You are helpful" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]; + + const tokenCount = countChatHistoryTokens(chatHistory); + expect(tokenCount).toBeGreaterThan(0); + // Should include message overhead (3 * 3 = 9 tokens) + expect(tokenCount).toBeGreaterThan(9); + }); + + it("should handle empty chat history", () => { + const tokenCount = countChatHistoryTokens([]); + expect(tokenCount).toBe(0); + }); + }); + + describe("calculateContextUsagePercentage", () => { + it("should calculate percentage correctly", () => { + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + defaultCompletionOptions: { + contextLength: 1000, + }, + }; + + expect(calculateContextUsagePercentage(800, model)).toBe(80); + expect(calculateContextUsagePercentage(500, model)).toBe(50); + expect(calculateContextUsagePercentage(1200, model)).toBe(100); // Capped at 100% + }); + }); + + describe("shouldAutoCompact", () => { + const createModel = ( + contextLength: number, + maxTokens?: number, + ): ModelConfig => ({ + name: "test-model", + model: "test", + provider: "openai", + defaultCompletionOptions: { + contextLength, + maxTokens, + }, + }); + + const createChatHistory = ( + tokenCount: number, + ): ChatCompletionMessageParam[] => { + // Create a message that will result in approximately the desired token count + const content = "x".repeat(tokenCount * 4); // 4 chars per token + return [{ role: "user", content }]; + }; + + it("should compact when input tokens exceed threshold with maxTokens", () => { + const model = createModel(1000, 200); // 1000 context, 200 max output + // Available for input: 1000 - 200 = 800 + // Threshold: 800 * 0.8 = 640 + const chatHistory = createChatHistory(650); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + it("should not compact when input tokens are below threshold with maxTokens", () => { + const model = createModel(1000, 200); // 1000 context, 200 max output + // Available for input: 1000 - 200 = 800 + // Threshold: 800 * 0.8 = 640 + const chatHistory = createChatHistory(600); // Below threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(false); + }); + + it("should use 35% default reservation when maxTokens is not set", () => { + const model = createModel(1000); // No maxTokens + // Reserved: 1000 * 0.35 = 350 + // Available for input: 1000 - 350 = 650 + // Threshold: 650 * 0.8 = 520 + const chatHistory = createChatHistory(530); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + it("should not compact when below default threshold without maxTokens", () => { + const model = createModel(1000); // No maxTokens + // Available for input: 1000 - 350 = 650 + // Threshold: 650 * 0.8 = 520 + const chatHistory = createChatHistory(500); // Below threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(false); + }); + + it("should throw error when maxTokens >= contextLength", () => { + const model = createModel(1000, 1000); // maxTokens equals contextLength + const chatHistory = createChatHistory(1); // Minimal input + + expect(() => shouldAutoCompact(chatHistory, model)).toThrow( + "max_tokens is larger than context_length, which should not be possible. Please check your configuration.", + ); + }); + + it("should throw error when maxTokens > contextLength", () => { + const model = createModel(1000, 1200); // maxTokens exceeds contextLength + const chatHistory = createChatHistory(1); // Minimal input + + expect(() => shouldAutoCompact(chatHistory, model)).toThrow( + "max_tokens is larger than context_length, which should not be possible. Please check your configuration.", + ); + }); + + it("should handle edge case with very small context limit", () => { + const model = createModel(100, 50); // Small context + // Available: 100 - 50 = 50 + // Threshold: 50 * 0.8 = 40 + const chatHistory = createChatHistory(45); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + it("should log debug information correctly", () => { + const model = createModel(1000, 200); + const chatHistory = createChatHistory(600); + + shouldAutoCompact(chatHistory, model); + + expect(logger.debug).toHaveBeenCalledWith("Context usage check", { + inputTokens: expect.any(Number), + contextLimit: 1000, + maxTokens: 200, + reservedForOutput: 200, + availableForInput: 800, + usage: expect.any(String), + threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`, + shouldCompact: expect.any(Boolean), + }); + }); + + it("should handle model with zero maxTokens correctly", () => { + const model = createModel(1000, 0); // Explicit zero + // Should use default 35% reservation: 1000 * 0.35 = 350 + const chatHistory = createChatHistory(530); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + describe("real-world scenarios", () => { + it("should prevent Claude 3.5 Sonnet context overflow", () => { + // Claude 3.5 Sonnet: 200k context, often uses 4k max_tokens + const model = createModel(200_000, 4_000); + // Available: 200k - 4k = 196k + // Threshold: 196k * 0.8 = 156.8k + const chatHistory = createChatHistory(160_000); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + it("should prevent GPT-4 context overflow", () => { + // GPT-4: 128k context, often uses 4k max_tokens + const model = createModel(128_000, 4_000); + // Available: 128k - 4k = 124k + // Threshold: 124k * 0.8 = 99.2k + const chatHistory = createChatHistory(100_000); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + + it("should handle models with very high max_tokens", () => { + // Some models allow very high max_tokens (e.g., 64k like in the error message) + const model = createModel(200_000, 64_000); + // Available: 200k - 64k = 136k + // Threshold: 136k * 0.8 = 108.8k + const chatHistory = createChatHistory(110_000); // Above threshold + + expect(shouldAutoCompact(chatHistory, model)).toBe(true); + }); + }); + }); +}); diff --git a/extensions/cli/src/util/tokenizer.ts b/extensions/cli/src/util/tokenizer.ts index 7dc53e809..5bf0117a4 100644 --- a/extensions/cli/src/util/tokenizer.ts +++ b/extensions/cli/src/util/tokenizer.ts @@ -117,20 +117,39 @@ export function calculateContextUsagePercentage( /** * Check if the chat history exceeds the auto-compact threshold * @param chatHistory The chat history to check - * @param modelName The model name + * @param model The model configuration * @returns Whether auto-compacting should be triggered */ export function shouldAutoCompact( chatHistory: ChatCompletionMessageParam[], model: ModelConfig, ): boolean { - const tokenCount = countChatHistoryTokens(chatHistory); - const limit = getModelContextLimit(model); - const usage = tokenCount / limit; + const inputTokens = countChatHistoryTokens(chatHistory); + const contextLimit = getModelContextLimit(model); + const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; + + // Calculate available space considering max_tokens reservation + // If maxTokens is not set, reserve 35% of context for output as a safe default + // (64k/200k with claude = 32%, round up to give a buffer) + const reservedForOutput = + maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); + const availableForInput = contextLimit - reservedForOutput; + + // Ensure we have positive space available for input + if (availableForInput <= 0) { + throw new Error( + `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`, + ); + } + + const usage = inputTokens / availableForInput; logger.debug("Context usage check", { - tokenCount, - limit, + inputTokens, + contextLimit, + maxTokens, + reservedForOutput, + availableForInput, usage: `${Math.round(usage * 100)}%`, threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`, shouldCompact: usage >= AUTO_COMPACT_THRESHOLD, @@ -138,3 +157,13 @@ export function shouldAutoCompact( return usage >= AUTO_COMPACT_THRESHOLD; } + +/** + * Get a descriptive message for auto-compaction that shows the context limit + * @param model The model configuration + * @returns A descriptive message explaining why compaction is needed + */ +export function getAutoCompactMessage(model: ModelConfig): string { + const limit = getModelContextLimit(model); + return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`; +} diff --git a/extensions/cli/validate-aliases.mjs b/extensions/cli/validate-aliases.mjs index df3f696e9..2f714a9dd 100755 --- a/extensions/cli/validate-aliases.mjs +++ b/extensions/cli/validate-aliases.mjs @@ -42,10 +42,14 @@ function getDefinedAliases() { } // Look for package names in non-commented lines - // Match both @continuedev/* packages and simple package names like "core" - const packageMatch = line.match(/"(@continuedev\/[^"]+|[^"@\/]+)":/); - if (packageMatch) { - aliases.add(packageMatch[1]); + // Match both quoted and unquoted keys + const quotedMatch = line.match(/"([^"]+)":/); + const unquotedMatch = line.match(/\s+([a-zA-Z@][a-zA-Z0-9@\/_-]*)\s*:/); + + if (quotedMatch) { + aliases.add(quotedMatch[1]); + } else if (unquotedMatch && !unquotedMatch[1].includes('__dirname') && unquotedMatch[1] !== 'js') { + aliases.add(unquotedMatch[1]); } }