From f3d604bdd80850f6b16346fb784a90858f880f47 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Aug 2025 12:53:07 -0700 Subject: [PATCH 01/38] fix: redirect agents -> assistants --- docs/docs.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/docs.json b/docs/docs.json index 369944933..daa2b037c 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -364,6 +364,10 @@ "source": "/hub/blocks", "destination": "/hub/blocks/intro" }, + { + "source": "/hub/agents/intro", + "destination": "/hub/assistants/intro" + }, { "source": "/customize", "destination": "/customization/overview" From 6b79cb4512f20d5690f8b44e1afd2e41da9968f7 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Aug 2025 22:00:11 -0700 Subject: [PATCH 02/38] feat: update agent and plan instructions to include brief apply formatting instructions --- core/llm/defaultSystemMessages.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index eebcc8510..c8f0997aa 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -46,6 +46,8 @@ export const EDIT_CODE_INSTRUCTIONS = `\ of changes unless the user specifically asks for code only. `; +const BRIEF_LAZY_INSTRUCTIONS = `For larger codeblocks, use brief language-appropriate placeholders for unmodified sections, e.g. '// ... existing code ...'";`; + export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ You are in chat mode. @@ -64,6 +66,11 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ If you need to use multiple tools, you can call multiple read only tools simultaneously. ${CODEBLOCK_FORMATTING_INSTRUCTIONS} + +${BRIEF_LAZY_INSTRUCTIONS} + +However, only output codeblocks for suggestion and planning purposes. For making changes, use the edit tools + `; // The note about read-only tools is for MCP servers @@ -75,7 +82,10 @@ export const DEFAULT_PLAN_SYSTEM_MESSAGE = `\ If the user wants to make changes, offer that they can switch to Agent mode to give you access to write tools to make the suggested updates. ${CODEBLOCK_FORMATTING_INSTRUCTIONS} -${EDIT_CODE_INSTRUCTIONS} + +${BRIEF_LAZY_INSTRUCTIONS} + +However, only output codeblocks for suggestion and planning purposes. For making changes, request to switch to Agent mode. In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan. `; From 9e0a7d2df0c4e3646ba61c64b5066097b101ac5d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Aug 2025 22:00:25 -0700 Subject: [PATCH 03/38] fix: system message copy --- core/llm/defaultSystemMessages.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index c8f0997aa..e43fdd06a 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -69,7 +69,7 @@ ${CODEBLOCK_FORMATTING_INSTRUCTIONS} ${BRIEF_LAZY_INSTRUCTIONS} -However, only output codeblocks for suggestion and planning purposes. For making changes, use the edit tools +However, only output codeblocks for suggestion and demonstration purposes. For making changes, use the edit tools `; From 3fe9031db72a365ef4e0c59733bfbc7e4c26b426 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Aug 2025 22:04:38 -0700 Subject: [PATCH 04/38] fix: tweak prompt --- core/llm/defaultSystemMessages.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index e43fdd06a..394dfbcc7 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -69,7 +69,7 @@ ${CODEBLOCK_FORMATTING_INSTRUCTIONS} ${BRIEF_LAZY_INSTRUCTIONS} -However, only output codeblocks for suggestion and demonstration purposes. For making changes, use the edit tools +However, only output codeblocks for suggestion and demonstration purposes. For examle, when enumerating multiple hypothetical options, output codeblocks rather than using the tool. But for making any actual changes, use the edit tools. `; From d8c2247713c788de4bae9f9bc6b9adcc209c7f87 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Aug 2025 22:22:36 -0700 Subject: [PATCH 05/38] fix: make current file tool a bit more happy --- core/tools/definitions/readCurrentlyOpenFile.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index e05241611..6a7e3010e 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -13,7 +13,7 @@ export const readCurrentlyOpenFileTool: Tool = { function: { name: BuiltInToolNames.ReadCurrentlyOpenFile, description: - "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, try using this", + "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, or is requestion an action on content that seems missing, try using this tool.", parameters: { type: "object", properties: {}, From dc3e2136a01e5bf98e45f23e34158b936dd05eb2 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 19 Aug 2025 22:26:34 -0700 Subject: [PATCH 06/38] fix: copy errors --- core/llm/defaultSystemMessages.ts | 6 +++--- core/tools/definitions/readCurrentlyOpenFile.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index 394dfbcc7..9d79966b9 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -46,7 +46,7 @@ export const EDIT_CODE_INSTRUCTIONS = `\ of changes unless the user specifically asks for code only. `; -const BRIEF_LAZY_INSTRUCTIONS = `For larger codeblocks, use brief language-appropriate placeholders for unmodified sections, e.g. '// ... existing code ...'";`; +const BRIEF_LAZY_INSTRUCTIONS = `For larger codeblocks (>20 lines), use brief language-appropriate placeholders for unmodified sections, e.g. '// ... existing code ...'`; export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ @@ -69,7 +69,7 @@ ${CODEBLOCK_FORMATTING_INSTRUCTIONS} ${BRIEF_LAZY_INSTRUCTIONS} -However, only output codeblocks for suggestion and demonstration purposes. For examle, when enumerating multiple hypothetical options, output codeblocks rather than using the tool. But for making any actual changes, use the edit tools. +However, only output codeblocks for suggestion and demonstration purposes, for examle, when enumerating multiple hypothetical options. For implementing changes, use the edit tools. `; @@ -85,7 +85,7 @@ ${CODEBLOCK_FORMATTING_INSTRUCTIONS} ${BRIEF_LAZY_INSTRUCTIONS} -However, only output codeblocks for suggestion and planning purposes. For making changes, request to switch to Agent mode. +However, only output codeblocks for suggestion and planning purposes. When ready to implement changes, request to switch to Agent mode. In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan. `; diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index 6a7e3010e..da1cb129b 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -13,7 +13,7 @@ export const readCurrentlyOpenFileTool: Tool = { function: { name: BuiltInToolNames.ReadCurrentlyOpenFile, description: - "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, or is requestion an action on content that seems missing, try using this tool.", + "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, or is requesting an action on content that seems missing, try using this tool.", parameters: { type: "object", properties: {}, From 69463a268a88639c3839d389fef6dac73d5dbf3f Mon Sep 17 00:00:00 2001 From: Pyroboomka Date: Thu, 21 Aug 2025 12:41:36 +0300 Subject: [PATCH 07/38] Respect "useReranking" field --- core/context/retrieval/retrieval.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 4f29d2ef8..022e5abf0 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -37,7 +37,7 @@ export async function retrieveContextItemsFromEmbeddings( const nFinal = options?.nFinal ?? Math.min(DEFAULT_N_FINAL, contextLength / tokensPerSnippet / 2); - const useReranking = !!extras.reranker; + const useReranking = options?.useReranking ?? !!extras.reranker; const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal; const branches = (await Promise.race([ From bb28da60125ed33d03d5781b976ea9c2806f628d Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Thu, 21 Aug 2025 11:43:50 -0700 Subject: [PATCH 08/38] Update cli-pr-checks.yml --- .github/workflows/cli-pr-checks.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/cli-pr-checks.yml b/.github/workflows/cli-pr-checks.yml index 0284cae4b..43995eb76 100644 --- a/.github/workflows/cli-pr-checks.yml +++ b/.github/workflows/cli-pr-checks.yml @@ -3,8 +3,6 @@ name: CLI PR Checks on: pull_request: branches: [main] - paths: - - "extensions/cli/**" permissions: contents: read From 66aa66da9b36a9402c540218360dd51878f84fb9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 21 Aug 2025 17:38:45 -0700 Subject: [PATCH 09/38] fix: typo --- core/llm/defaultSystemMessages.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index 9d79966b9..43ab7990e 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -69,7 +69,7 @@ ${CODEBLOCK_FORMATTING_INSTRUCTIONS} ${BRIEF_LAZY_INSTRUCTIONS} -However, only output codeblocks for suggestion and demonstration purposes, for examle, when enumerating multiple hypothetical options. For implementing changes, use the edit tools. +However, only output codeblocks for suggestion and demonstration purposes, for example, when enumerating multiple hypothetical options. For implementing changes, use the edit tools. `; From 5c37672a914b8a94bbcadf42ec595faf11099a44 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 12:26:35 -0700 Subject: [PATCH 10/38] fix: npm run start correct path --- core/package-lock.json | 1 + extensions/cli/package.json | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/core/package-lock.json b/core/package-lock.json index f6211baaf..974a50300 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -228,6 +228,7 @@ "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.14", "@types/json-schema": "^7.0.15", + "@types/node": "^24.3.0", "cross-env": "^7.0.3", "semantic-release": "^24.2.7", "ts-jest": "^29.2.3", diff --git a/extensions/cli/package.json b/extensions/cli/package.json index c825b6c6a..cd09ecc6c 100644 --- a/extensions/cli/package.json +++ b/extensions/cli/package.json @@ -15,11 +15,11 @@ "test:e2e": "vitest run --config vitest.e2e.config.ts", "test:smoke": "node smoke-test.mjs", "build:tsc": "tsc -p tsconfig.build.json", - "build:local-deps": "cd ../../packages/config-types && npm run build && cd ../config-yaml && npm run build && cd ../openai-adapters && npm run build", + "build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && cd ../extensions/cli && npm i", "build:validate": "node validate-aliases.mjs", "build:bundle": "node build.mjs", "build": "npm run build:local-deps && npm run build:validate && npm run build:bundle", - "start": "node dist/index.js", + "start": "node dist/cn.js", "dev": "tsx src/index.ts", "repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml", "repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml", From eaa8077c8991972e1af03284556601b9cb2bac58 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 12:26:42 -0700 Subject: [PATCH 11/38] fix: UI improvements --- extensions/cli/package-lock.json | 1 + extensions/cli/src/asciiArt.test.ts | 11 ++++++----- extensions/cli/src/asciiArt.ts | 16 +++++++++++++--- .../cli/src/ui/components/MemoizedMessage.tsx | 5 +++-- 4 files changed, 23 insertions(+), 10 deletions(-) diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index 1a667013a..19e1f2762 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -276,6 +276,7 @@ "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.14", "@types/json-schema": "^7.0.15", + "@types/node": "^24.3.0", "cross-env": "^7.0.3", "semantic-release": "^24.2.7", "ts-jest": "^29.2.3", diff --git a/extensions/cli/src/asciiArt.test.ts b/extensions/cli/src/asciiArt.test.ts index 9f97137d3..fe1878834 100644 --- a/extensions/cli/src/asciiArt.test.ts +++ b/extensions/cli/src/asciiArt.test.ts @@ -27,26 +27,27 @@ describe("asciiArt", () => { expect(result).toBe(CONTINUE_ASCII_ART); }); - it("should return simple text version when terminal is too narrow", () => { + it("should return CN ASCII art version when terminal is too narrow", () => { // Set process.stdout.columns to simulate narrow terminal process.stdout.columns = 60; const result = getDisplayableAsciiArt(); - expect(result).toContain("CONTINUE"); - // expect(result).toContain("v0.0.0-dev"); + expect(result).toContain("██████╗"); + expect(result).toContain("(alpha)"); expect(result).not.toBe(CONTINUE_ASCII_ART); // Should be much shorter than the full ASCII art expect(result.length).toBeLessThan(CONTINUE_ASCII_ART.length / 2); }); - it("should return simple text version when terminal is below threshold", () => { + it("should return CN ASCII art version when terminal is below threshold", () => { // Test the edge case at exactly 74 columns (below our threshold of 75) process.stdout.columns = 74; const result = getDisplayableAsciiArt(); - expect(result).toContain("CONTINUE"); + expect(result).toContain("██████╗"); + expect(result).toContain("(alpha)"); expect(result).not.toBe(CONTINUE_ASCII_ART); }); diff --git a/extensions/cli/src/asciiArt.ts b/extensions/cli/src/asciiArt.ts index 39d365388..c65f877da 100644 --- a/extensions/cli/src/asciiArt.ts +++ b/extensions/cli/src/asciiArt.ts @@ -12,7 +12,17 @@ ${mind.multiline(` ██████╗ ██████╗ ███╗ ██║ ██║ ██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║██╔══╝ ╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝███████╗ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝`)} - ${d("v" + getVersion())}`; + ${d("v" + getVersion() + " (alpha)")}`; + +// ASCII art for just "CN" (first two letters) +const CN_ASCII_ART = ` +${mind.multiline(` ██████╗███╗ ██╗ + ██╔════╝████╗ ██║ + ██║ ██╔██╗ ██║ + ██║ ██║╚██╗██║ + ╚██████╗██║ ╚████║ + ╚═════╝╚═╝ ╚═══╝`)} + ${d("v" + getVersion() + " (alpha)")}`; // Minimum terminal width required to display ASCII art properly const MIN_WIDTH_FOR_ASCII_ART = 75; @@ -28,8 +38,8 @@ export function getDisplayableAsciiArt(): string { return CONTINUE_ASCII_ART; } - // If terminal is too narrow, just show a simple version - return `\n${chalk.bold.blue("CONTINUE")} ${d("v" + getVersion())}\n`; + // If terminal is too narrow, show just "CN" ASCII art + return CN_ASCII_ART; } export const CONTINUE_LOGO_ASCII_ART = ` diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index 0e254f23a..8708afd88 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -20,7 +20,8 @@ export const MemoizedMessage = memo( case "tool-start": return ( - ○ {message.content} + {/* TODO: Change back to empty circle (○) with white color once we want to differentiate in-progress vs completed tool calls */} + ● {message.content} ); @@ -87,7 +88,7 @@ export const MemoizedMessage = memo( return ( - ● + ● {isUser ? ( {message.content} From 4306eb1cc5889f3fe7014013313593314ebcd79e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 22 Aug 2025 19:31:30 +0000 Subject: [PATCH 12/38] chore(deps): bump actions/checkout from 4 to 5 Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/beta-release.yml | 2 +- .github/workflows/cli-pr-checks.yml | 4 ++-- .github/workflows/stable-release.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml index 945735731..4c763a8c9 100644 --- a/.github/workflows/beta-release.yml +++ b/.github/workflows/beta-release.yml @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} diff --git a/.github/workflows/cli-pr-checks.yml b/.github/workflows/cli-pr-checks.yml index 7adbfd5fc..b08207074 100644 --- a/.github/workflows/cli-pr-checks.yml +++ b/.github/workflows/cli-pr-checks.yml @@ -16,7 +16,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Node.js uses: actions/setup-node@v4 @@ -52,7 +52,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Node.js ${{ matrix.node-version }} uses: actions/setup-node@v4 diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.yml index 89e56c881..b213b7481 100644 --- a/.github/workflows/stable-release.yml +++ b/.github/workflows/stable-release.yml @@ -34,7 +34,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }} From 6823cbf7ceeccf8c0e228f95adf26462311003f4 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 12:39:06 -0700 Subject: [PATCH 13/38] ci: don't run local-deps in npm run build --- extensions/cli/package.json | 2 +- extensions/cli/src/ui/components/MemoizedMessage.tsx | 4 +++- package-lock.json | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/extensions/cli/package.json b/extensions/cli/package.json index cd09ecc6c..a340d48d0 100644 --- a/extensions/cli/package.json +++ b/extensions/cli/package.json @@ -18,7 +18,7 @@ "build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && cd ../extensions/cli && npm i", "build:validate": "node validate-aliases.mjs", "build:bundle": "node build.mjs", - "build": "npm run build:local-deps && npm run build:validate && npm run build:bundle", + "build": "npm run build:validate && npm run build:bundle", "start": "node dist/cn.js", "dev": "tsx src/index.ts", "repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml", diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index 8708afd88..68c3923e4 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -21,7 +21,9 @@ export const MemoizedMessage = memo( return ( {/* TODO: Change back to empty circle (○) with white color once we want to differentiate in-progress vs completed tool calls */} - ● {message.content} + + ● {message.content} + ); diff --git a/package-lock.json b/package-lock.json index b4289d422..5a364313b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "continue", + "name": "wt-nate-4", "lockfileVersion": 3, "requires": true, "packages": { From 7a18f37a9e1bb9a7fd78bb931512104f2a895a5e Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 12:49:33 -0700 Subject: [PATCH 14/38] fix: stop dependencies from logging to stdout when in tui mode --- extensions/cli/src/commands/chat.ts | 2 +- extensions/cli/src/index.ts | 7 +- extensions/cli/src/init.ts | 128 +++++++++++++++++++++ extensions/cli/src/util/consoleOverride.ts | 115 ------------------ extensions/cli/vitest.setup.ts | 2 +- 5 files changed, 135 insertions(+), 119 deletions(-) create mode 100644 extensions/cli/src/init.ts delete mode 100644 extensions/cli/src/util/consoleOverride.ts diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 4b2638fd8..c3177a10a 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -10,6 +10,7 @@ import { getHistoryForLLM, } from "../compaction.js"; import { processCommandFlags } from "../flags/flagProcessor.js"; +import { safeStdout } from "../init.js"; import { configureLogger } from "../logger.js"; import * as logging from "../logging.js"; import { sentryService } from "../sentry.js"; @@ -22,7 +23,6 @@ import { constructSystemMessage } from "../systemMessage.js"; 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 { formatAnthropicError, formatError } from "../util/formatError.js"; import { logger } from "../util/logger.js"; import { diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index 4964c8481..cf3040968 100644 --- a/extensions/cli/src/index.ts +++ b/extensions/cli/src/index.ts @@ -1,5 +1,8 @@ #!/usr/bin/env node +// MUST be the first import - intercepts console/stdout/stderr before any dependencies load +import "./init.js"; + import { Command } from "commander"; import { chat } from "./commands/chat.js"; @@ -10,12 +13,12 @@ import { remoteTest } from "./commands/remote-test.js"; import { remote } from "./commands/remote.js"; import { serve } from "./commands/serve.js"; import { - validateFlags, handleValidationErrors, + validateFlags, } from "./flags/flagValidator.js"; +import { configureConsoleForHeadless } from "./init.js"; import { sentryService } from "./sentry.js"; import { addCommonOptions, mergeParentOptions } from "./shared-options.js"; -import { configureConsoleForHeadless } from "./util/consoleOverride.js"; import { logger } from "./util/logger.js"; import { readStdinSync } from "./util/stdin.js"; import { getVersion } from "./version.js"; diff --git a/extensions/cli/src/init.ts b/extensions/cli/src/init.ts new file mode 100644 index 000000000..47766c0bb --- /dev/null +++ b/extensions/cli/src/init.ts @@ -0,0 +1,128 @@ +/** + * Early initialization that must happen before ANY other imports + * This file intercepts console and stdout/stderr to prevent dependency logging + */ + +// Check if we're in headless mode by looking at process arguments +// We need to do this before any imports to catch early logging +const args = process.argv.slice(2); +const isHeadlessMode = args.includes("-p") || args.includes("--print"); + +// Store original methods before ANY dependencies can use them +const originalStdoutWrite = process.stdout.write.bind(process.stdout); +const originalStderrWrite = process.stderr.write.bind(process.stderr); +const originalConsole = { + log: console.log, + info: console.info, + warn: console.warn, + error: console.error, + debug: console.debug, + trace: console.trace, + table: console.table, + dir: console.dir, + dirxml: console.dirxml, + group: console.group, + groupEnd: console.groupEnd, + groupCollapsed: console.groupCollapsed, + time: console.time, + timeEnd: console.timeEnd, + timeLog: console.timeLog, + clear: console.clear, + count: console.count, + countReset: console.countReset, + assert: console.assert, +}; + +// Track if we're inside our own code vs dependency code +let isHeadlessModeConfigured = false; + +// Override console methods if in headless mode +if (isHeadlessMode) { + // Override ALL console methods to no-ops + Object.keys(originalConsole).forEach((method) => { + (console as any)[method] = () => {}; + }); + + // Override stdout/stderr to block everything by default + process.stdout.write = function ( + chunk: any, + encoding?: any, + callback?: any, + ): boolean { + // Always return true to indicate success, but don't actually write + if (typeof encoding === "function") { + encoding(); + return true; + } + if (typeof callback === "function") { + callback(); + } + return true; + }; + + process.stderr.write = function ( + chunk: any, + encoding?: any, + callback?: any, + ): boolean { + // Always return true to indicate success, but don't actually write + if (typeof encoding === "function") { + encoding(); + return true; + } + if (typeof callback === "function") { + callback(); + } + return true; + }; +} + +/** + * Configure console for headless mode + * Since init.ts already blocks everything, this just tracks state + * and provides the safe output functions + */ +export function configureConsoleForHeadless(headless: boolean): void { + isHeadlessModeConfigured = headless; + + // init.ts should have already handled the blocking if in headless mode + // This function now mainly exists for compatibility and state tracking +} + +/** + * Safe stdout output that bypasses all overrides + * Use this for intentional output in headless mode + */ +export function safeStdout(message: string): void { + if (isHeadlessMode || isHeadlessModeConfigured) { + // Use the original stdout that was saved before any overrides + originalStdoutWrite(message); + } else { + // In non-headless mode, just use normal stdout + process.stdout.write(message); + } +} + +/** + * Safe stderr output that bypasses all overrides + * Use this for error messages that should always be visible + */ +export function safeStderr(message: string): void { + if (isHeadlessMode || isHeadlessModeConfigured) { + // Use the original stderr that was saved before any overrides + originalStderrWrite(message); + } else { + // In non-headless mode, just use normal stderr + process.stderr.write(message); + } +} + +/** + * Reset console overrides to original state + * Note: This won't affect init.ts overrides which happen at module load + */ +export function resetConsoleOverrides(): void { + isHeadlessModeConfigured = false; + // The actual console restoration would need to happen in init.ts + // This is mainly for testing purposes +} diff --git a/extensions/cli/src/util/consoleOverride.ts b/extensions/cli/src/util/consoleOverride.ts deleted file mode 100644 index 24ee2e5d0..000000000 --- a/extensions/cli/src/util/consoleOverride.ts +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Console override utility to prevent unwanted output in headless mode - * This ensures that only intentional stdout output reaches the user - */ - -interface ConsoleBackup { - log: typeof console.log; - info: typeof console.info; - warn: typeof console.warn; - error: typeof console.error; - debug: typeof console.debug; -} - -let originalConsole: ConsoleBackup | null = null; -let isHeadlessMode = false; - -/** - * Override console methods to prevent unwanted output in headless mode - * In headless mode, only console.error and explicitly allowed outputs should reach stdout - */ -export function configureConsoleForHeadless(headless: boolean): void { - isHeadlessMode = headless; - - if (headless && !originalConsole) { - // Backup original console methods - originalConsole = { - log: console.log, - info: console.info, - warn: console.warn, - error: console.error, - debug: console.debug, - }; - - // Override console methods to suppress output in headless mode - console.log = () => {}; // Suppress all console.log - console.info = () => {}; // Suppress all console.info - console.warn = () => {}; // Suppress all console.warn - console.debug = () => {}; // Suppress all console.debug - - // Keep console.error for genuine errors, but send to stderr - console.error = (...args: any[]) => { - originalConsole!.error(...args); - }; - } else if (!headless && originalConsole) { - // Restore original console methods - console.log = originalConsole.log; - console.info = originalConsole.info; - console.warn = originalConsole.warn; - console.error = originalConsole.error; - console.debug = originalConsole.debug; - - originalConsole = null; - } -} - -/** - * Safe stdout output that bypasses console overrides - * Use this for intentional output in headless mode - */ -export function safeStdout(message: string): void { - process.stdout.write(message); -} - -/** - * Safe stderr output that bypasses console overrides - * Use this for error messages that should always be visible - */ -export function safeStderr(message: string): void { - process.stderr.write(message); -} - -/** - * Temporarily restore console for a specific operation - * Useful for debugging or when you need original console behavior - */ -export function withOriginalConsole(fn: () => T): T { - if (!originalConsole || !isHeadlessMode) { - return fn(); - } - - // Temporarily restore - const tempConsole = { ...console }; - Object.assign(console, originalConsole); - - try { - return fn(); - } finally { - // Restore overrides - Object.assign(console, tempConsole); - } -} - -/** - * Check if currently in headless mode - */ -export function isInHeadlessMode(): boolean { - return isHeadlessMode; -} - -/** - * Reset console overrides to original state - * Useful for testing to ensure clean state - */ -export function resetConsoleOverrides(): void { - if (originalConsole) { - console.log = originalConsole.log; - console.info = originalConsole.info; - console.warn = originalConsole.warn; - console.error = originalConsole.error; - console.debug = originalConsole.debug; - - originalConsole = null; - } - isHeadlessMode = false; -} diff --git a/extensions/cli/vitest.setup.ts b/extensions/cli/vitest.setup.ts index c7ad30ec3..886bd6ca0 100644 --- a/extensions/cli/vitest.setup.ts +++ b/extensions/cli/vitest.setup.ts @@ -1,6 +1,6 @@ import { vi } from "vitest"; -import { resetConsoleOverrides } from "./src/util/consoleOverride.js"; +import { resetConsoleOverrides } from "./src/init.js"; // Disable telemetry for tests process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0"; From 35434542aba77277e64f7f20858e01f157e568b7 Mon Sep 17 00:00:00 2001 From: Brian Douglas Date: Fri, 22 Aug 2025 13:23:10 -0700 Subject: [PATCH 15/38] docs: update recommended model links (#7345) --- docs/customization/models.mdx | 8 ++-- .../model-providers/top-level/azure.mdx | 2 +- .../model-providers/top-level/deepseek.mdx | 2 +- .../model-providers/top-level/gemini.mdx | 2 +- .../model-providers/top-level/ollama.mdx | 2 +- docs/features/agent/model-setup.mdx | 17 +------- docs/features/autocomplete/model-setup.mdx | 40 +------------------ docs/features/chat/model-setup.mdx | 11 +---- docs/features/edit/model-setup.mdx | 5 +-- 9 files changed, 12 insertions(+), 77 deletions(-) diff --git a/docs/customization/models.mdx b/docs/customization/models.mdx index d4b02be76..2b63f40d5 100644 --- a/docs/customization/models.mdx +++ b/docs/customization/models.mdx @@ -18,11 +18,11 @@ description: "These blocks form the foundation of the entire assistant experienc | Model role | Best open models | Best closed models | Notes | |:------------|:------------------|:-------------------|:--------| -| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed models are slightly better than open models | -| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance | -| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder | Closed models are slightly better than open models | +| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Qwen2.5-Coder (32B), Devstral (27B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), GPT-4, [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro), DeepSeek models | Closed models are slightly better than open models | +| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B), DeepSeek Chat | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance | +| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder, Mercury Coder Small, DeepSeek Coder | Closed models are slightly better than open models | | Apply | N/A | [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply), [Morph Fast Apply](https://hub.continue.dev/morphllm/morph-v2) | Open models are basically non-existent / not good enough for this model role | -| Embed | N/A | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed | Open models are basically non-existent / not good enough for this model role | +| Embed | Nomic Embed Text | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed, text-embedding-3-large, text-embedding-004 | Open embeddings models are emerging but closed models still perform better | | Rerank | zerank-1, zerank-1-small | rerank-2.5, Relace Code Rerank, [Morph Rerank](https://hub.continue.dev/morphllm/morph-rerank-v2) | Open models are beginning to emerge for this model role | | Next Edit | Zeta | Mercury Coder | Closed models are significantly better than open models | diff --git a/docs/customize/model-providers/top-level/azure.mdx b/docs/customize/model-providers/top-level/azure.mdx index b59c2071c..2fd9b32e4 100644 --- a/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/customize/model-providers/top-level/azure.mdx @@ -92,7 +92,7 @@ If you use Azure Machine Learning Studio to deploy Codestral: ## How to Configure Azure AI Foundry Embeddings Models -We recommend configuring **text-embedding-3-large** as your embeddings model. +For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models). diff --git a/docs/customize/model-providers/top-level/deepseek.mdx b/docs/customize/model-providers/top-level/deepseek.mdx index 376a33173..018ac4186 100644 --- a/docs/customize/model-providers/top-level/deepseek.mdx +++ b/docs/customize/model-providers/top-level/deepseek.mdx @@ -41,7 +41,7 @@ We recommend configuring **DeepSeek Chat** as your chat model. ## How to Set Up DeepSeek Autocomplete Models -We recommend configuring **DeepSeek Coder** as your autocomplete model. +For recommended autocomplete models, please refer to our [Model Recommendations page](/customization/models). diff --git a/docs/customize/model-providers/top-level/gemini.mdx b/docs/customize/model-providers/top-level/gemini.mdx index 2e85be425..36a85ca8b 100644 --- a/docs/customize/model-providers/top-level/gemini.mdx +++ b/docs/customize/model-providers/top-level/gemini.mdx @@ -48,7 +48,7 @@ Gemini currently does not offer any autocomplete models. ## How to Configure Gemini Embeddings Models -We recommend configuring **text-embedding-004** as your embeddings model. +For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models). diff --git a/docs/customize/model-providers/top-level/ollama.mdx b/docs/customize/model-providers/top-level/ollama.mdx index d595cb8fb..cd9a0b45f 100644 --- a/docs/customize/model-providers/top-level/ollama.mdx +++ b/docs/customize/model-providers/top-level/ollama.mdx @@ -65,7 +65,7 @@ We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. ## How to Set Up Ollama Embeddings Models -We recommend configuring **Nomic Embed Text** as your embeddings model. +For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models). diff --git a/docs/features/agent/model-setup.mdx b/docs/features/agent/model-setup.mdx index c1ef8fb82..ae8e5675f 100644 --- a/docs/features/agent/model-setup.mdx +++ b/docs/features/agent/model-setup.mdx @@ -27,22 +27,7 @@ Instead of relying solely on native tool calling APIs (which vary between provid - **Better reliability** - Models that struggle with native tools often perform better with system message tools - **Seamless switching** - Change between providers without modifying your workflow -### What Models Are Recommended for Agent Mode - -For the best Agent mode experience, we recommend models with strong reasoning and instruction-following capabilities: - -**Premium Models:** - -- **Claude Sonnet 4** (Anthropic) - Our top recommendation for its exceptional tool use and reasoning -- **GPT-4** models (OpenAI) - Excellent native tool support -- **DeepSeek** models - Strong performance with competitive pricing - -**Local Models:** -While more limited in capabilities, these models can work with system message tools: - -- Qwen2.5-Coder 32B - Best local option for Agent mode -- Devstral 27B - Good for code-specific tasks -- Smaller models (7B-13B) - May struggle with complex tool interactions +For recommended Agent models, please refer to our [Model Recommendations page](/customization/models). ### How to Configure Agent Mode diff --git a/docs/features/autocomplete/model-setup.mdx b/docs/features/autocomplete/model-setup.mdx index aca816ef3..879939c14 100644 --- a/docs/features/autocomplete/model-setup.mdx +++ b/docs/features/autocomplete/model-setup.mdx @@ -10,45 +10,7 @@ Setting up the right model for autocomplete is crucial for a smooth coding exper For a complete comparison of all autocomplete models, see our [comprehensive model recommendations](/customization/models#recommended-models). -## Recommended Models for Autocomplete in Continue - -### Hosted (Best Performance) - -For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral. - -This model is specifically designed for code completion and offers excellent performance across multiple programming languages. - -**Codestral Quick Setup:** - -1. Get your API key from [Mistral AI](https://console.mistral.ai) -2. Add [Codestral](https://hub.continue.dev/mistral/codestral) to your assistant on Continue Hub -3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the assistant selector in the Continue IDE extension - -### Hosted (Best Speed/Quality Tradeoff) - -For fast, quality autocomplete suggestions, we recommend **[Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small)** from Inception. - -This model is specifically designed for code completion and is particularly fast because it is a diffusion model. - -**Mercury Coder Small Quick Setup:** - -1. Get your API key from [Inception](https://platform.inceptionlabs.ai/) -2. Add [Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small) to your assistant on Continue Hub -3. Add `INCEPTION_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the assistant selector in the Continue IDE extension - -### Local (Offline / Privacy First) - -For a fully local autocomplete experience, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)**. - -This model provides good suggestions while keeping your code completely private. - -**Quick Setup:** - -1. Install [Ollama](https://ollama.ai/) -2. Add [Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to your assistant on Continue Hub -3. Click `Reload config` in the assistant selector in the Continue IDE extension +For model recommendations, please refer to our [Model Recommendations page](/customization/models). ## Next Edit Model diff --git a/docs/features/chat/model-setup.mdx b/docs/features/chat/model-setup.mdx index 0f881d6b0..409b1b7a0 100644 --- a/docs/features/chat/model-setup.mdx +++ b/docs/features/chat/model-setup.mdx @@ -7,16 +7,7 @@ The model you use for for Chat mode will be For a comprehensive comparison of all available models by role, see our [model recommendations table](/customization/models#recommended-models). -## What Models Are Recommended for Chat? - -Our strong recommendation is to use [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic. - -Its strong tool calling and reasoning capabilities make it the best model for Agent mode. - -1. Get your API key from [Anthropic](https://console.anthropic.com/) -2. Add [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) to your assistant on Continue Hub -3. Add `ANTHROPIC_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) -4. Click `Reload config` in the assistant selector in the Continue IDE extension +For model recommendations, please refer to our [Model Recommendations page](/customization/models). ### What Other Hosted Models Are Available? diff --git a/docs/features/edit/model-setup.mdx b/docs/features/edit/model-setup.mdx index 1760c5aee..35694ce97 100644 --- a/docs/features/edit/model-setup.mdx +++ b/docs/features/edit/model-setup.mdx @@ -16,10 +16,7 @@ The recommended models and how to set them up can be found [here](/features/chat We also recommend setting up an Apply model for the best Edit experience. -**Recommended Apply models:** - -- [Morph v3](https://hub.continue.dev/morphllm/morph-v2) -- [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply) +For recommended Apply models, please refer to our [Model Recommendations page](/customization/models). ## How to Determine Model Compatibility From 89cc96c6c8c753dac2588a91088422028de743c8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 22 Aug 2025 13:50:33 -0700 Subject: [PATCH 16/38] chore: upgrade to 1.3.0 --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index f980b66d5..5b92de1f1 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.83", + "version": "1.3.0", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From c2231a9366cff60305124c51bcc7558858f073f3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 22 Aug 2025 14:44:37 -0700 Subject: [PATCH 17/38] refactor: code cleanup for next edit (#7312) * feat: don't format when model is not mercury * chore: bump * fix: remove mercury-coder-nextedit * refactor: remove refs to mercury-coder-nextedit * feat: add util function for converting model name to enum * refactor: add new types * refactor: create an abstract base class for providers * refactor: add child provider for instinct * refactor: add provider for mercury coder * refactor: provider factory * refactor: use factory to create model providers based on helper.modelName * refactor: clean up redundant logic to be more provider-friendly * add buildPromptMetadata as an abstract method * refactor: use handlebars and provider-specific template renderers * refactor: use this.modelProvider instead of prompt engine * refactor: remove redundant helper * fix: update vitest after refactor * feat: add test for convertNextEditModelNameToEnum * fix: add isSecurityConcern imports --- core/llm/autodetect.ts | 1 - core/llm/autodetect.vitest.ts | 24 +- core/llm/constants.ts | 1 - core/nextEdit/NextEditProvider.ts | 724 ++++-------------- core/nextEdit/NextEditProviderFactory.ts | 16 + core/nextEdit/constants.ts | 4 - .../providers/BaseNextEditProvider.ts | 415 ++++++++++ .../providers/InstinctNextEditProvider.ts | 155 ++++ .../providers/MercuryCoderNextEditProvider.ts | 145 ++++ .../templating/NextEditPromptEngine.ts | 284 +------ .../templating/NextEditPromptEngine.vitest.ts | 303 +++----- core/nextEdit/types.ts | 35 + core/nextEdit/utils.ts | 9 + core/nextEdit/utils.vitest.ts | 39 +- 14 files changed, 1066 insertions(+), 1089 deletions(-) create mode 100644 core/nextEdit/NextEditProviderFactory.ts create mode 100644 core/nextEdit/providers/BaseNextEditProvider.ts create mode 100644 core/nextEdit/providers/InstinctNextEditProvider.ts create mode 100644 core/nextEdit/providers/MercuryCoderNextEditProvider.ts diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 3f9e62dfc..8e036ff3a 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -178,7 +178,6 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired( // update core/nextEdit/templating/NextEditPromptEngine.ts as well. const MODEL_SUPPORTS_NEXT_EDIT: string[] = [ NEXT_EDIT_MODELS.MERCURY_CODER, - NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, NEXT_EDIT_MODELS.INSTINCT, ]; diff --git a/core/llm/autodetect.vitest.ts b/core/llm/autodetect.vitest.ts index 4e250f1ad..95a2f3d82 100644 --- a/core/llm/autodetect.vitest.ts +++ b/core/llm/autodetect.vitest.ts @@ -220,7 +220,7 @@ describe("modelSupportsNextEdit", () => { expect( modelSupportsNextEdit( { nextEdit: false }, - "mercury-coder-nextedit", + "mercury-coder", "Mercury Coder", ), ).toBe(false); @@ -231,7 +231,7 @@ describe("modelSupportsNextEdit", () => { expect( modelSupportsNextEdit( { nextEdit: false }, - "mercury-coder-nextedit", + "mercury-coder", "Mercury Coder", ), ).toBe(false); @@ -239,10 +239,10 @@ describe("modelSupportsNextEdit", () => { }); describe("when capabilities.nextEdit is undefined", () => { - it("should return true for mercury-coder-nextedit model (case insensitive)", () => { - expect( - modelSupportsNextEdit(undefined, "Mercury-Coder-Nextedit", undefined), - ).toBe(true); + it("should return true for mercury-coder model (case insensitive)", () => { + expect(modelSupportsNextEdit(undefined, "Mercury-Coder", undefined)).toBe( + true, + ); }); it("should return true for instinct", () => { @@ -255,7 +255,7 @@ describe("modelSupportsNextEdit", () => { expect( modelSupportsNextEdit( undefined, - "provider/mercury-coder-nextedit-v2", + "provider/mercury-coder-v2", undefined, ), ).toBe(true); @@ -266,7 +266,7 @@ describe("modelSupportsNextEdit", () => { modelSupportsNextEdit( undefined, "some-model", - "This is mercury-coder-nextedit model", + "This is mercury-coder model", ), ).toBe(true); }); @@ -312,14 +312,14 @@ describe("modelSupportsNextEdit", () => { }); it("should handle undefined title gracefully", () => { - expect( - modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined), - ).toBe(true); + expect(modelSupportsNextEdit(undefined, "mercury-coder", undefined)).toBe( + true, + ); }); it("should handle case sensitivity correctly", () => { expect( - modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"), + modelSupportsNextEdit(undefined, "MERCURY-CODER", "instinct"), ).toBe(true); }); diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 4364257ab..c368e0d5a 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -21,7 +21,6 @@ export enum LLMConfigurationStatuses { export enum NEXT_EDIT_MODELS { MERCURY_CODER = "mercury-coder", - MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit", INSTINCT = "instinct", } diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 310f7a5b3..5bd199e05 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -1,15 +1,6 @@ -import * as path from "path"; import { v4 as uuidv4 } from "uuid"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { - ChatMessage, - DiffLine, - IDE, - ILLM, - Position, - Range, - RangeInFile, -} from "../index.js"; +import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; @@ -18,10 +9,7 @@ import { ContextRetrievalService } from "../autocomplete/context/ContextRetrieva import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; -import { - getAllSnippetsWithoutRace, - SnippetPayload, -} from "../autocomplete/snippets/index.js"; +import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js"; import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; import { getAst } from "../autocomplete/util/ast.js"; @@ -29,39 +17,23 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; -import { myersDiff } from "../diff/myers.js"; import { isSecurityConcern } from "../indexing/ignore.js"; import { modelSupportsNextEdit } from "../llm/autodetect.js"; -import { NEXT_EDIT_MODELS } from "../llm/constants.js"; import { countTokens } from "../llm/countTokens.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; -import { - INSTINCT_SYSTEM_PROMPT, - MERCURY_SYSTEM_PROMPT, - MODEL_WINDOW_SIZES, - UNIQUE_TOKEN, -} from "./constants.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; -import { - calculateFinalCursorPosition, - DiffGroup, - groupDiffLines, -} from "./diff/diff.js"; import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; import { PrefetchQueue } from "./NextEditPrefetchQueue.js"; +import { NextEditProviderFactory } from "./NextEditProviderFactory.js"; +import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js"; import { - renderDefaultSystemPrompt, - renderDefaultUserPrompt, - renderPrompt, -} from "./templating/NextEditPromptEngine.js"; -import { + ModelSpecificContext, NextEditOutcome, Prompt, PromptMetadata, RecentlyEditedRange, } from "./types.js"; -import { isWhitespaceOnlyDeletion } from "./utils.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -92,6 +64,9 @@ export class NextEditProvider { private previousCompletions: NextEditOutcome[] = []; // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; + // Model-specific provider instance. + private modelProvider: BaseNextEditProvider | null = null; + private constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, @@ -298,28 +273,23 @@ export class NextEditProvider { } = await this._initializeCompletionRequest(input, token); if (!helper) return undefined; + // Create model-specific provider based on the model name. + this.modelProvider = NextEditProviderFactory.createProvider( + helper.modelName, + ); + const { editableRegionStartLine, editableRegionEndLine, prompts } = await this._generatePrompts(helper, opts); - if (this.endpointType === "default") { - return await this._handleDefaultEndpointCompletion( - helper, - prompts, - abortToken, - startTime, - editableRegionEndLine, - ); - } else { - return await this._handleFineTunedEndpointCompletion( - helper, - prompts, - abortToken, - startTime, - editableRegionStartLine, - editableRegionEndLine, - opts, - ); - } + return await this._handleCompletion( + helper, + prompts, + abortToken, + startTime, + editableRegionStartLine, + editableRegionEndLine, + opts, + ); } catch (e: any) { this.onError(e); } finally { @@ -335,7 +305,7 @@ export class NextEditProvider { startTime: number; helper: HelperVars | undefined; }> { - // Create abort signal if not given. + // Create abort signal if not given if (!token) { const controller = this.loggingService.createAbortController( input.completionId, @@ -345,7 +315,7 @@ export class NextEditProvider { const startTime = Date.now(); const options = await this._getAutocompleteOptions(); - // Debounce. + // Debounce if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { return { token, startTime, helper: undefined }; } @@ -355,9 +325,7 @@ export class NextEditProvider { return { token, startTime, helper: undefined }; } - // In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts. - // For other editors, this check should be done in their respective config reloaders. - // This is left for a final check. + // Check model capabilities if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) { console.error(`${llm.model} is not capable of next edit.`); return { token, startTime, helper: undefined }; @@ -387,6 +355,10 @@ export class NextEditProvider { editableRegionEndLine: number; prompts: Prompt[]; }> { + if (!this.modelProvider) { + throw new Error("Model provider not initialized"); + } + const [snippetPayload, workspaceDirs] = await Promise.all([ getAllSnippetsWithoutRace({ helper, @@ -397,56 +369,118 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); - const modelName = helper.modelName.includes( - NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, - ) - ? NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT - : helper.modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) - ? NEXT_EDIT_MODELS.MERCURY_CODER - : NEXT_EDIT_MODELS.INSTINCT; - + // Calculate editable region based on model and options. const { editableRegionStartLine, editableRegionEndLine } = - opts?.usingFullFileDiff - ? this._calculateOptimalEditableRegion(helper, "tokenizer") - : { - editableRegionStartLine: Math.max( - helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin, - 0, - ), - editableRegionEndLine: Math.min( - helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin, - helper.fileLines.length - 1, - ), - }; + this.modelProvider.calculateEditableRegion( + helper, + opts?.usingFullFileDiff ?? false, + ); - // const editableRegionStartLine = opts?.usingFullFileDiff - // ? 0 - // : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0); + // Build context for model-specific prompt generation. + const context: ModelSpecificContext = { + helper, + snippetPayload, + editableRegionStartLine, + editableRegionEndLine, + diffContext: this.diffContext, + autocompleteContext: this.autocompleteContext, + historyDiff: createDiff({ + beforeContent: + DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( + localPathOrUriToPath(helper.filepath), + ) ?? "", + afterContent: helper.fileContents, + filePath: helper.filepath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }), + }; - // const editableRegionEndLine = opts?.usingFullFileDiff - // ? helper.fileLines.length - 1 - // : Math.min( - // helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - // helper.fileLines.length - 1, - // ); + const prompts = await this.modelProvider.generatePrompts(context); - const prompts: Prompt[] = []; + this.promptMetadata = this.modelProvider.buildPromptMetadata(context); - if (this.endpointType === "default") { - prompts.push(renderDefaultSystemPrompt()); - prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); + return { editableRegionStartLine, editableRegionEndLine, prompts }; + } + + private async _handleCompletion( + helper: HelperVars, + prompts: Prompt[], + token: AbortSignal, + startTime: number, + editableRegionStartLine: number, + editableRegionEndLine: number, + opts?: { + withChain: boolean; + usingFullFileDiff: boolean; + }, + ): Promise { + if (!this.modelProvider) { + throw new Error("Model provider not initialized"); + } + + const llm = await this._prepareLlm(); + if (!llm) return undefined; + + // Inject unique token if needed (for Mercury models). + if (this.modelProvider.shouldInjectUniqueToken()) { + const uniqueToken = this.modelProvider.getUniqueToken(); + if (uniqueToken) { + const lastPrompt = prompts[prompts.length - 1]; + if (lastPrompt && typeof lastPrompt.content === "string") { + lastPrompt.content += uniqueToken; + } + } + } + + // Send prompts to LLM (using only user prompt for fine-tuned models). + const msg: ChatMessage = await llm.chat([prompts[1]], token, { + stream: false, + }); + + if (typeof msg.content !== "string") { + return undefined; + } + + // Extract completion using model-specific logic. + const nextCompletion = this.modelProvider.extractCompletion(msg.content); + + let outcome: NextEditOutcome | undefined; + + // Handle based on diff type. + if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { + outcome = await this.modelProvider.handlePartialFileDiff( + helper, + editableRegionStartLine, + editableRegionEndLine, + startTime, + llm, + nextCompletion, + this.promptMetadata!, + this.ide, + ); } else { - prompts.push( - ...(await this._generateFineTunedPrompts( - helper, - snippetPayload, - editableRegionStartLine, - editableRegionEndLine, - )), + outcome = await this.modelProvider.handleFullFileDiff( + helper, + editableRegionStartLine, + editableRegionEndLine, + startTime, + llm, + nextCompletion, + this.promptMetadata!, + this.ide, ); } - return { editableRegionStartLine, editableRegionEndLine, prompts }; + if (outcome) { + // Handle NextEditProvider-specific state + this.previousCompletions.push(outcome); + + // Mark as displayed for JetBrains + await this._markDisplayedIfJetBrains(helper.input.completionId, outcome); + } + + return outcome; } private _calculateOptimalEditableRegion( @@ -540,500 +574,6 @@ export class NextEditProvider { }; } - private async _generateFineTunedPrompts( - helper: HelperVars, - snippetPayload: SnippetPayload, - editableRegionStartLine: number, - editableRegionEndLine: number, - ): Promise { - const historyDiff = createDiff({ - beforeContent: - DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( - localPathOrUriToPath(helper.filepath), - ) ?? "", - afterContent: helper.fileContents, - filePath: helper.filepath, - diffType: DiffFormatType.Unified, - contextLines: 3, - }); - - const modelName = helper.modelName; - let ctx: any; - - if ( - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) || - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT) - ) { - ctx = { - recentlyViewedCodeSnippets: - snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ - filepath: snip.filepath, - content: snip.content, - })) ?? [], - currentFileContent: helper.fileContents, - editableRegionStartLine, - editableRegionEndLine, - editDiffHistory: this.diffContext, - currentFilePath: helper.filepath, - }; - } else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) { - // Calculate the window around the cursor position (25 lines above and below). - const windowStart = Math.max(0, helper.pos.line - 25); - const windowEnd = Math.min( - helper.fileLines.length - 1, - helper.pos.line + 25, - ); - - // // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive). - // const actualEditableStart = Math.max( - // 0, - // helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin, - // ); - // const actualEditableEnd = Math.min( - // helper.fileLines.length - 1, - // helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin, - // ); - - // Ensure editable region boundaries are within the window. - const adjustedEditableStart = Math.max( - windowStart, - editableRegionStartLine, - ); - const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine); - ctx = { - contextSnippets: this.autocompleteContext, - currentFileContent: helper.fileContents, - windowStart, - windowEnd, - editableRegionStartLine: adjustedEditableStart, - editableRegionEndLine: adjustedEditableEnd, - editDiffHistory: this.diffContext, - currentFilePath: helper.filepath, - languageShorthand: helper.lang.name, - }; - } else { - ctx = {}; - } - - const promptMetadata = await renderPrompt(helper, ctx); - this.promptMetadata = promptMetadata; - - const systemPrompt: Prompt = { - role: "system", - content: - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) || - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT) - ? MERCURY_SYSTEM_PROMPT - : INSTINCT_SYSTEM_PROMPT, - }; - - return [systemPrompt, promptMetadata.prompt]; - } - - private async _handleDefaultEndpointCompletion( - helper: HelperVars, - prompts: Prompt[], - token: AbortSignal, - startTime: number, - editableRegionEndLine: number, - ): Promise { - const llm = await this._prepareLlm(); - if (!llm) return undefined; - - const msg: ChatMessage = await llm.chat(prompts, token); - - if (typeof msg.content === "string") { - const nextCompletion = JSON.parse(msg.content).newCode; - const finalCursorPos: Position = { - line: editableRegionEndLine, - character: 0, - }; - - const outcomeNext = await this._createNextEditOutcome({ - helper, - startTime, - llm, - promptContent: prompts.join("\n"), - completion: nextCompletion, - finalCursorPosition: finalCursorPos, - editableRegionStartLine: 0, - editableRegionEndLine: 0, - userEdits: "", - userExcerpts: "", - originalEditableRange: "", - diffLines: [], - }); - - // Mark as displayed for JetBrains extension - await this._markDisplayedIfJetBrains( - helper.input.completionId, - outcomeNext, - ); - - return outcomeNext; - } - - return undefined; - } - - private async _handleFineTunedEndpointCompletion( - helper: HelperVars, - prompts: Prompt[], - token: AbortSignal, - startTime: number, - editableRegionStartLine: number, - editableRegionEndLine: number, - opts?: { - withChain: boolean; - usingFullFileDiff: boolean; - }, - ): Promise { - const llm = await this._prepareLlm(); - if (!llm) return undefined; - - // Check for mercury models, and inject unique token for next edit. - // Capture the unique tokens in llm Inception.ts and apis Inception.ts - const modelName = helper.modelName; - if ( - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) || - modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT) - ) { - // Inject the unique token to the last prompt's content. - const lastPrompt = prompts[prompts.length - 1]; - if (lastPrompt && typeof lastPrompt.content === "string") { - lastPrompt.content += UNIQUE_TOKEN; - } - } - - const msg: ChatMessage = await llm.chat([prompts[1]], token, { - stream: false, - }); - - if (typeof msg.content !== "string") { - return undefined; - } - - // NOTE: Keep this in case there is a change in spec. - // const nextCompletion = - // msg.content - // .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1] - // .replace(/\n$/, "") ?? msg.content; - const nextCompletion = msg.content.slice( - msg.content.indexOf("```\n") + "'''\n".length, - msg.content.lastIndexOf("\n\n```"), - ); - - if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { - return await this._handlePartialFileDiff( - // we could use fillFileDiff - helper, - editableRegionStartLine, - editableRegionEndLine, - startTime, - llm, - nextCompletion, - ); - } else { - return await this._handleFullFileDiff( - helper, - editableRegionStartLine, - editableRegionEndLine, - startTime, - llm, - nextCompletion, - ); - } - } - - private async _handlePartialFileDiff( - helper: HelperVars, - editableRegionStartLine: number, - editableRegionEndLine: number, - startTime: number, - llm: ILLM, - nextCompletion: string, - ): Promise { - const oldEditRangeSlice = helper.fileContents - .split("\n") - .slice(editableRegionStartLine, editableRegionEndLine + 1) - .join("\n"); - - const finalCursorPos = calculateFinalCursorPosition( - helper.pos, - editableRegionStartLine, - oldEditRangeSlice, - nextCompletion, - ); - - const outcomeNext = await this._createNextEditOutcome({ - helper, - startTime, - llm, - promptContent: this.promptMetadata!.prompt.content, - completion: nextCompletion, - finalCursorPosition: finalCursorPos, - editableRegionStartLine, - editableRegionEndLine, - userEdits: this.promptMetadata!.userEdits, - userExcerpts: this.promptMetadata!.userExcerpts, - originalEditableRange: oldEditRangeSlice, - diffLines: [], - }); - - this.previousCompletions.push(outcomeNext); - - // Mark as displayed for JetBrains extension - await this._markDisplayedIfJetBrains( - helper.input.completionId, - outcomeNext, - ); - - return outcomeNext; - } - - private async _handleFullFileDiff( - helper: HelperVars, - editableRegionStartLine: number, - editableRegionEndLine: number, - startTime: number, - llm: ILLM, - nextCompletion: string, - ): Promise { - const fileSlice = helper.fileLines - .slice(editableRegionStartLine, editableRegionEndLine + 1) - .join("\n"); - const diffLines = myersDiff(fileSlice, nextCompletion); - const diffGroups = groupDiffLines( - diffLines, - editableRegionStartLine, - 5, - ).filter((group) => !isWhitespaceOnlyDeletion(group.lines)); - const currentLine = helper.pos.line; - const prefetchQueue = PrefetchQueue.getInstance(); - - // Process diff groups and find the one containing the cursor - const cursorLocalDiffGroup = await this._processDiffGroups( - diffGroups, - currentLine, - helper, - startTime, - llm, - prefetchQueue, - ); - - // Handle the diff group containing the cursor if found - if (cursorLocalDiffGroup) { - return await this._createOutcomeFromDiffGroup( - cursorLocalDiffGroup, - helper, - startTime, - llm, - helper.input.completionId, - true, - ); - // } else if (diffGroups.length > 0) { - // // Fallback to first diff group if cursor's group not found - // return await this._createOutcomeFromDiffGroup( - // diffGroups[0], - // helper, - // startTime, - // llm, - // helper.input.completionId, - // false, - // ); - } - - return undefined; - } - - private async _processDiffGroups( - diffGroups: DiffGroup[], - currentLine: number, - helper: HelperVars, - startTime: number, - llm: ILLM, - prefetchQueue: PrefetchQueue, - ): Promise { - let cursorGroup: DiffGroup | undefined; - - console.log("diffGroups:"); - console.log(diffGroups); - - for (const group of diffGroups) { - if (currentLine >= group.startLine && currentLine <= group.endLine) { - cursorGroup = group; - } else { - // Add non-cursor groups to prefetch queue - await this._addDiffGroupToPrefetchQueue( - group, - helper, - startTime, - llm, - prefetchQueue, - ); - } - } - - return cursorGroup; - } - - private async _addDiffGroupToPrefetchQueue( - group: DiffGroup, - helper: HelperVars, - startTime: number, - llm: ILLM, - prefetchQueue: PrefetchQueue, - ): Promise { - const groupContent = group.lines - .filter((l) => l.type !== "old") - .map((l) => l.line) - .join("\n"); - - // Create a range for this diff group - const rangeInFile: RangeInFile = { - filepath: helper.filepath, - range: { - start: { line: group.startLine, character: 0 }, - end: { - line: group.endLine, - character: group.lines[group.lines.length - 1].line.length, - }, - }, - }; - - const originalContent = group.lines - .filter((l) => l.type !== "new") - .map((l) => l.line) - .join("\n"); - - // Build outcome for this diff group - const groupOutcome = await this._createNextEditOutcome({ - helper, - startTime, - llm, - promptContent: this.promptMetadata!.prompt.content, - completion: groupContent, - finalCursorPosition: { - line: group.endLine, - character: group.lines[group.lines.length - 1].line.length, - }, - editableRegionStartLine: group.startLine, - editableRegionEndLine: group.endLine, - userEdits: this.promptMetadata!.userEdits, - userExcerpts: this.promptMetadata!.userExcerpts, - originalEditableRange: originalContent, - cursorPosition: { line: group.startLine, character: 0 }, - completionId: uuidv4(), // Generate a new ID for this prefetched item - diffLines: group.lines, - }); - - // Add to prefetch queue - prefetchQueue.enqueueProcessed({ - location: rangeInFile, - outcome: groupOutcome, - }); - } - - private async _createOutcomeFromDiffGroup( - diffGroup: DiffGroup, - helper: HelperVars, - startTime: number, - llm: ILLM, - completionId: string, - isCurrentCursorGroup: boolean, - ): Promise { - const groupContent = diffGroup.lines - .filter((l) => l.type !== "old") - .map((line) => line.line) - .join("\n"); - - const originalContent = diffGroup.lines - .filter((l) => l.type !== "new") - .map((l) => l.line) - .join("\n"); - - // Use the actual cursor position if this is the group containing the cursor - // Otherwise use the start of the diff group - const cursorPos = isCurrentCursorGroup - ? helper.pos - : { line: diffGroup.startLine, character: 0 }; - - const finalCursorPos = calculateFinalCursorPosition( - cursorPos, - diffGroup.startLine, - originalContent, - groupContent, - ); - - const outcomeNext = await this._createNextEditOutcome({ - helper, - startTime, - llm, - promptContent: this.promptMetadata!.prompt.content, - completion: groupContent, - finalCursorPosition: finalCursorPos, - editableRegionStartLine: diffGroup.startLine, - editableRegionEndLine: diffGroup.endLine, - userEdits: this.promptMetadata!.userEdits, - userExcerpts: this.promptMetadata!.userExcerpts, - originalEditableRange: originalContent, - cursorPosition: cursorPos, - completionId, - diffLines: diffGroup.lines, - }); - - this.previousCompletions.push(outcomeNext); - - // Mark as displayed for JetBrains - await this._markDisplayedIfJetBrains(completionId, outcomeNext); - - return outcomeNext; - } - - private async _createNextEditOutcome(outcomeCtx: { - helper: HelperVars; - startTime: number; - llm: ILLM; - promptContent: string; - completion: string; - finalCursorPosition: Position; - editableRegionStartLine: number; - editableRegionEndLine: number; - userEdits: string; - userExcerpts: string; - originalEditableRange: string; - cursorPosition?: Position; - completionId?: string; - diffLines: DiffLine[]; - }): Promise { - return { - elapsed: Date.now() - outcomeCtx.startTime, - modelProvider: outcomeCtx.llm.underlyingProviderName, - modelName: outcomeCtx.llm.model + ":zetaDataset", - completionOptions: null, - completionId: - outcomeCtx.completionId || outcomeCtx.helper.input.completionId, - gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath), - uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), - fileUri: outcomeCtx.helper.filepath, - workspaceDirUri: - outcomeCtx.helper.workspaceUris[0] ?? - path.dirname(outcomeCtx.helper.filepath), - prompt: outcomeCtx.promptContent, - userEdits: outcomeCtx.userEdits ?? "", - userExcerpts: outcomeCtx.userExcerpts ?? "", - originalEditableRange: outcomeCtx.originalEditableRange ?? "", - completion: outcomeCtx.completion, - cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos, - finalCursorPosition: outcomeCtx.finalCursorPosition, - editableRegionStartLine: outcomeCtx.editableRegionStartLine, - editableRegionEndLine: outcomeCtx.editableRegionEndLine, - diffLines: outcomeCtx.diffLines, - ...outcomeCtx.helper.options, - }; - } - private async _markDisplayedIfJetBrains( completionId: string, outcome: NextEditOutcome, diff --git a/core/nextEdit/NextEditProviderFactory.ts b/core/nextEdit/NextEditProviderFactory.ts new file mode 100644 index 000000000..4ba97c651 --- /dev/null +++ b/core/nextEdit/NextEditProviderFactory.ts @@ -0,0 +1,16 @@ +import { NEXT_EDIT_MODELS } from "../llm/constants.js"; +import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js"; +import { InstinctProvider } from "./providers/InstinctNextEditProvider.js"; +import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js"; + +export class NextEditProviderFactory { + static createProvider(modelName: string): BaseNextEditProvider { + if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) { + return new MercuryCoderProvider(); + } else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) { + return new InstinctProvider(); + } else { + throw new Error(`Unsupported model: ${modelName}`); + } + } +} diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index c569cb208..d8bd4c9df 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -12,10 +12,6 @@ export const MODEL_WINDOW_SIZES: Record< topMargin: 0, bottomMargin: 5, }, // mercury coder uses full file diff, so this should be unnecessary - "mercury-coder-nextedit": { - topMargin: 0, - bottomMargin: 5, - }, // mercury coder nextedit uses full file diff, so this should be unnecessary instinct: { topMargin: 1, bottomMargin: 5 }, }; diff --git a/core/nextEdit/providers/BaseNextEditProvider.ts b/core/nextEdit/providers/BaseNextEditProvider.ts new file mode 100644 index 000000000..02d9c3998 --- /dev/null +++ b/core/nextEdit/providers/BaseNextEditProvider.ts @@ -0,0 +1,415 @@ +import * as path from "path"; +import { v4 as uuidv4 } from "uuid"; + +import { HelperVars } from "../../autocomplete/util/HelperVars.js"; +import { myersDiff } from "../../diff/myers.js"; +import { DiffLine, IDE, ILLM, Position, RangeInFile } from "../../index.js"; +import { countTokens } from "../../llm/countTokens.js"; +import { + calculateFinalCursorPosition, + DiffGroup, + groupDiffLines, +} from "../diff/diff.js"; +import { PrefetchQueue } from "../NextEditPrefetchQueue.js"; +import { + ModelSpecificContext, + NextEditOutcome, + Prompt, + PromptMetadata, +} from "../types.js"; +import { isWhitespaceOnlyDeletion } from "../utils.js"; + +export abstract class BaseNextEditProvider { + protected readonly modelName: string; + + constructor(modelName: string) { + this.modelName = modelName; + } + + // Leave methods as abstract when you must have the models implement their own versions. + abstract getSystemPrompt(): string; + abstract generatePrompts(context: ModelSpecificContext): Promise; + abstract extractCompletion(message: string): string; + abstract buildPromptContext(context: ModelSpecificContext): any; + abstract buildPromptMetadata(context: ModelSpecificContext): PromptMetadata; + abstract getWindowSize(): { topMargin: number; bottomMargin: number }; + abstract calculateEditableRegion( + helper: HelperVars, + usingFullFileDiff: boolean, + ): { + editableRegionStartLine: number; + editableRegionEndLine: number; + }; + + // Methods that can be used as default fallback. + public async handlePartialFileDiff( + helper: HelperVars, + editableRegionStartLine: number, + editableRegionEndLine: number, + startTime: number, + llm: ILLM, + nextCompletion: string, + promptMetadata: PromptMetadata, + ide: IDE, + ): Promise { + const oldEditRangeSlice = helper.fileContents + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + const finalCursorPos = calculateFinalCursorPosition( + helper.pos, + editableRegionStartLine, + oldEditRangeSlice, + nextCompletion, + ); + + const outcome = await this.createNextEditOutcome({ + helper, + startTime, + llm, + promptContent: promptMetadata.prompt.content, + completion: nextCompletion, + finalCursorPosition: finalCursorPos, + editableRegionStartLine, + editableRegionEndLine, + userEdits: promptMetadata.userEdits, + userExcerpts: promptMetadata.userExcerpts, + originalEditableRange: oldEditRangeSlice, + diffLines: [], + ide, + }); + + return outcome; + } + + public async handleFullFileDiff( + helper: HelperVars, + editableRegionStartLine: number, + editableRegionEndLine: number, + startTime: number, + llm: ILLM, + nextCompletion: string, + promptMetadata: PromptMetadata, + ide: IDE, + ): Promise { + const fileSlice = helper.fileLines + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + const diffLines = myersDiff(fileSlice, nextCompletion); + const diffGroups = groupDiffLines( + diffLines, + editableRegionStartLine, + 5, + ).filter((group) => !isWhitespaceOnlyDeletion(group.lines)); + const currentLine = helper.pos.line; + const prefetchQueue = PrefetchQueue.getInstance(); + + const cursorLocalDiffGroup = await this.processDiffGroups( + diffGroups, + currentLine, + helper, + startTime, + llm, + prefetchQueue, + promptMetadata, + ide, + ); + + if (cursorLocalDiffGroup) { + return await this.createOutcomeFromDiffGroup( + cursorLocalDiffGroup, + helper, + startTime, + llm, + helper.input.completionId, + true, + promptMetadata, + ide, + ); + } + + return undefined; + } + + /** + * Process diff groups and find the one containing the cursor. + */ + private async processDiffGroups( + diffGroups: DiffGroup[], + currentLine: number, + helper: HelperVars, + startTime: number, + llm: ILLM, + prefetchQueue: PrefetchQueue, + promptMetadata: PromptMetadata, + ide: IDE, + ): Promise { + let cursorGroup: DiffGroup | undefined; + + for (const group of diffGroups) { + if (currentLine >= group.startLine && currentLine <= group.endLine) { + cursorGroup = group; + } else { + await this.addDiffGroupToPrefetchQueue( + group, + helper, + startTime, + llm, + prefetchQueue, + promptMetadata, + ide, + ); + } + } + + return cursorGroup; + } + + private async addDiffGroupToPrefetchQueue( + group: DiffGroup, + helper: HelperVars, + startTime: number, + llm: ILLM, + prefetchQueue: PrefetchQueue, + promptMetadata: PromptMetadata, + ide: IDE, + ): Promise { + // Extract lines that are not old. + const groupContent = group.lines + .filter((l) => l.type !== "old") + .map((l) => l.line) + .join("\n"); + + const rangeInFile: RangeInFile = { + filepath: helper.filepath, + range: { + start: { line: group.startLine, character: 0 }, + end: { + line: group.endLine, + character: group.lines[group.lines.length - 1].line.length, + }, + }, + }; + + // Extract lines that are not new. + const originalContent = group.lines + .filter((l) => l.type !== "new") + .map((l) => l.line) + .join("\n"); + + const groupOutcome = await this.createNextEditOutcome({ + helper, + startTime, + llm, + promptContent: promptMetadata.prompt.content, + completion: groupContent, + finalCursorPosition: { + line: group.endLine, + character: group.lines[group.lines.length - 1].line.length, + }, + editableRegionStartLine: group.startLine, + editableRegionEndLine: group.endLine, + userEdits: promptMetadata.userEdits, + userExcerpts: promptMetadata.userExcerpts, + originalEditableRange: originalContent, + cursorPosition: { line: group.startLine, character: 0 }, + completionId: uuidv4(), // Generate a new ID for this prefetched item. + diffLines: group.lines, + ide, + }); + + prefetchQueue.enqueueProcessed({ + location: rangeInFile, + outcome: groupOutcome, + }); + } + + private async createOutcomeFromDiffGroup( + diffGroup: DiffGroup, + helper: HelperVars, + startTime: number, + llm: ILLM, + completionId: string, + isCurrentCursorGroup: boolean, + promptMetadata: PromptMetadata, + ide: IDE, + ): Promise { + const groupContent = diffGroup.lines + .filter((l) => l.type !== "old") + .map((l) => l.line) + .join("\n"); + + const originalContent = diffGroup.lines + .filter((l) => l.type !== "new") + .map((l) => l.line) + .join("\n"); + + const cursorPos = isCurrentCursorGroup + ? helper.pos + : { line: diffGroup.startLine, character: 0 }; + + const finalCursorPos = calculateFinalCursorPosition( + cursorPos, + diffGroup.startLine, + originalContent, + groupContent, + ); + + const outcomeNext = await this.createNextEditOutcome({ + helper, + startTime, + llm, + promptContent: promptMetadata.prompt.content, + completion: groupContent, + finalCursorPosition: finalCursorPos, + editableRegionStartLine: diffGroup.startLine, + editableRegionEndLine: diffGroup.endLine, + userEdits: promptMetadata.userEdits, + userExcerpts: promptMetadata.userExcerpts, + originalEditableRange: originalContent, + cursorPosition: cursorPos, + completionId, + diffLines: diffGroup.lines, + ide, + }); + + return outcomeNext; + } + + protected async createNextEditOutcome(outcomeCtx: { + helper: HelperVars; + startTime: number; + llm: ILLM; + promptContent: string; + completion: string; + finalCursorPosition: Position; + editableRegionStartLine: number; + editableRegionEndLine: number; + userEdits: string; + userExcerpts: string; + originalEditableRange: string; + cursorPosition?: Position; + completionId?: string; + diffLines: DiffLine[]; + ide: IDE; + }): Promise { + return { + elapsed: Date.now() - outcomeCtx.startTime, + modelProvider: outcomeCtx.llm.underlyingProviderName, + modelName: outcomeCtx.llm.model + ":zetaDataset", + completionOptions: null, + completionId: + outcomeCtx.completionId || outcomeCtx.helper.input.completionId, + gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath), + uniqueId: await outcomeCtx.ide.getUniqueId(), + timestamp: Date.now(), + fileUri: outcomeCtx.helper.filepath, + workspaceDirUri: + outcomeCtx.helper.workspaceUris[0] ?? + path.dirname(outcomeCtx.helper.filepath), + prompt: outcomeCtx.promptContent, + userEdits: outcomeCtx.userEdits ?? "", + userExcerpts: outcomeCtx.userExcerpts ?? "", + originalEditableRange: outcomeCtx.originalEditableRange ?? "", + completion: outcomeCtx.completion, + cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos, + finalCursorPosition: outcomeCtx.finalCursorPosition, + editableRegionStartLine: outcomeCtx.editableRegionStartLine, + editableRegionEndLine: outcomeCtx.editableRegionEndLine, + diffLines: outcomeCtx.diffLines, + ...outcomeCtx.helper.options, + }; + } + + // Shared utility for calculating editable regions. + protected calculateOptimalEditableRegion( + helper: HelperVars, + maxTokens: number = 512, + heuristic: "fourChars" | "tokenizer" = "tokenizer", + ): { + editableRegionStartLine: number; + editableRegionEndLine: number; + } { + const cursorLine = helper.pos.line; + const fileLines = helper.fileLines; + + let editableRegionStartLine = cursorLine; + let editableRegionEndLine = cursorLine; + + let currentContent = fileLines[cursorLine]; + let totalTokens = + heuristic === "tokenizer" + ? countTokens(currentContent, helper.modelName) + : Math.ceil(currentContent.length / 4); + + let addingAbove = true; + + while (totalTokens < maxTokens) { + let addedLine = false; + + if (addingAbove) { + if (editableRegionStartLine > 0) { + editableRegionStartLine--; + const lineContent = fileLines[editableRegionStartLine]; + const lineTokens = + heuristic === "tokenizer" + ? countTokens(lineContent, helper.modelName) + : Math.ceil(lineContent.length / 4); + + totalTokens += lineTokens; + addedLine = true; + } + } else { + if (editableRegionEndLine < fileLines.length - 1) { + editableRegionEndLine++; + const lineContent = fileLines[editableRegionEndLine]; + const lineTokens = + heuristic === "tokenizer" + ? countTokens(lineContent, helper.modelName) + : Math.ceil(lineContent.length / 4); + + totalTokens += lineTokens; + addedLine = true; + } + } + + if (!addedLine) { + if ( + editableRegionStartLine === 0 && + editableRegionEndLine === fileLines.length - 1 + ) { + break; + } + addingAbove = !addingAbove; + continue; + } + + if (totalTokens > maxTokens) { + if (addingAbove) { + editableRegionStartLine++; + } else { + editableRegionEndLine--; + } + break; + } + + addingAbove = !addingAbove; + } + + return { + editableRegionStartLine, + editableRegionEndLine, + }; + } + + // Optional methods with defaults. + shouldInjectUniqueToken(): boolean { + return false; + } + + getUniqueToken(): string | null { + return null; + } +} diff --git a/core/nextEdit/providers/InstinctNextEditProvider.ts b/core/nextEdit/providers/InstinctNextEditProvider.ts new file mode 100644 index 000000000..fcf156ee2 --- /dev/null +++ b/core/nextEdit/providers/InstinctNextEditProvider.ts @@ -0,0 +1,155 @@ +import { HelperVars } from "../../autocomplete/util/HelperVars.js"; +import { NEXT_EDIT_MODELS } from "../../llm/constants.js"; +import { INSTINCT_SYSTEM_PROMPT } from "../constants.js"; +import { + contextSnippetsBlock, + currentFileContentBlock, + editHistoryBlock, +} from "../templating/instinct.js"; +import { + NEXT_EDIT_MODEL_TEMPLATES, + PromptTemplateRenderer, +} from "../templating/NextEditPromptEngine.js"; +import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js"; +import { BaseNextEditProvider } from "./BaseNextEditProvider.js"; + +export class InstinctProvider extends BaseNextEditProvider { + private templateRenderer: PromptTemplateRenderer; + + constructor() { + super(NEXT_EDIT_MODELS.INSTINCT); + + const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT]; + this.templateRenderer = new PromptTemplateRenderer(template.template); + } + + getSystemPrompt(): string { + return INSTINCT_SYSTEM_PROMPT; + } + + getWindowSize() { + return { topMargin: 1, bottomMargin: 5 }; + } + + shouldInjectUniqueToken(): boolean { + return false; // Instinct doesn't use unique tokens. + } + + extractCompletion(message: string): string { + return message; // Instinct returns the completion directly. + } + + buildPromptContext(context: ModelSpecificContext): any { + // Calculate the window around the cursor position (25 lines above and below). + const windowStart = Math.max(0, context.helper.pos.line - 25); + const windowEnd = Math.min( + context.helper.fileLines.length - 1, + context.helper.pos.line + 25, + ); + + // Ensure editable region boundaries are within the window. + const adjustedEditableStart = Math.max( + windowStart, + context.editableRegionStartLine, + ); + const adjustedEditableEnd = Math.min( + windowEnd, + context.editableRegionEndLine, + ); + + return { + contextSnippets: context.autocompleteContext, + currentFileContent: context.helper.fileContents, + windowStart, + windowEnd, + editableRegionStartLine: adjustedEditableStart, + editableRegionEndLine: adjustedEditableEnd, + editDiffHistory: context.diffContext, + currentFilePath: context.helper.filepath, + languageShorthand: context.helper.lang.name, + }; + } + + async generatePrompts(context: ModelSpecificContext): Promise { + const promptCtx = this.buildPromptContext(context); + + const templateVars = { + contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets), + currentFileContent: currentFileContentBlock( + promptCtx.currentFileContent, + promptCtx.windowStart, + promptCtx.windowEnd, + promptCtx.editableRegionStartLine, + promptCtx.editableRegionEndLine, + context.helper.pos, + ), + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), + currentFilePath: promptCtx.currentFilePath, + languageShorthand: promptCtx.languageShorthand, + }; + + const userPromptContent = this.templateRenderer.render(templateVars); + + return [ + { + role: "system", + content: this.getSystemPrompt(), + }, + { + role: "user", + content: userPromptContent, + }, + ]; + } + + buildPromptMetadata(context: ModelSpecificContext): PromptMetadata { + const promptCtx = this.buildPromptContext(context); + + const templateVars = { + contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets), + currentFileContent: currentFileContentBlock( + promptCtx.currentFileContent, + promptCtx.windowStart, + promptCtx.windowEnd, + promptCtx.editableRegionStartLine, + promptCtx.editableRegionEndLine, + context.helper.pos, + ), + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), + currentFilePath: promptCtx.currentFilePath, + languageShorthand: promptCtx.languageShorthand, + }; + + const userPromptContent = this.templateRenderer.render(templateVars); + + return { + prompt: { + role: "user", + content: userPromptContent, + }, + userEdits: promptCtx.editDiffHistory.join("\n"), + userExcerpts: templateVars.currentFileContent, + }; + } + + calculateEditableRegion( + helper: HelperVars, + usingFullFileDiff: boolean, + ): { + editableRegionStartLine: number; + editableRegionEndLine: number; + } { + if (usingFullFileDiff) { + return this.calculateOptimalEditableRegion(helper, 512, "tokenizer"); + } else { + const { topMargin, bottomMargin } = this.getWindowSize(); + return { + editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0), + editableRegionEndLine: Math.min( + helper.pos.line + bottomMargin, + helper.fileLines.length - 1, + ), + }; + } + } +} diff --git a/core/nextEdit/providers/MercuryCoderNextEditProvider.ts b/core/nextEdit/providers/MercuryCoderNextEditProvider.ts new file mode 100644 index 000000000..759381f39 --- /dev/null +++ b/core/nextEdit/providers/MercuryCoderNextEditProvider.ts @@ -0,0 +1,145 @@ +import { HelperVars } from "../../autocomplete/util/HelperVars.js"; +import { NEXT_EDIT_MODELS } from "../../llm/constants.js"; +import { MERCURY_SYSTEM_PROMPT, UNIQUE_TOKEN } from "../constants.js"; +import { + currentFileContentBlock, + editHistoryBlock, + recentlyViewedCodeSnippetsBlock, +} from "../templating/mercuryCoderNextEdit.js"; +import { + NEXT_EDIT_MODEL_TEMPLATES, + PromptTemplateRenderer, +} from "../templating/NextEditPromptEngine.js"; +import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js"; +import { BaseNextEditProvider } from "./BaseNextEditProvider.js"; + +export class MercuryCoderProvider extends BaseNextEditProvider { + private templateRenderer: PromptTemplateRenderer; + + constructor() { + super(NEXT_EDIT_MODELS.MERCURY_CODER); + + const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER]; + this.templateRenderer = new PromptTemplateRenderer(template.template); + } + + getSystemPrompt(): string { + return MERCURY_SYSTEM_PROMPT; + } + + getWindowSize() { + return { topMargin: 0, bottomMargin: 5 }; + } + + shouldInjectUniqueToken(): boolean { + return true; + } + + getUniqueToken(): string { + return UNIQUE_TOKEN; + } + + extractCompletion(message: string): string { + // Extract the code between the markdown code blocks. + return message.slice( + message.indexOf("```\n") + "```\n".length, + message.lastIndexOf("\n\n```"), + ); + } + + buildPromptContext(context: ModelSpecificContext): any { + return { + recentlyViewedCodeSnippets: + context.snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ + filepath: snip.filepath, + content: snip.content, + })) ?? [], + currentFileContent: context.helper.fileContents, + editableRegionStartLine: context.editableRegionStartLine, + editableRegionEndLine: context.editableRegionEndLine, + editDiffHistory: context.diffContext, + currentFilePath: context.helper.filepath, + }; + } + + async generatePrompts(context: ModelSpecificContext): Promise { + const promptCtx = this.buildPromptContext(context); + + const templateVars = { + recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( + promptCtx.recentlyViewedCodeSnippets, + ), + currentFileContent: currentFileContentBlock( + promptCtx.currentFileContent, + promptCtx.editableRegionStartLine, + promptCtx.editableRegionEndLine, + context.helper.pos, + ), + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), + currentFilePath: promptCtx.currentFilePath, + }; + + const userPromptContent = this.templateRenderer.render(templateVars); + + return [ + { + role: "system", + content: this.getSystemPrompt(), + }, + { + role: "user", + content: userPromptContent, + }, + ]; + } + + buildPromptMetadata(context: ModelSpecificContext): PromptMetadata { + const promptCtx = this.buildPromptContext(context); + + const templateVars = { + recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( + promptCtx.recentlyViewedCodeSnippets, + ), + currentFileContent: currentFileContentBlock( + promptCtx.currentFileContent, + promptCtx.editableRegionStartLine, + promptCtx.editableRegionEndLine, + context.helper.pos, + ), + editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory), + currentFilePath: promptCtx.currentFilePath, + }; + + const userPromptContent = this.templateRenderer.render(templateVars); + + return { + prompt: { + role: "user", + content: userPromptContent, + }, + userEdits: promptCtx.editDiffHistory.join("\n"), + userExcerpts: templateVars.currentFileContent, + }; + } + + calculateEditableRegion( + helper: HelperVars, + usingFullFileDiff: boolean, + ): { + editableRegionStartLine: number; + editableRegionEndLine: number; + } { + if (usingFullFileDiff) { + return this.calculateOptimalEditableRegion(helper, 512, "tokenizer"); + } else { + const { topMargin, bottomMargin } = this.getWindowSize(); + return { + editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0), + editableRegionEndLine: Math.min( + helper.pos.line + bottomMargin, + helper.fileLines.length - 1, + ), + }; + } + } +} diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index d8ca2226d..0d02a2f27 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -1,7 +1,4 @@ import Handlebars from "handlebars"; -import { Position } from "../.."; -import { SnippetPayload } from "../../autocomplete/snippets"; -import { HelperVars } from "../../autocomplete/util/HelperVars"; import { NEXT_EDIT_MODELS } from "../../llm/constants"; import { INSTINCT_USER_PROMPT_PREFIX, @@ -12,274 +9,39 @@ import { MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, } from "../constants"; -import { - InstinctTemplateVars, - MercuryTemplateVars, - NextEditTemplate, - PromptMetadata, - SystemPrompt, - TemplateVars, - UserPrompt, -} from "../types"; -import { - contextSnippetsBlock, - currentFileContentBlock as instinctCurrentFileContentBlock, - editHistoryBlock as instinctEditHistoryBlock, -} from "./instinct"; -import { - currentFileContentBlock, - editHistoryBlock, - recentlyViewedCodeSnippetsBlock, -} from "./mercuryCoderNextEdit"; -import { - insertCursorToken, - insertEditableRegionTokensWithStaticRange, -} from "./utils"; +import { NextEditTemplate, TemplateVars } from "../types"; -type TemplateRenderer = (vars: TemplateVars) => string; - -const NEXT_EDIT_MODEL_TEMPLATES: Record = { +// Keep the template registry +export const NEXT_EDIT_MODEL_TEMPLATES: Record< + NEXT_EDIT_MODELS, + NextEditTemplate +> = { "mercury-coder": { template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`, }, - "mercury-coder-nextedit": { - template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`, - }, instinct: { template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpt:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`, }, }; -function templateRendererOfModel( - modelName: NEXT_EDIT_MODELS, -): TemplateRenderer { - let template = NEXT_EDIT_MODEL_TEMPLATES[modelName]; +// Export a utility for providers to use +export class PromptTemplateRenderer { + private compiledTemplate: HandlebarsTemplateDelegate; + + constructor(template: string) { + this.compiledTemplate = Handlebars.compile(template); + } + + render(vars: TemplateVars): string { + return this.compiledTemplate(vars); + } +} + +// Keep for backward compatibility or remove if not needed +export function getTemplateForModel(modelName: NEXT_EDIT_MODELS): string { + const template = NEXT_EDIT_MODEL_TEMPLATES[modelName]; if (!template) { throw new Error(`Model ${modelName} is not supported for next edit.`); } - - const compiledTemplate = Handlebars.compile(template.template); - - return (vars: TemplateVars): string => { - return compiledTemplate(vars); - }; -} - -export async function renderPrompt( - helper: HelperVars, - ctx: any, -): Promise { - let modelName = helper.modelName as NEXT_EDIT_MODELS; - - // Validate that the modelName is actually a supported model. - if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) { - // Check if modelName includes any known model name as substring. - const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) => - modelName.includes(key), - ); - - if (matchingModel) { - modelName = matchingModel as NEXT_EDIT_MODELS; - } else { - throw new Error( - `${helper.modelName} is not yet supported for next edit.`, - ); - } - } - - const renderer = templateRendererOfModel(modelName); - let userEdits = ""; - let editedCodeWithTokens = ""; - let tv: TemplateVars; - - switch (modelName) { - case NEXT_EDIT_MODELS.MERCURY_CODER: { - userEdits = ctx.editDiffHistory; - - // editedCodeWithTokens = insertTokens( - // helper.fileContents.split("\n"), - // helper.pos, - // MERCURY_CURSOR, - // ); - - const mercuryCtx: MercuryTemplateVars = { - recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( - ctx.recentlyViewedCodeSnippets, - ), - currentFileContent: currentFileContentBlock( - ctx.currentFileContent, - ctx.editableRegionStartLine, - ctx.editableRegionEndLine, - helper.pos, - ), - editDiffHistory: editHistoryBlock(ctx.editDiffHistory), - currentFilePath: ctx.currentFilePath, - }; - - tv = mercuryCtx; - - editedCodeWithTokens = mercuryCtx.currentFileContent; - - break; - } - case NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT: { - userEdits = ctx.editDiffHistory; - - // editedCodeWithTokens = insertTokens( - // helper.fileContents.split("\n"), - // helper.pos, - // MERCURY_CURSOR, - // ); - - const mercuryCtx: MercuryTemplateVars = { - recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( - ctx.recentlyViewedCodeSnippets, - ), - currentFileContent: currentFileContentBlock( - ctx.currentFileContent, - ctx.editableRegionStartLine, - ctx.editableRegionEndLine, - helper.pos, - ), - editDiffHistory: editHistoryBlock(ctx.editDiffHistory), - currentFilePath: ctx.currentFilePath, - }; - - tv = mercuryCtx; - - editedCodeWithTokens = mercuryCtx.currentFileContent; - - break; - } - case NEXT_EDIT_MODELS.INSTINCT: { - userEdits = ctx.editDiffHistory; - - // editedCodeWithTokens = insertTokens( - // helper.fileContents.split("\n"), - // helper.pos, - // INSTINCT_USER_CURSOR_IS_HERE_TOKEN, - // ); - - const instinctCtx: InstinctTemplateVars = { - contextSnippets: contextSnippetsBlock(ctx.contextSnippets), - currentFileContent: instinctCurrentFileContentBlock( - ctx.currentFileContent, - ctx.windowStart, - ctx.windowEnd, - ctx.editableRegionStartLine, - ctx.editableRegionEndLine, - helper.pos, - ), - editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory), - currentFilePath: ctx.currentFilePath, - languageShorthand: ctx.languageShorthand, - }; - - tv = instinctCtx; - - editedCodeWithTokens = instinctCtx.currentFileContent; - - break; - } - default: - tv = {}; - break; - } - - return { - prompt: { - role: "user", - content: renderer(tv), - }, - userEdits, - userExcerpts: editedCodeWithTokens, - }; -} - -export function renderDefaultSystemPrompt(): SystemPrompt { - return { - role: "system", - content: [ - /* Identity forming */ - "You are an expert polyglot developer who is overseeing a junior developer write code in some language.", - "You are psychic as well, so you are an expert at reading minds just from what the junior has done.", - "As an expert, you know what the next edit of the junior is going to be, and you want to suggest it to save both of your's time.", - /* Action crash course */ - "An action is a change in code state that preserves the well-formedness of the code.", - "Well-formedness means that given a cursor location, the local syntax tree that the cursor is in is syntactically correct, and the semantic correctness in the current cursor's character location - 1.", - /* Input description */ - // 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.', - // "language is the language the code is written in.", - // "originalCode is the code state before the junior has taken some edit action.", - // "editedCode is the code state after the junior has taken some edit action.", - // "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.", - // "Measure the difference between the originalCode and editedCode inside the prompt, make your best understanding of what the junior wants to accomplish, and figure out what the junior will do next.", - 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "rootPathSnippets": string; "importDefinitionSnippets": string; "ideSnippets": string; "recentlyEditedRangeSnippets": string; "diffSnippets": string; "clipboardSnippets": string; "recentlyVisitedRangesSnippets": string; }.', - "rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.", - "recentlyEditedRange is the code that the junior has recently edited.", - "Do not guess what previous edit the junior has taken right before the request -- this is already given to you.", - "The next edit action can happen any location, so do not default to where the junior left off. A potential next edit action can happen before or after the junior edit.", - "The junior might want to add new code, delete existing code, or replace different parts of code.", - "The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.", - /* Output description */ - 'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.', - /* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/ - /* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */ - "actionType is a four-sentence description of the type of action the junior has taken and the reason why you determined that to be the case. Actually analyze the given edit.", - // "actionType is the type of action the junior has taken.", - "newCode is what the full code looks like after applying your nextEditContent.", - // "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.", - "Given the above definition of an action, you should prioritize fixing the following:", - "- Patterns and repetition in code.", - "- Static errors that the compiler of the language may return.", - "- The junior's code style.", - "If the junior has deleted some code, there's a good chance that the next edit will also be deletions.", - "If the junior has added some code, there's a good chance that the next edit will also be additions.", - "If the junior has performed an action on some part of the code, and you see similar code remaining, there's a good chance that the next edit will also target these remaining similar code.", - "Careful of language intricacies.", - // "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.", - "Do not reply in markdown.", - "Do not hallucinate.", - ].join(" "), - }; -} - -export function renderDefaultUserPrompt( - // originalCode: string, - // editedCode: string, - snippets: SnippetPayload, - helper: HelperVars, -): UserPrompt { - const userEdit = { - language: helper.lang, - rootPathSnippets: snippets.rootPathSnippets, - importDefinitionSnippets: snippets.importDefinitionSnippets, - ideSnippets: snippets.ideSnippets, - recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets, - diffSnippets: snippets.diffSnippets, - clipboardSnippets: snippets.clipboardSnippets, - recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets, - }; - - return { - role: "user", - content: `Your junior made the following edit: ${JSON.stringify(userEdit)}. What is the most possible next edit your junior ${helper.lang.name} developer will make?`, - }; -} - -function insertTokens( - lines: string[], - cursorPos: Position, - cursorToken: string, - editableRegionStart?: number, - editableRegionEnd?: number, -) { - const a = insertCursorToken(lines, cursorPos, cursorToken); - const b = insertEditableRegionTokensWithStaticRange( - a, - cursorPos, - editableRegionStart, - editableRegionEnd, - ); - return b.join("\n"); + return template.template; } diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index f72d3ca0b..7fd189ecc 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -1,243 +1,112 @@ -import { beforeEach, describe, expect, it } from "vitest"; -import { Position } from "../.."; -import { SnippetPayload } from "../../autocomplete/snippets"; -import { AutocompleteSnippetType } from "../../autocomplete/snippets/types"; -import { HelperVars } from "../../autocomplete/util/HelperVars"; +import { describe, expect, it } from "vitest"; import { NEXT_EDIT_MODELS } from "../../llm/constants"; import { - INSTINCT_USER_CURSOR_IS_HERE_TOKEN, INSTINCT_USER_PROMPT_PREFIX, MERCURY_CURRENT_FILE_CONTENT_CLOSE, MERCURY_CURRENT_FILE_CONTENT_OPEN, - MERCURY_CURSOR, MERCURY_EDIT_DIFF_HISTORY_CLOSE, MERCURY_EDIT_DIFF_HISTORY_OPEN, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, - MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE, - MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN, } from "../constants"; import { - renderDefaultSystemPrompt, - renderDefaultUserPrompt, - renderPrompt, + NEXT_EDIT_MODEL_TEMPLATES, + PromptTemplateRenderer, + getTemplateForModel, } from "./NextEditPromptEngine"; describe("NextEditPromptEngine", () => { - describe("renderPrompt", () => { - let mercuryHelper: HelperVars; - let instinctHelper: HelperVars; - let testHelper: HelperVars; - let unsupportedHelper: HelperVars; - let ctx: any; - - beforeEach(() => { - mercuryHelper = { - modelName: "inception/mercury-coder" as NEXT_EDIT_MODELS, - fileContents: "function test() {\n const a = 1;\n return a;\n}", - pos: { line: 1, character: 12 } as Position, - lang: { name: "typescript" }, - } as HelperVars; - instinctHelper = { - modelName: "continuedev/instinct" as NEXT_EDIT_MODELS, - fileContents: "function test() {\n const a = 1;\n return a;\n}", - pos: { line: 1, character: 12 } as Position, - lang: { name: "typescript" }, - } as HelperVars; - unsupportedHelper = { - modelName: "mistral/codestral" as NEXT_EDIT_MODELS, - fileContents: "function test() {\n const a = 1;\n return a;\n}", - pos: { line: 1, character: 12 } as Position, - lang: { name: "typescript" }, - } as HelperVars; - - ctx = { - recentlyViewedCodeSnippets: [ - { filepath: "/path/to/file1.ts", content: "const b = 2;" }, - ], - currentFileContent: "function test() {\n const a = 1;\n return a;\n}", - editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"], - editableRegionStartLine: 0, - editableRegionEndLine: 3, - userEdits: "Added constant a", - languageShorthand: "ts", - userExcerpts: "const a = 1;", - }; - }); - - it("should render mercury-coder prompt correctly", async () => { - const result = await renderPrompt(mercuryHelper, ctx); - - expect(result).toHaveProperty("prompt"); - expect(result.prompt.role).toBe("user"); - - const content = result.prompt.content; - expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN); - expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE); - expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN); - expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE); - expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN); - expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE); - expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN); - expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE); - - expect(result.userEdits).toBe(ctx.editDiffHistory); - expect(result.userExcerpts).toContain(MERCURY_CURSOR); - }); - - it("should render instinct prompt correctly", async () => { - // Create proper instinct context structure matching NextEditProvider.ts - const instinctCtx = { - contextSnippets: - "+++++ /path/to/context.ts\nconst contextVar = 'test';", - currentFileContent: instinctHelper.fileContents, - windowStart: 0, // Math.max(0, helper.pos.line - 25) - windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25) - editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window - editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window - editDiffHistory: [ - "diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }", - ], // unified diff - currentFilePath: "/path/to/file.ts", - languageShorthand: "ts", - }; - - const result = await renderPrompt(instinctHelper, instinctCtx); - console.log(result); - - expect(result).toHaveProperty("prompt"); - expect(result.prompt.role).toBe("user"); - expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX); - expect(result.prompt.content).toContain("### Context:"); - expect(result.prompt.content).toContain("### User Edits:"); - expect(result.prompt.content).toContain("### User Excerpt:"); - - expect(result.userEdits).toBe(instinctCtx.editDiffHistory); - expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN); - }); - - it("should throw error for unsupported model name", async () => { - await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow( - "mistral/codestral is not yet supported for next edit.", + describe("NEXT_EDIT_MODEL_TEMPLATES", () => { + it("should contain templates for all supported models", () => { + expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty( + NEXT_EDIT_MODELS.MERCURY_CODER, + ); + expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty( + NEXT_EDIT_MODELS.INSTINCT, ); }); - }); - describe("renderDefaultSystemPrompt", () => { - it("should return a system prompt with expected role and content", () => { - const result = renderDefaultSystemPrompt(); + it("mercury-coder template should contain expected tokens", () => { + const template = + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template; - expect(result.role).toBe("system"); - expect(result.content).toContain("You are an expert polyglot developer"); - expect(result.content).toContain("Do not hallucinate."); + expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN); + expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE); + expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN); + expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE); + expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN); + expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE); + expect(template).toContain("{{{recentlyViewedCodeSnippets}}}"); + expect(template).toContain("{{{currentFileContent}}}"); + expect(template).toContain("{{{editDiffHistory}}}"); + }); + + it("instinct template should contain expected tokens", () => { + const template = + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT].template; + + expect(template).toContain(INSTINCT_USER_PROMPT_PREFIX); + expect(template).toContain("### Context:"); + expect(template).toContain("### User Edits:"); + expect(template).toContain("### User Excerpt:"); + expect(template).toContain("{{{contextSnippets}}}"); + expect(template).toContain("{{{currentFileContent}}}"); + expect(template).toContain("{{{editDiffHistory}}}"); + expect(template).toContain("{{{currentFilePath}}}"); }); }); - describe("renderDefaultUserPrompt", () => { - it("should render a user prompt with the correct structure", () => { - const snippets: SnippetPayload = { - rootPathSnippets: [ - { - type: AutocompleteSnippetType.Code, - filepath: "", - content: "root path", - }, - ], - importDefinitionSnippets: [ - { - type: AutocompleteSnippetType.Code, - filepath: "", - content: "import def", - }, - ], - ideSnippets: [ - { - type: AutocompleteSnippetType.Code, - filepath: "", - content: "ide snippets", - }, - ], - recentlyEditedRangeSnippets: [ - { - type: AutocompleteSnippetType.Code, - filepath: "", - content: "recent edits", - }, - ], - diffSnippets: [ - { - type: AutocompleteSnippetType.Diff, - content: "diff snippets", - }, - ], - clipboardSnippets: [ - { - type: AutocompleteSnippetType.Clipboard, - content: "clipboard", - copiedAt: new Date().toISOString(), - }, - ], - recentlyVisitedRangesSnippets: [ - { - type: AutocompleteSnippetType.Code, - filepath: "", - content: "visited ranges", - }, - ], - recentlyOpenedFileSnippets: [ - { - type: AutocompleteSnippetType.Code, - filepath: "", - content: "recently opened files", - }, - ], - staticSnippet: [ - { - type: AutocompleteSnippetType.Static, - filepath: "", - content: "static content", - }, - ], - }; + describe("PromptTemplateRenderer", () => { + it("should render a template with provided variables", () => { + const template = "Hello {{{name}}}, you have {{{count}}} messages"; + const renderer = new PromptTemplateRenderer(template); - const helper: HelperVars = { - lang: { name: "typescript" }, - } as HelperVars; - - const result = renderDefaultUserPrompt(snippets, helper); - - expect(result.role).toBe("user"); - expect(result.content).toContain("Your junior made the following edit:"); - expect(result.content).toContain("typescript"); - expect(result.content).toContain("root path"); - }); - }); - - describe("insertTokens", () => { - it("should correctly insert cursor and editable region tokens", () => { - const mercuryHelper = { - modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS, - fileContents: "function test() {\n const a = 1;\n return a;\n}", - pos: { line: 1, character: 12 } as Position, - lang: { name: "typescript" }, - } as HelperVars; - - const ctx = { - recentlyViewedCodeSnippets: [ - { filepath: "/path/to/file1.ts", content: "const b = 2;" }, - ], - currentFileContent: "function test() {\n const a = 1;\n return a;\n}", - editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"], - editableRegionStartLine: 0, - editableRegionEndLine: 3, - userEdits: "Added constant a", - languageShorthand: "ts", - userExcerpts: "const a = 1;", - }; - - return renderPrompt(mercuryHelper, ctx).then((result) => { - expect(result.userExcerpts).toContain(MERCURY_CURSOR); + const result = renderer.render({ + name: "Alice", + count: "5", }); + + expect(result).toBe("Hello Alice, you have 5 messages"); + }); + + it("should handle missing variables gracefully", () => { + const template = "Hello {{{name}}}"; + const renderer = new PromptTemplateRenderer(template); + + const result = renderer.render({}); + + expect(result).toBe("Hello "); + }); + + it("should render complex templates correctly", () => { + const template = + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template; + const renderer = new PromptTemplateRenderer(template); + + const result = renderer.render({ + recentlyViewedCodeSnippets: "snippet1", + currentFileContent: "file content", + editDiffHistory: "diff history", + }); + + expect(result).toContain("snippet1"); + expect(result).toContain("file content"); + expect(result).toContain("diff history"); + }); + }); + + describe("getTemplateForModel", () => { + it("should return the correct template for a supported model", () => { + const template = getTemplateForModel(NEXT_EDIT_MODELS.MERCURY_CODER); + expect(template).toBe( + NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template, + ); + }); + + it("should throw an error for an unsupported model", () => { + expect(() => + getTemplateForModel("unsupported" as NEXT_EDIT_MODELS), + ).toThrow("Model unsupported is not supported for next edit."); }); }); }); diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index d30d803e0..78ca343ae 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -5,7 +5,9 @@ import { RangeInFile, TabAutocompleteOptions, } from "../"; +import { SnippetPayload } from "../autocomplete/snippets"; import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types"; +import { HelperVars } from "../autocomplete/util/HelperVars"; export type RecentlyEditedRange = RangeInFile & { timestamp: number; @@ -104,3 +106,36 @@ export interface MercuryTemplateVars extends TemplateVars { editDiffHistory: string; // could be a singe large unified diff currentFilePath: string; } + +/** + * Context object containing all necessary information for model-specific operations. + */ +export interface ModelSpecificContext { + helper: HelperVars; + snippetPayload: SnippetPayload; + editableRegionStartLine: number; + editableRegionEndLine: number; + diffContext: string[]; + autocompleteContext: string; + historyDiff?: string; + workspaceDirs?: string[]; +} + +/** + * Configuration for editable region calculation. + */ +export interface EditableRegionConfig { + usingFullFileDiff?: boolean; + maxTokens?: number; + topMargin?: number; + bottomMargin?: number; +} + +/** + * Configuration for prompt generation. + */ +export interface PromptConfig { + includeHistory?: boolean; + includeRecentEdits?: boolean; + maxContextSnippets?: number; +} diff --git a/core/nextEdit/utils.ts b/core/nextEdit/utils.ts index 07ec52a19..15f2e6339 100644 --- a/core/nextEdit/utils.ts +++ b/core/nextEdit/utils.ts @@ -1,4 +1,5 @@ import { DiffLine } from ".."; +import { NEXT_EDIT_MODELS } from "../llm/constants"; export function isNextEditTest(): boolean { const enabled = process.env.NEXT_EDIT_TEST_ENABLED; @@ -21,3 +22,11 @@ export function isWhitespaceOnlyDeletion(diffLines: DiffLine[]): boolean { (diff.line.trim() === "" || /^\s+$/.test(diff.line)), ); } + +export function convertNextEditModelNameToEnum( + modelName: string, +): NEXT_EDIT_MODELS | undefined { + const nextEditModels = Object.values(NEXT_EDIT_MODELS); + + return nextEditModels.find((model) => modelName.includes(model)); +} diff --git a/core/nextEdit/utils.vitest.ts b/core/nextEdit/utils.vitest.ts index b5494a525..abbab499b 100644 --- a/core/nextEdit/utils.vitest.ts +++ b/core/nextEdit/utils.vitest.ts @@ -1,6 +1,11 @@ import { describe, expect, test, vi } from "vitest"; import { DiffLine } from ".."; -import { isNextEditTest, isWhitespaceOnlyDeletion } from "./utils"; +import { NEXT_EDIT_MODELS } from "../llm/constants"; +import { + convertNextEditModelNameToEnum, + isNextEditTest, + isWhitespaceOnlyDeletion, +} from "./utils"; describe("isNextEditTest", () => { test("returns true when NEXT_EDIT_TEST_ENABLED is 'true'", () => { @@ -57,3 +62,35 @@ describe("isWhitespaceOnlyDeletion", () => { expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true); }); }); + +describe("convertNextEditModelNameToEnum", () => { + test("returns correct enum for exact matches", () => { + Object.values(NEXT_EDIT_MODELS).forEach((model) => { + expect(convertNextEditModelNameToEnum(model)).toBe(model); + }); + }); + + test("returns correct enum when model name is contained in a longer string", () => { + expect(convertNextEditModelNameToEnum("inception/mercury-coder")).toBe( + NEXT_EDIT_MODELS.MERCURY_CODER, + ); + expect(convertNextEditModelNameToEnum("blah/instinct")).toBe( + NEXT_EDIT_MODELS.INSTINCT, + ); + }); + + test("returns undefined for non-matching model names", () => { + expect(convertNextEditModelNameToEnum("unknown-model")).toBeUndefined(); + expect(convertNextEditModelNameToEnum("random-string")).toBeUndefined(); + expect(convertNextEditModelNameToEnum("")).toBeUndefined(); + }); + + test("returns first match when multiple models could match", () => { + const modelName = "model-that-contains-multiple-matches"; + const result = convertNextEditModelNameToEnum(modelName); + + if (result !== undefined) { + expect(Object.values(NEXT_EDIT_MODELS)).toContain(result); + } + }); +}); From 06f734cfe8aeb2947a3353527d9bb7e3aaa052ef Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 22 Aug 2025 15:30:18 -0700 Subject: [PATCH 18/38] fix: name check --- .github/workflows/preview.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index b68a65efd..289381034 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -20,7 +20,7 @@ jobs: - id: check working-directory: . run: | - if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then + if [[ "${{ github.event.release.tag_name }}" == v1.3.*-vscode ]]; then echo "should_run=true" >> $GITHUB_OUTPUT else echo "should_run=false" >> $GITHUB_OUTPUT From 229b6e13708fe7a94361e7d466153fdca20a7577 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Fri, 22 Aug 2025 16:44:52 -0700 Subject: [PATCH 19/38] Update package.json --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 5b92de1f1..af10a7043 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.3.0", + "version": "1.3.1", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From ea2fac7c2cada49be7968b6257b47af37585f988 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 16:52:04 -0700 Subject: [PATCH 20/38] feat: --prompt flag --- extensions/cli/package-lock.json | 1 + extensions/cli/src/__mocks__/args.ts | 2 + extensions/cli/src/args.prompt.test.ts | 49 +++++++ extensions/cli/src/args.ts | 47 +++++-- extensions/cli/src/commands/chat.ts | 12 +- extensions/cli/src/e2e/basic-commands.test.ts | 1 + extensions/cli/src/onboarding.ts | 4 +- extensions/cli/src/services/ConfigService.ts | 4 +- extensions/cli/src/shared-options.ts | 11 ++ extensions/cli/src/systemMessage.ts | 4 +- extensions/cli/src/ui/AppRoot.tsx | 1 + extensions/cli/src/ui/TUIChat.tsx | 3 + extensions/cli/src/ui/hooks/useChat.ts | 16 ++- extensions/cli/src/ui/hooks/useChat.types.ts | 1 + extensions/cli/src/ui/index.ts | 3 + .../cli/src/util/promptProcessor.test.ts | 128 ++++++++++++++++++ extensions/cli/src/util/promptProcessor.ts | 39 ++++++ 17 files changed, 300 insertions(+), 26 deletions(-) create mode 100644 extensions/cli/src/args.prompt.test.ts create mode 100644 extensions/cli/src/util/promptProcessor.test.ts create mode 100644 extensions/cli/src/util/promptProcessor.ts diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index 1a667013a..19e1f2762 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -276,6 +276,7 @@ "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.14", "@types/json-schema": "^7.0.15", + "@types/node": "^24.3.0", "cross-env": "^7.0.3", "semantic-release": "^24.2.7", "ts-jest": "^29.2.3", diff --git a/extensions/cli/src/__mocks__/args.ts b/extensions/cli/src/__mocks__/args.ts index b0d25ffad..07e63d652 100644 --- a/extensions/cli/src/__mocks__/args.ts +++ b/extensions/cli/src/__mocks__/args.ts @@ -1,3 +1,5 @@ import { vi } from "vitest"; +export const processPromptOrRule = vi.fn<(spec: string) => Promise>(); export const processRule = vi.fn<(rule: string) => Promise>(); +export const processPrompt = vi.fn<(prompt: string) => Promise>(); diff --git a/extensions/cli/src/args.prompt.test.ts b/extensions/cli/src/args.prompt.test.ts new file mode 100644 index 000000000..aa581559e --- /dev/null +++ b/extensions/cli/src/args.prompt.test.ts @@ -0,0 +1,49 @@ +import { describe, it, expect, beforeEach } from "vitest"; + +import { parseArgs, processPrompt } from "./args.js"; + +describe("args --prompt flag", () => { + beforeEach(() => { + // Reset process.argv for each test + process.argv = ["node", "script.js"]; + }); + + it("should parse single prompt from --prompt flag", () => { + process.argv = ["node", "script.js", "--prompt", "my-prompt"]; + const result = parseArgs(); + expect(result.prompts).toEqual(["my-prompt"]); + }); + + it("should parse multiple prompts from multiple --prompt flags", () => { + process.argv = ["node", "script.js", "--prompt", "prompt1", "--prompt", "prompt2"]; + const result = parseArgs(); + expect(result.prompts).toEqual(["prompt1", "prompt2"]); + }); + + it("should handle mixed flags including --prompt", () => { + process.argv = ["node", "script.js", "--config", "myconfig", "--prompt", "myprompt", "--resume"]; + const result = parseArgs(); + expect(result.configPath).toBe("myconfig"); + expect(result.prompts).toEqual(["myprompt"]); + expect(result.resume).toBe(true); + }); + + it("should not include --prompt value in non-flag arguments", () => { + process.argv = ["node", "script.js", "--prompt", "prompt-value", "actual-prompt"]; + const result = parseArgs(); + expect(result.prompts).toEqual(["prompt-value"]); + expect(result.prompt).toBe("actual-prompt"); + }); + + it("should handle both --rule and --prompt flags", () => { + process.argv = ["node", "script.js", "--rule", "my-rule", "--prompt", "my-prompt"]; + const result = parseArgs(); + expect(result.rules).toEqual(["my-rule"]); + expect(result.prompts).toEqual(["my-prompt"]); + }); + + it("should process direct string content", async () => { + const result = await processPrompt("This is a direct prompt"); + expect(result).toBe("This is a direct prompt"); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/args.ts b/extensions/cli/src/args.ts index 1d46ee40f..35f97a0f6 100644 --- a/extensions/cli/src/args.ts +++ b/extensions/cli/src/args.ts @@ -12,6 +12,7 @@ export interface CommandLineArgs { resume?: boolean; // Resume from last session readonly?: boolean; // Start in plan mode (backward compatibility) rules?: string[]; // Array of rule specifications + prompts?: string[]; // Array of prompt specifications format?: "json"; // Output format for headless mode } @@ -83,31 +84,31 @@ async function loadRuleFromHub(slug: string): Promise { } /** - * Process a rule specification and return its content - * @param ruleSpec - Can be a file path, hub slug, or direct string content - * @returns The processed rule content + * Process a specification (rule or prompt) and return its content + * @param spec - Can be a file path, hub slug, or direct string content + * @returns The processed content */ -export async function processRule(ruleSpec: string): Promise { +export async function processPromptOrRule(spec: string): Promise { // If it looks like a hub slug (contains / but doesn't start with . or /) if ( - ruleSpec.includes("/") && - !ruleSpec.startsWith(".") && - !ruleSpec.startsWith("/") + spec.includes("/") && + !spec.startsWith(".") && + !spec.startsWith("/") ) { - return await loadRuleFromHub(ruleSpec); + return await loadRuleFromHub(spec); } // If it looks like a file path (contains . or / or ends with common file extensions) if ( - ruleSpec.includes(".") || - ruleSpec.includes("/") || - ruleSpec.includes("\\") + spec.includes(".") || + spec.includes("/") || + spec.includes("\\") ) { - return loadRuleFromFile(ruleSpec); + return loadRuleFromFile(spec); } // Otherwise, treat it as direct string content - return ruleSpec; + return spec; } /** @@ -115,6 +116,7 @@ export async function processRule(ruleSpec: string): Promise { * @deprecated Most functionality has been moved to services. This is only kept for backward compatibility. * @returns Parsed command line arguments */ +/* eslint-disable */ export function parseArgs(): CommandLineArgs { const args = process.argv.slice(2); @@ -170,8 +172,25 @@ export function parseArgs(): CommandLineArgs { } } + // Get prompts from --prompt flags (can be specified multiple times) + const promptIndices: number[] = []; + for (let i = 0; i < args.length; i++) { + if (args[i] === "--prompt") { + promptIndices.push(i); + } + } + + if (promptIndices.length > 0) { + result.prompts = []; + for (const promptIndex of promptIndices) { + if (promptIndex + 1 < args.length) { + result.prompts.push(args[promptIndex + 1]); + } + } + } + // Find the last argument that's not a flag or a flag value - const flagsWithValues = ["--config", "--org", "--rule", "--format"]; + const flagsWithValues = ["--config", "--org", "--rule", "--prompt", "--format"]; const nonFlagArgs = args.filter((arg, index) => { // Skip flags (starting with --) if (arg.startsWith("--") || arg === "-p") return false; diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 4b2638fd8..73d7a1747 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -78,6 +78,7 @@ export interface ChatOptions extends ExtendedCommandOptions { headless?: boolean; resume?: boolean; rule?: string[]; // Array of rule specifications + prompt?: string[]; // Array of prompt specifications format?: "json"; // Output format for headless mode silent?: boolean; // Strip tags and excess whitespace org?: string; // Organization slug to use for this session @@ -388,17 +389,21 @@ async function runHeadlessMode( compactionIndex = findCompactionIndex(chatHistory); } + // Handle additional prompts from --prompt flags + const { processAndCombinePrompts } = await import("../util/promptProcessor.js"); + const initialUserInput = await processAndCombinePrompts(options.prompt, prompt); + let isFirstMessage = true; while (true) { // When in headless mode, don't ask for user input - if (!isFirstMessage && prompt && options.headless) { + if (!isFirstMessage && initialUserInput && options.headless) { break; } // Get user input const userInput = - isFirstMessage && prompt - ? prompt + isFirstMessage && initialUserInput + ? initialUserInput : readlineSync.question(`\n${chalk.bold.green("You:")} `); isFirstMessage = false; @@ -465,6 +470,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { configPath: options.config, organizationSlug: options.org, additionalRules: options.rule, + additionalPrompts: options.prompt, toolPermissionOverrides: permissionOverrides, skipOnboarding: true, }; diff --git a/extensions/cli/src/e2e/basic-commands.test.ts b/extensions/cli/src/e2e/basic-commands.test.ts index 0b054f912..c738bea3e 100644 --- a/extensions/cli/src/e2e/basic-commands.test.ts +++ b/extensions/cli/src/e2e/basic-commands.test.ts @@ -40,6 +40,7 @@ describe("E2E: Basic Commands", () => { expect(result.stdout).toContain("--readonly"); expect(result.stdout).toContain("--auto"); expect(result.stdout).toContain("--rule "); + expect(result.stdout).toContain("--prompt "); }); it("should show available commands", async () => { diff --git a/extensions/cli/src/onboarding.ts b/extensions/cli/src/onboarding.ts index 36240b9a9..ace43f761 100644 --- a/extensions/cli/src/onboarding.ts +++ b/extensions/cli/src/onboarding.ts @@ -7,7 +7,7 @@ import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; import chalk from "chalk"; import * as readlineSync from "readline-sync"; -import { processRule } from "./args.js"; +import { processPromptOrRule } from "./args.js"; import { AuthConfig, isAuthenticated, login } from "./auth/workos.js"; import { initialize } from "./config.js"; import { env } from "./env.js"; @@ -239,7 +239,7 @@ async function injectRulesIntoConfig( const processedRules: string[] = []; for (const ruleSpec of rules) { try { - const processedRule = await processRule(ruleSpec); + const processedRule = await processPromptOrRule(ruleSpec); processedRules.push(processedRule); } catch (error: any) { console.warn( diff --git a/extensions/cli/src/services/ConfigService.ts b/extensions/cli/src/services/ConfigService.ts index c1fc706a9..f3038eab7 100644 --- a/extensions/cli/src/services/ConfigService.ts +++ b/extensions/cli/src/services/ConfigService.ts @@ -1,7 +1,7 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; -import { processRule } from "../args.js"; +import { processPromptOrRule } from "../args.js"; import { AuthConfig, loadAuthConfig } from "../auth/workos.js"; import { logger } from "../util/logger.js"; @@ -155,7 +155,7 @@ export class ConfigService for (const ruleSpec of rules) { try { - const processedRule = await processRule(ruleSpec); + const processedRule = await processPromptOrRule(ruleSpec); processedRules.push(processedRule); } catch (error: any) { logger.warn(`Failed to process rule "${ruleSpec}": ${error.message}`); diff --git a/extensions/cli/src/shared-options.ts b/extensions/cli/src/shared-options.ts index 6a68f29b1..9c61e9fa1 100644 --- a/extensions/cli/src/shared-options.ts +++ b/extensions/cli/src/shared-options.ts @@ -24,6 +24,16 @@ export function addCommonOptions(command: Command): Command { }, [] as string[], ) + .option( + "--prompt ", + "Add to the initial user message (can be a file path, hub slug, or string content). Can be specified multiple times.", + (value: string, previous: string[] | undefined) => { + const array = Array.isArray(previous) ? previous : []; + array.push(value); + return array; + }, + [] as string[], + ) .option( "--allow ", "Allow specified tool (overrides default policies). Can be specified multiple times.", @@ -70,6 +80,7 @@ export function mergeParentOptions(parentCommand: Command, options: any): any { "tools", "verbose", "rule", + "prompt", "allow", "ask", "exclude", diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index 1f09ff5c6..b48a4f151 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -5,7 +5,7 @@ import * as path from "path"; import pkg from "ignore-walk"; import { Minimatch } from "minimatch"; -import { processRule } from "./args.js"; +import { processPromptOrRule } from "./args.js"; import { serviceContainer } from "./services/ServiceContainer.js"; import { ConfigServiceState, SERVICE_NAMES } from "./services/types.js"; const { WalkerSync } = pkg; @@ -150,7 +150,7 @@ export async function constructSystemMessage( if (additionalRules && additionalRules.length > 0) { for (const ruleSpec of additionalRules) { try { - const processedRule = await processRule(ruleSpec); + const processedRule = await processPromptOrRule(ruleSpec); processedRules.push(processedRule); } catch (error: any) { console.warn( diff --git a/extensions/cli/src/ui/AppRoot.tsx b/extensions/cli/src/ui/AppRoot.tsx index 8f2c1c193..f6cef3c20 100644 --- a/extensions/cli/src/ui/AppRoot.tsx +++ b/extensions/cli/src/ui/AppRoot.tsx @@ -9,6 +9,7 @@ interface AppRootProps { initialPrompt?: string; resume?: boolean; additionalRules?: string[]; + additionalPrompts?: string[]; } /** diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 6ef19ca08..e1a93137d 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -36,6 +36,7 @@ interface TUIChatProps { initialPrompt?: string; resume?: boolean; additionalRules?: string[]; + additionalPrompts?: string[]; } const TUIChat: React.FC = ({ @@ -44,6 +45,7 @@ const TUIChat: React.FC = ({ initialPrompt, resume, additionalRules, + additionalPrompts, }) => { // Check if we're in remote mode const isRemoteMode = useMemo(() => { @@ -126,6 +128,7 @@ const TUIChat: React.FC = ({ initialPrompt, resume, additionalRules, + additionalPrompts, onShowConfigSelector: () => navigateTo("config"), onShowModelSelector: () => navigateTo("model"), onShowMCPSelector: () => navigateTo("mcp"), diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 4a75c9a1f..fca26ef4c 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -42,6 +42,7 @@ export function useChat({ initialPrompt, resume, additionalRules, + additionalPrompts, onShowConfigSelector, onShowModelSelector, onShowMCPSelector, @@ -163,10 +164,19 @@ export function useChat({ useEffect(() => { // Only handle initial prompt after chat history is initialized // This prevents race conditions where the prompt runs before system message is loaded - if (initialPrompt && isChatHistoryInitialized) { - handleUserMessage(initialPrompt); + if ((initialPrompt || (additionalPrompts && additionalPrompts.length > 0)) && isChatHistoryInitialized) { + const processPrompts = async () => { + const { processAndCombinePrompts } = await import("../../util/promptProcessor.js"); + const finalMessage = await processAndCombinePrompts(additionalPrompts, initialPrompt); + + if (finalMessage) { + handleUserMessage(finalMessage); + } + }; + + processPrompts(); } - }, [initialPrompt, isChatHistoryInitialized]); + }, [initialPrompt, additionalPrompts, isChatHistoryInitialized]); const executeStreamingResponse = async ( newHistory: ChatCompletionMessageParam[], diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index f0cca4978..fa752fed8 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -11,6 +11,7 @@ export interface UseChatProps { initialPrompt?: string; resume?: boolean; additionalRules?: string[]; + additionalPrompts?: string[]; onShowConfigSelector: () => void; onShowMCPSelector: () => void; onShowModelSelector?: () => void; diff --git a/extensions/cli/src/ui/index.ts b/extensions/cli/src/ui/index.ts index e75f9aa91..eb4cc77ec 100644 --- a/extensions/cli/src/ui/index.ts +++ b/extensions/cli/src/ui/index.ts @@ -15,6 +15,7 @@ interface StartTUIChatOptions { configPath?: string; organizationSlug?: string; additionalRules?: string[]; + additionalPrompts?: string[]; toolPermissionOverrides?: { allow?: string[]; ask?: string[]; @@ -33,6 +34,7 @@ export async function startTUIChat( configPath, organizationSlug, additionalRules, + additionalPrompts, toolPermissionOverrides, skipOnboarding, customStdin, @@ -64,6 +66,7 @@ export async function startTUIChat( initialPrompt, resume, additionalRules, + additionalPrompts, }), }), renderOptions, diff --git a/extensions/cli/src/util/promptProcessor.test.ts b/extensions/cli/src/util/promptProcessor.test.ts new file mode 100644 index 000000000..2bc28004d --- /dev/null +++ b/extensions/cli/src/util/promptProcessor.test.ts @@ -0,0 +1,128 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import * as args from "../args.js"; + +import { processAndCombinePrompts } from "./promptProcessor.js"; + +// Mock the args module +vi.mock("../args.js", () => ({ + processPromptOrRule: vi.fn(), +})); + +// Mock the logger +vi.mock("./logger.js", () => ({ + logger: { + warn: vi.fn(), + }, +})); + +describe("promptProcessor", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("processAndCombinePrompts", () => { + it("should return initial prompt when no additional prompts", async () => { + const result = await processAndCombinePrompts(undefined, "initial"); + expect(result).toBe("initial"); + }); + + it("should return initial prompt when empty additional prompts array", async () => { + const result = await processAndCombinePrompts([], "initial"); + expect(result).toBe("initial"); + }); + + it("should return undefined when no prompts at all", async () => { + const result = await processAndCombinePrompts(); + expect(result).toBeUndefined(); + }); + + it("should process single additional prompt without initial", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule.mockResolvedValue("processed prompt"); + + const result = await processAndCombinePrompts(["prompt1"]); + + expect(mockProcessPromptOrRule).toHaveBeenCalledWith("prompt1"); + expect(result).toBe("processed prompt"); + }); + + it("should combine multiple processed prompts", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule + .mockResolvedValueOnce("first prompt") + .mockResolvedValueOnce("second prompt"); + + const result = await processAndCombinePrompts(["prompt1", "prompt2"]); + + expect(mockProcessPromptOrRule).toHaveBeenCalledTimes(2); + expect(mockProcessPromptOrRule).toHaveBeenNthCalledWith(1, "prompt1"); + expect(mockProcessPromptOrRule).toHaveBeenNthCalledWith(2, "prompt2"); + expect(result).toBe("first prompt\n\nsecond prompt"); + }); + + it("should combine processed prompts with initial prompt", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule + .mockResolvedValueOnce("processed1") + .mockResolvedValueOnce("processed2"); + + const result = await processAndCombinePrompts( + ["prompt1", "prompt2"], + "initial", + ); + + expect(result).toBe("processed1\n\nprocessed2\n\ninitial"); + }); + + it("should handle processing errors and continue with successful ones", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule + .mockResolvedValueOnce("success1") + .mockRejectedValueOnce(new Error("processing failed")) + .mockResolvedValueOnce("success2"); + + const result = await processAndCombinePrompts([ + "good1", + "bad", + "good2", + ]); + + expect(mockProcessPromptOrRule).toHaveBeenCalledTimes(3); + expect(result).toBe("success1\n\nsuccess2"); + }); + + it("should return initial prompt when all processing fails", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule + .mockRejectedValueOnce(new Error("fail1")) + .mockRejectedValueOnce(new Error("fail2")); + + const result = await processAndCombinePrompts(["bad1", "bad2"], "initial"); + + expect(result).toBe("initial"); + }); + + it("should return undefined when all processing fails and no initial", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule.mockRejectedValue(new Error("processing failed")); + + const result = await processAndCombinePrompts(["bad"]); + + expect(result).toBeUndefined(); + }); + + it("should warn when processing fails", async () => { + const mockProcessPromptOrRule = vi.mocked(args.processPromptOrRule); + mockProcessPromptOrRule.mockRejectedValue(new Error("test error")); + + const { logger } = await import("./logger.js"); + + await processAndCombinePrompts(["bad-prompt"]); + + expect(logger.warn).toHaveBeenCalledWith( + 'Failed to process prompt "bad-prompt": test error', + ); + }); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/util/promptProcessor.ts b/extensions/cli/src/util/promptProcessor.ts new file mode 100644 index 000000000..ef36bf6ea --- /dev/null +++ b/extensions/cli/src/util/promptProcessor.ts @@ -0,0 +1,39 @@ +import { processPromptOrRule } from "../args.js"; +import { logger } from "./logger.js"; + +/** + * Process additional prompts from --prompt flags and combine with initial prompt + * @param additionalPrompts - Array of prompt specifications to process + * @param initialPrompt - Optional initial prompt to combine with + * @returns Combined prompt string or undefined if no prompts + */ +export async function processAndCombinePrompts( + additionalPrompts?: string[], + initialPrompt?: string, +): Promise { + if (!additionalPrompts || additionalPrompts.length === 0) { + return initialPrompt; + } + + const processedPrompts: string[] = []; + + for (const promptSpec of additionalPrompts) { + try { + const processed = await processPromptOrRule(promptSpec); + processedPrompts.push(processed); + } catch (error: any) { + logger.warn( + `Failed to process prompt "${promptSpec}": ${error.message}`, + ); + } + } + + if (processedPrompts.length === 0) { + return initialPrompt; + } + + const combinedPrompts = processedPrompts.join("\n\n"); + return initialPrompt + ? `${combinedPrompts}\n\n${initialPrompt}` + : combinedPrompts; +} \ No newline at end of file From 5955488430c2b324ab7752b8cf4101a9f2dc3b2e Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 17:28:55 -0700 Subject: [PATCH 21/38] fix: jb tests --- .github/actions/run-jetbrains-tests/action.yml | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/actions/run-jetbrains-tests/action.yml b/.github/actions/run-jetbrains-tests/action.yml index e05437f77..f3fbe7eea 100644 --- a/.github/actions/run-jetbrains-tests/action.yml +++ b/.github/actions/run-jetbrains-tests/action.yml @@ -135,14 +135,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() }} From 5b83e477741c9965dc508be72ca6ea814672c378 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 18:16:13 -0700 Subject: [PATCH 22/38] fix: pin to ffmpeg version 7.1 --- .github/actions/run-jetbrains-tests/action.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/actions/run-jetbrains-tests/action.yml b/.github/actions/run-jetbrains-tests/action.yml index f3fbe7eea..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 From ee79bff04835697fee1b2d90d49513f1a3b8fcf8 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 19:01:27 -0700 Subject: [PATCH 23/38] fix: truncate Read tool output to avoid context overflow --- extensions/cli/src/tools/readFile.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index f7258a3bf..37a15639c 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: ${ From 3585250333460905c8e50a1699ed55178c83271b Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 20:45:35 -0700 Subject: [PATCH 24/38] fix: workflow dispatch default proper type --- .github/workflows/main.yaml | 2 +- .github/workflows/preview.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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/preview.yaml b/.github/workflows/preview.yaml index b68a65efd..03078f6d4 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: From 1000694b639b31715c344097d54d9edcee6fc7fc Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 20:47:44 -0700 Subject: [PATCH 25/38] fix: vaildate aliases fix core --- extensions/cli/validate-aliases.mjs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) 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]); } } From 4c829d776bc58f58e9ea35e45068a217011b5505 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 21:13:09 -0700 Subject: [PATCH 26/38] fix: auto compaction between tool calls --- extensions/cli/src/commands/chat.ts | 111 +++++----- .../streamChatResponse.autoCompaction.test.ts | 208 ++++++++++++++++++ .../src/streamChatResponse.autoCompaction.ts | 176 +++++++++++++++ extensions/cli/src/streamChatResponse.ts | 19 ++ .../cli/src/streamChatResponse.types.ts | 1 + .../cli/src/ui/hooks/useChat.helpers.ts | 84 ++----- .../src/ui/hooks/useChat.stream.helpers.ts | 10 + 7 files changed, 491 insertions(+), 118 deletions(-) create mode 100644 extensions/cli/src/streamChatResponse.autoCompaction.test.ts create mode 100644 extensions/cli/src/streamChatResponse.autoCompaction.ts diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 6e10b5350..45726d49d 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -28,7 +28,6 @@ import { logger } from "../util/logger.js"; import { calculateContextUsagePercentage, countChatHistoryTokens, - getAutoCompactMessage, shouldAutoCompact, } from "../util/tokenizer.js"; @@ -160,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, @@ -168,60 +167,68 @@ 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(`\n${getAutoCompactMessage(model)}`)); - } 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/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/streamChatResponse.autoCompaction.test.ts new file mode 100644 index 000000000..ce67f8660 --- /dev/null +++ b/extensions/cli/src/streamChatResponse.autoCompaction.test.ts @@ -0,0 +1,208 @@ +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, + }); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.ts b/extensions/cli/src/streamChatResponse.autoCompaction.ts new file mode 100644 index 000000000..087896d2e --- /dev/null +++ b/extensions/cli/src/streamChatResponse.autoCompaction.ts @@ -0,0 +1,176 @@ +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>; + 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/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index b7fc4417b..2b1113bc9 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -7,10 +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 { - getAutoCompactMessage, - shouldAutoCompact, -} from "../../util/tokenizer.js"; import { DisplayMessage } from "../types.js"; import { SlashCommandResult } from "./useChat.types.js"; @@ -281,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, @@ -295,69 +291,25 @@ export async function handleAutoCompaction({ currentChatHistory: ChatCompletionMessageParam[]; currentCompactionIndex: number | null; }> { - if (!model || !shouldAutoCompact(chatHistory, model)) { - return { - currentChatHistory: chatHistory, - currentCompactionIndex: compactionIndex, - }; + if (!llmApi) { + throw new Error("LLM API is not available for auto-compaction"); } - logger.info("Auto-compacting triggered in TUI mode"); + const { handleAutoCompaction: coreAutoCompaction } = await import( + "../../streamChatResponse.autoCompaction.js" + ); - setMessages((prev) => [ - ...prev, - { - role: "system", - content: getAutoCompactMessage(model), - 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, + }, + ]); + }, }; } From 04e35c5d52a5cf49e0291fd1f1aa015fa9963b2f Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 21:48:41 -0700 Subject: [PATCH 27/38] fix: prune before compacting --- .../cli/src/compaction.infiniteLoop.test.ts | 126 +++++++++++++ .../src/compaction.pruneLastMessage.test.ts | 169 ++++++++++++++++++ extensions/cli/src/compaction.ts | 67 ++++++- 3 files changed, 360 insertions(+), 2 deletions(-) create mode 100644 extensions/cli/src/compaction.infiniteLoop.test.ts create mode 100644 extensions/cli/src/compaction.pruneLastMessage.test.ts diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts new file mode 100644 index 000000000..24daf01a9 --- /dev/null +++ b/extensions/cli/src/compaction.infiniteLoop.test.ts @@ -0,0 +1,126 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import { describe, it, expect, vi } from "vitest"; +import { ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; + +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?.(); + 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?.(); + 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?.(); + 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(); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/compaction.pruneLastMessage.test.ts b/extensions/cli/src/compaction.pruneLastMessage.test.ts new file mode 100644 index 000000000..ae9c9866c --- /dev/null +++ b/extensions/cli/src/compaction.pruneLastMessage.test.ts @@ -0,0 +1,169 @@ +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 preserve history ending with assistant message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual(history); + }); + + it("should preserve history ending with tool message", () => { + 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(history); + }); + + it("should prune user messages at the end", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + { role: "user", content: "Another question" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]); + }); + + it("should prune multiple user messages at the end", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + { role: "user", content: "Question 1" }, + { role: "user", content: "Question 2" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there" }, + ]); + }); + + it("should handle tool call sequences correctly", () => { + 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 return only system message when no assistant/tool messages exist", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + { role: "user", content: "Hello" }, + { role: "user", content: "Another message" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + ]); + }); + + it("should return empty array when no system message and no assistant/tool messages", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "user", content: "Hello" }, + { role: "user", content: "Another message" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([]); + }); + + it("should handle history with only system message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "system", content: "System" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + ]); + }); + + it("should handle history with only assistant message", () => { + const history: ChatCompletionMessageParam[] = [ + { role: "assistant", content: "Hello" }, + ]; + + const result = pruneLastMessage(history); + expect(result).toEqual([ + { role: "assistant", content: "Hello" }, + ]); + }); + + 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" }, + ]); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index c60f814a7..2e40d1486 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,34 @@ 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; + } + + 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, From ca057569d588e305b5693e38a994fc0b2cc1dba4 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 22 Aug 2025 21:49:54 -0700 Subject: [PATCH 28/38] chore: format --- extensions/cli/build.mjs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) 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); From decd562a89dd6c61d26d444c6949681c035e0dbb Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Aug 2025 10:32:52 -0700 Subject: [PATCH 29/38] feat: info slash command --- extensions/cli/src/commands/commands.ts | 7 +- extensions/cli/src/session.ts | 2 +- extensions/cli/src/slashCommands.test.ts | 279 +++++++++++++---------- extensions/cli/src/slashCommands.ts | 59 +++++ 4 files changed, 223 insertions(+), 124 deletions(-) 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/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..8d5ae0e70 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -1,147 +1,182 @@ -// 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: " }], + version: "1.0.0" }; 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"); + + (isAuthenticated as MockedFunction).mockReturnValue(false); + (services.config.getState as MockedFunction).mockReturnValue({ + config: null, + configPath: "/test/config.yaml" + } as ConfigServiceState); - 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, + 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).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("Using default configuration"); + 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).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.", - ); - - // Verify auth service login was called - expect(services.auth.login).toHaveBeenCalledTimes(1); - - // Verify automatic cascade reload was triggered - only auth service reload needed - expect(reloadService).toHaveBeenCalledTimes(1); - expect(reloadService).toHaveBeenCalledWith(SERVICE_NAMES.AUTH); - - // Verify manual service reloads are NOT called - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.API_CLIENT); - expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.CONFIG); + 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); }); - test.skip("login failure should not trigger any reloads", async () => { - const loginError = new Error("Login failed"); - (services.auth.login as any).mockRejectedValue(loginError); + 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).mockImplementation(() => { + throw new Error("Service not ready"); + }); - const result = await handleSlashCommands("/login", mockAssistant); + const result = await handleSlashCommands("/info", mockAssistant); - expect(result).not.toBeNull(); - expect(result?.output).toContain("Login failed: Login failed"); + expect(result).toBeDefined(); + expect(result?.output).toContain("Configuration service not available"); + }); - // Verify NO reload was triggered on failure - expect(reloadService).not.toHaveBeenCalled(); + 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"); + + (isAuthenticated as MockedFunction).mockReturnValue(false); + (services.config.getState as MockedFunction).mockReturnValue({ + config: null, + configPath: undefined + } as ConfigServiceState); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result?.output).toContain("/test-home/.continue/cli-sessions/"); + expect(result?.output).toContain(".json"); }); }); - - 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(); - }); - }); -}); +}); \ No newline at end of file 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" }); From 1d915c1fb8c725f158422f18cda9dd0dc71b2aac Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Aug 2025 10:33:45 -0700 Subject: [PATCH 30/38] ci: log when tests are re-run --- .github/actions/track-rerun/action.yml | 19 +++++++++++++++++++ .github/workflows/cli-pr-checks.yml | 8 ++++++++ .github/workflows/pr-checks.yaml | 8 ++++++++ 3 files changed, 35 insertions(+) create mode 100644 .github/actions/track-rerun/action.yml 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 7adbfd5fc..cdb0116ac 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/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: From a93c2bcb0dcb4b725b120d464d776fea925ff72a Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Aug 2025 10:50:45 -0700 Subject: [PATCH 31/38] fix: tests --- .../src/compaction.pruneLastMessage.test.ts | 98 +++++++++---------- extensions/cli/src/compaction.ts | 5 + extensions/cli/src/slashCommands.test.ts | 2 +- 3 files changed, 55 insertions(+), 50 deletions(-) diff --git a/extensions/cli/src/compaction.pruneLastMessage.test.ts b/extensions/cli/src/compaction.pruneLastMessage.test.ts index ae9c9866c..1d901cfc5 100644 --- a/extensions/cli/src/compaction.pruneLastMessage.test.ts +++ b/extensions/cli/src/compaction.pruneLastMessage.test.ts @@ -9,7 +9,43 @@ describe("pruneLastMessage", () => { expect(result).toEqual([]); }); - it("should preserve history ending with assistant message", () => { + 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" }, @@ -17,10 +53,12 @@ describe("pruneLastMessage", () => { ]; const result = pruneLastMessage(history); - expect(result).toEqual(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + ]); }); - it("should preserve history ending with tool message", () => { + 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" }, @@ -29,13 +67,15 @@ describe("pruneLastMessage", () => { ]; const result = pruneLastMessage(history); - expect(result).toEqual(history); + expect(result).toEqual([ + { role: "system", content: "System" }, + { role: "user", content: "Run command" }, + ]); }); - it("should prune user messages at the end", () => { + 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: "user", content: "Hello" }, { role: "assistant", content: "Hi there" }, { role: "user", content: "Another question" }, ]; @@ -43,16 +83,13 @@ describe("pruneLastMessage", () => { const result = pruneLastMessage(history); expect(result).toEqual([ { role: "system", content: "System" }, - { role: "user", content: "Hello" }, { role: "assistant", content: "Hi there" }, ]); }); - it("should prune multiple user messages at the end", () => { + it("should handle multiple user messages by removing two at a time", () => { const history: ChatCompletionMessageParam[] = [ { role: "system", content: "System" }, - { role: "user", content: "Hello" }, - { role: "assistant", content: "Hi there" }, { role: "user", content: "Question 1" }, { role: "user", content: "Question 2" }, ]; @@ -60,12 +97,10 @@ describe("pruneLastMessage", () => { const result = pruneLastMessage(history); expect(result).toEqual([ { role: "system", content: "System" }, - { role: "user", content: "Hello" }, - { role: "assistant", content: "Hi there" }, ]); }); - it("should handle tool call sequences correctly", () => { + it("should handle tool call sequences by removing user after tool", () => { const history: ChatCompletionMessageParam[] = [ { role: "system", content: "System" }, { role: "user", content: "Do something" }, @@ -83,20 +118,7 @@ describe("pruneLastMessage", () => { ]); }); - it("should return only system message when no assistant/tool messages exist", () => { - const history: ChatCompletionMessageParam[] = [ - { role: "system", content: "System" }, - { role: "user", content: "Hello" }, - { role: "user", content: "Another message" }, - ]; - - const result = pruneLastMessage(history); - expect(result).toEqual([ - { role: "system", content: "System" }, - ]); - }); - - it("should return empty array when no system message and no assistant/tool messages", () => { + it("should remove both user messages when consecutive", () => { const history: ChatCompletionMessageParam[] = [ { role: "user", content: "Hello" }, { role: "user", content: "Another message" }, @@ -106,28 +128,6 @@ describe("pruneLastMessage", () => { expect(result).toEqual([]); }); - it("should handle history with only system message", () => { - const history: ChatCompletionMessageParam[] = [ - { role: "system", content: "System" }, - ]; - - const result = pruneLastMessage(history); - expect(result).toEqual([ - { role: "system", content: "System" }, - ]); - }); - - it("should handle history with only assistant message", () => { - const history: ChatCompletionMessageParam[] = [ - { role: "assistant", content: "Hello" }, - ]; - - const result = pruneLastMessage(history); - expect(result).toEqual([ - { role: "assistant", content: "Hello" }, - ]); - }); - it("should handle complex conversation flow", () => { const history: ChatCompletionMessageParam[] = [ { role: "system", content: "System" }, diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index 2e40d1486..920f754d7 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -169,6 +169,11 @@ export function pruneLastMessage( return chatHistory; } + if (chatHistory.length === 1) { + // Only one message - always return empty array + return []; + } + const secondToLastIndex = chatHistory.length - 2; const secondToLastMessage = chatHistory[secondToLastIndex]; diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index 8d5ae0e70..825c71bda 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -108,7 +108,7 @@ describe("slashCommands", () => { expect(result?.output).toContain("Authentication:"); expect(result?.output).toContain("Authenticated via environment variable"); expect(result?.output).toContain("Configuration:"); - expect(result?.output).toContain("Using default configuration"); + expect(result?.output).toContain("Config not found"); expect(result?.exit).toBe(false); }); From bb41c5406eec52058d588299816e615bd43cb260 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Aug 2025 10:57:03 -0700 Subject: [PATCH 32/38] chore: format --- extensions/cli/src/commands/chat.ts | 5 +- .../cli/src/compaction.infiniteLoop.test.ts | 62 ++++---- .../src/compaction.pruneLastMessage.test.ts | 40 +++-- extensions/cli/src/slashCommands.test.ts | 137 ++++++++++++------ .../streamChatResponse.autoCompaction.test.ts | 63 +++++--- .../src/streamChatResponse.autoCompaction.ts | 34 +++-- extensions/cli/src/tools/readFile.ts | 8 +- 7 files changed, 225 insertions(+), 124 deletions(-) diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 45726d49d..2e7357fc3 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -174,7 +174,10 @@ async function handleAutoCompaction( // Custom callbacks for headless mode console output const callbacks = { onSystemMessage: (message: string) => { - if (message.includes("Auto-compacting") || message.includes("Approaching")) { + if ( + message.includes("Auto-compacting") || + message.includes("Approaching") + ) { if (!isHeadless) { console.info(chalk.yellow(`\n${message}`)); } else if (format === "json") { diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts index 24daf01a9..4fe565660 100644 --- a/extensions/cli/src/compaction.infiniteLoop.test.ts +++ b/extensions/cli/src/compaction.infiniteLoop.test.ts @@ -24,13 +24,15 @@ describe("compaction infinite loop prevention", () => { 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 { countChatHistoryTokens, getModelContextLimit } = await import( + "./util/tokenizer.js" + ); const mockStreamResponse = vi.mocked(streamChatResponse); const mockCountTokens = vi.mocked(countChatHistoryTokens); const mockGetContextLimit = vi.mocked(getModelContextLimit); @@ -38,11 +40,13 @@ describe("compaction infinite loop prevention", () => { // Setup mocks mockGetContextLimit.mockReturnValue(4000); mockCountTokens.mockReturnValue(5000); // Always too big - mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => { - callbacks?.onContent?.("Summary"); - callbacks?.onContentComplete?.(); - return "Summary"; - }); + mockStreamResponse.mockImplementation( + async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.(); + return "Summary"; + }, + ); // History that can't be pruned further (only system message) const history: ChatCompletionMessageParam[] = [ @@ -51,14 +55,16 @@ describe("compaction infinite loop prevention", () => { // 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 { countChatHistoryTokens, getModelContextLimit } = await import( + "./util/tokenizer.js" + ); const mockStreamResponse = vi.mocked(streamChatResponse); const mockCountTokens = vi.mocked(countChatHistoryTokens); const mockGetContextLimit = vi.mocked(getModelContextLimit); @@ -66,11 +72,13 @@ describe("compaction infinite loop prevention", () => { // Setup mocks mockGetContextLimit.mockReturnValue(4000); mockCountTokens.mockReturnValue(5000); // Always too big - mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => { - callbacks?.onContent?.("Summary"); - callbacks?.onContentComplete?.(); - return "Summary"; - }); + mockStreamResponse.mockImplementation( + async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.(); + return "Summary"; + }, + ); // History that ends with assistant - pruning won't change it const history: ChatCompletionMessageParam[] = [ @@ -81,19 +89,21 @@ describe("compaction infinite loop prevention", () => { // 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 { 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(() => { @@ -102,12 +112,14 @@ describe("compaction infinite loop prevention", () => { 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?.(); - return "Summary"; - }); + + mockStreamResponse.mockImplementation( + async (history, model, api, controller, callbacks) => { + callbacks?.onContent?.("Summary"); + callbacks?.onContentComplete?.(); + return "Summary"; + }, + ); // History that can be successfully pruned const history: ChatCompletionMessageParam[] = [ @@ -118,9 +130,9 @@ describe("compaction infinite loop prevention", () => { ]; const result = await compactChatHistory(history, mockModel, mockLlmApi); - + expect(result.compactedHistory).toBeDefined(); // The function will call countTokens multiple times during the process expect(mockCountTokens).toHaveBeenCalled(); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/compaction.pruneLastMessage.test.ts b/extensions/cli/src/compaction.pruneLastMessage.test.ts index 1d901cfc5..40e10949d 100644 --- a/extensions/cli/src/compaction.pruneLastMessage.test.ts +++ b/extensions/cli/src/compaction.pruneLastMessage.test.ts @@ -53,16 +53,18 @@ describe("pruneLastMessage", () => { ]; const result = pruneLastMessage(history); - expect(result).toEqual([ - { role: "system", content: "System" }, - ]); + 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: "assistant", + content: "Running...", + tool_calls: [{ id: "1" } as any], + }, { role: "tool", content: "Command output", tool_call_id: "1" }, ]; @@ -95,16 +97,18 @@ describe("pruneLastMessage", () => { ]; const result = pruneLastMessage(history); - expect(result).toEqual([ - { role: "system", content: "System" }, - ]); + 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: "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" }, ]; @@ -113,7 +117,11 @@ describe("pruneLastMessage", () => { 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: "assistant", + content: "I'll help", + tool_calls: [{ id: "1" } as any], + }, { role: "tool", content: "Tool result", tool_call_id: "1" }, ]); }); @@ -134,7 +142,11 @@ describe("pruneLastMessage", () => { { 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: "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" }, @@ -147,7 +159,11 @@ describe("pruneLastMessage", () => { { 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: "assistant", + content: "Using tool", + tool_calls: [{ id: "1" } as any], + }, { role: "tool", content: "Tool result", tool_call_id: "1" }, { role: "assistant", content: "Final response" }, ]); @@ -166,4 +182,4 @@ describe("pruneLastMessage", () => { { role: "assistant", content: "Hi" }, ]); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index 825c71bda..50185cf33 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -1,5 +1,12 @@ import type { AssistantUnrolled } from "@continuedev/config-yaml"; -import { describe, it, expect, vi, beforeEach, type MockedFunction } from "vitest"; +import { + describe, + it, + expect, + vi, + beforeEach, + type MockedFunction, +} from "vitest"; import type { AuthConfig, AuthenticatedConfig } from "./auth/workos.js"; import type { ConfigServiceState } from "./services/types.js"; @@ -9,58 +16,60 @@ import { handleSlashCommands } from "./slashCommands.js"; vi.mock("./services/index.js", () => ({ services: { config: { - getState: vi.fn() - } + getState: vi.fn(), + }, }, reloadService: vi.fn(), SERVICE_NAMES: { - AUTH: 'AUTH' - } + AUTH: "AUTH", + }, })); // Mock auth functions vi.mock("./auth/workos.js", () => ({ isAuthenticated: vi.fn(), isAuthenticatedConfig: vi.fn(), - loadAuthConfig: vi.fn() + loadAuthConfig: vi.fn(), })); // Mock telemetry vi.mock("./telemetry/posthogService.js", () => ({ posthogService: { - capture: vi.fn() - } + capture: vi.fn(), + }, })); // Mock commands vi.mock("./commands/commands.js", () => ({ - getAllSlashCommands: vi.fn(() => []) + getAllSlashCommands: vi.fn(() => []), })); // Mock os and path vi.mock("os", () => ({ default: { - homedir: vi.fn(() => "/home/test") - } + homedir: vi.fn(() => "/home/test"), + }, })); vi.mock("path", () => ({ default: { - join: vi.fn((...parts) => parts.join("/")) + join: vi.fn((...parts) => parts.join("/")), }, - 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) + 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" + version: "1.0.0", }; beforeEach(() => { @@ -71,11 +80,17 @@ describe("slashCommands", () => { it("should handle /info command when not authenticated", 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).mockReturnValue({ + + ( + isAuthenticated as MockedFunction + ).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ config: null, - configPath: "/test/config.yaml" + configPath: "/test/config.yaml", } as ConfigServiceState); const result = await handleSlashCommands("/info", mockAssistant); @@ -91,46 +106,66 @@ describe("slashCommands", () => { }); it("should handle /info command when authenticated via environment", async () => { - const { isAuthenticated, loadAuthConfig, isAuthenticatedConfig } = await import("./auth/workos.js"); + 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); + + ( + isAuthenticated as MockedFunction + ).mockReturnValue(true); + (loadAuthConfig as MockedFunction).mockReturnValue( + {} as AuthConfig, + ); (isAuthenticatedConfig as any).mockReturnValue(false); - (services.config.getState as MockedFunction).mockReturnValue({ + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ config: null, - configPath: undefined + 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( + "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 { 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" + organizationId: "test-org-id", }; - (isAuthenticated as MockedFunction).mockReturnValue(true); - (loadAuthConfig as MockedFunction).mockReturnValue(mockAuthConfig); + ( + isAuthenticated as MockedFunction + ).mockReturnValue(true); + (loadAuthConfig as MockedFunction).mockReturnValue( + mockAuthConfig, + ); (isAuthenticatedConfig as any).mockReturnValue(true); - (services.config.getState as MockedFunction).mockReturnValue({ + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ config: null, - configPath: "/custom/config.yaml" + configPath: "/custom/config.yaml", } as ConfigServiceState); const result = await handleSlashCommands("/info", mockAssistant); @@ -147,9 +182,15 @@ describe("slashCommands", () => { 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).mockImplementation(() => { + + ( + isAuthenticated as MockedFunction + ).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockImplementation(() => { throw new Error("Service not ready"); }); @@ -163,14 +204,22 @@ describe("slashCommands", () => { 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"); - - (isAuthenticated as MockedFunction).mockReturnValue(false); - (services.config.getState as MockedFunction).mockReturnValue({ + (getSessionFilePath as any).mockReturnValue( + "/test-home/.continue/cli-sessions/continue-cli-test-123.json", + ); + + ( + isAuthenticated as MockedFunction + ).mockReturnValue(false); + ( + services.config.getState as MockedFunction< + typeof services.config.getState + > + ).mockReturnValue({ config: null, - configPath: undefined + configPath: undefined, } as ConfigServiceState); const result = await handleSlashCommands("/info", mockAssistant); @@ -179,4 +228,4 @@ describe("slashCommands", () => { expect(result?.output).toContain(".json"); }); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/streamChatResponse.autoCompaction.test.ts index ce67f8660..bfc9daae6 100644 --- a/extensions/cli/src/streamChatResponse.autoCompaction.test.ts +++ b/extensions/cli/src/streamChatResponse.autoCompaction.test.ts @@ -72,17 +72,25 @@ describe("handleAutoCompaction", () => { }); it("should perform auto-compaction when context limit is approaching", async () => { - const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js"); + 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, + { + role: "system", + content: "You are a helpful assistant.", + } as ChatCompletionMessageParam, + { + role: "assistant", + content: "[COMPACTED HISTORY]\nConversation summary...", + } as ChatCompletionMessageParam, ], compactionIndex: 1, compactionContent: "Conversation summary...", @@ -112,10 +120,16 @@ describe("handleAutoCompaction", () => { 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(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, @@ -124,13 +138,17 @@ describe("handleAutoCompaction", () => { }); it("should handle compaction errors gracefully", async () => { - const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js"); + 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")); + vi.mocked(compactChatHistory).mockRejectedValue( + new Error("Compaction failed"), + ); const mockCallbacks = { onSystemMessage: vi.fn(), @@ -161,14 +179,18 @@ describe("handleAutoCompaction", () => { }); it("should not call system message callback in headless mode", async () => { - const { shouldAutoCompact, getAutoCompactMessage } = await import("./util/tokenizer.js"); + 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], + compactedHistory: [ + { role: "system", content: "System" } as ChatCompletionMessageParam, + ], compactionIndex: 0, compactionContent: "Summary", }; @@ -179,15 +201,10 @@ describe("handleAutoCompaction", () => { onSystemMessage: vi.fn(), }; - await handleAutoCompaction( - mockChatHistory, - mockModel, - mockLlmApi, - { - isHeadless: true, - callbacks: mockCallbacks, - }, - ); + await handleAutoCompaction(mockChatHistory, mockModel, mockLlmApi, { + isHeadless: true, + callbacks: mockCallbacks, + }); expect(mockCallbacks.onSystemMessage).not.toHaveBeenCalled(); }); @@ -205,4 +222,4 @@ describe("handleAutoCompaction", () => { compactionIndex: null, }); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.ts b/extensions/cli/src/streamChatResponse.autoCompaction.ts index 087896d2e..ee9336250 100644 --- a/extensions/cli/src/streamChatResponse.autoCompaction.ts +++ b/extensions/cli/src/streamChatResponse.autoCompaction.ts @@ -8,21 +8,20 @@ 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"; +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>; + setChatHistory?: React.Dispatch< + React.SetStateAction + >; setCompactionIndex?: React.Dispatch>; - + // For headless mode - no callbacks needed, just return values } @@ -41,7 +40,7 @@ function notifyCompactionStart( callbacks?: AutoCompactionCallbacks, ) { if (isHeadless) return; - + if (callbacks?.onSystemMessage) { callbacks.onSystemMessage(message); } else if (callbacks?.setMessages) { @@ -65,12 +64,16 @@ function handleCompactionSuccess( 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) { + } else if ( + callbacks?.setMessages && + callbacks?.setChatHistory && + callbacks?.setCompactionIndex + ) { callbacks.setChatHistory(result.compactedHistory); callbacks.setCompactionIndex(result.compactionIndex); callbacks.setMessages((prev) => [ @@ -96,9 +99,9 @@ function handleCompactionError( logger.error(errorMessage); if (isHeadless) return; - + const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`; - + if (callbacks?.onSystemMessage) { callbacks.onSystemMessage(warningMessage); } else if (callbacks?.setMessages) { @@ -136,7 +139,9 @@ export async function handleAutoCompaction( return { chatHistory, compactionIndex: null }; } - logger.info(`Auto-compaction triggered${isHeadless ? ' in headless mode' : ''}`); + logger.info( + `Auto-compaction triggered${isHeadless ? " in headless mode" : ""}`, + ); // Notify about compaction start notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks); @@ -173,4 +178,3 @@ export async function handleAutoCompaction( return { chatHistory, compactionIndex: null }; } } - diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index 37a15639c..80a6bbe62 100644 --- a/extensions/cli/src/tools/readFile.ts +++ b/extensions/cli/src/tools/readFile.ts @@ -39,13 +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'); + + const lines = content.split("\n"); if (lines.length > 5000) { - const truncatedContent = lines.slice(0, 5000).join('\n'); + 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: ${ From d235cb4969f8010fb9bcd92028440ba828b125ba Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Aug 2025 10:57:44 -0700 Subject: [PATCH 33/38] fix: more tests --- .../cli/src/compaction.infiniteLoop.test.ts | 16 ++++++++-------- .../cli/src/test-helpers/ui-test-context.ts | 2 +- extensions/cli/src/ui/hooks/useChat.helpers.ts | 4 ---- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts index 4fe565660..c0f1127cd 100644 --- a/extensions/cli/src/compaction.infiniteLoop.test.ts +++ b/extensions/cli/src/compaction.infiniteLoop.test.ts @@ -1,7 +1,7 @@ -import { ChatCompletionMessageParam } from "openai/resources.mjs"; -import { describe, it, expect, vi } from "vitest"; 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"; @@ -43,7 +43,7 @@ describe("compaction infinite loop prevention", () => { mockStreamResponse.mockImplementation( async (history, model, api, controller, callbacks) => { callbacks?.onContent?.("Summary"); - callbacks?.onContentComplete?.(); + callbacks?.onContentComplete?.("Summary"); return "Summary"; }, ); @@ -54,7 +54,7 @@ describe("compaction infinite loop prevention", () => { ]; // This should not hang - it should break out of the loop - const result = await compactChatHistory(history, mockModel, mockLlmApi); + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); // Should complete successfully even though token count is still too high expect(result.compactedHistory).toBeDefined(); @@ -75,7 +75,7 @@ describe("compaction infinite loop prevention", () => { mockStreamResponse.mockImplementation( async (history, model, api, controller, callbacks) => { callbacks?.onContent?.("Summary"); - callbacks?.onContentComplete?.(); + callbacks?.onContentComplete?.("Summary"); return "Summary"; }, ); @@ -88,7 +88,7 @@ describe("compaction infinite loop prevention", () => { ]; // This should not hang - const result = await compactChatHistory(history, mockModel, mockLlmApi); + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); expect(result.compactedHistory).toBeDefined(); }); @@ -116,7 +116,7 @@ describe("compaction infinite loop prevention", () => { mockStreamResponse.mockImplementation( async (history, model, api, controller, callbacks) => { callbacks?.onContent?.("Summary"); - callbacks?.onContentComplete?.(); + callbacks?.onContentComplete?.("Summary"); return "Summary"; }, ); @@ -129,7 +129,7 @@ describe("compaction infinite loop prevention", () => { { role: "user", content: "Another question" }, ]; - const result = await compactChatHistory(history, mockModel, mockLlmApi); + const result = await compactChatHistory(history, mockModel, mockLlmApi, {}); expect(result.compactedHistory).toBeDefined(); // The function will call countTokens multiple times during the process 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/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 2b1113bc9..b8d77e028 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -291,10 +291,6 @@ export async function handleAutoCompaction({ currentChatHistory: ChatCompletionMessageParam[]; currentCompactionIndex: number | null; }> { - if (!llmApi) { - throw new Error("LLM API is not available for auto-compaction"); - } - const { handleAutoCompaction: coreAutoCompaction } = await import( "../../streamChatResponse.autoCompaction.js" ); From d9eba9a303c178d3ae9bd88825187a64caa15f4c Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Sat, 23 Aug 2025 11:16:36 -0700 Subject: [PATCH 34/38] Update extensions/cli/src/ui/hooks/useChat.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- extensions/cli/src/ui/hooks/useChat.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index fca26ef4c..938862692 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -174,7 +174,7 @@ export function useChat({ } }; - processPrompts(); + processPrompts().catch(console.error); } }, [initialPrompt, additionalPrompts, isChatHistoryInitialized]); From 826182ceec0e86eaeda8d4ef0e157f1cddd011ef Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Aug 2025 11:23:58 -0700 Subject: [PATCH 35/38] fix: address feedback --- extensions/cli/src/__mocks__/args.ts | 2 +- extensions/cli/src/args.prompt.test.ts | 13 ++++++-- extensions/cli/src/args.test.ts | 30 +++++++++---------- extensions/cli/src/args.ts | 13 ++++++-- .../cli/src/services/ConfigService.test.ts | 2 +- extensions/cli/src/systemMessage.test.ts | 6 ++-- extensions/cli/src/ui/hooks/useChat.ts | 2 +- 7 files changed, 42 insertions(+), 26 deletions(-) diff --git a/extensions/cli/src/__mocks__/args.ts b/extensions/cli/src/__mocks__/args.ts index 07e63d652..f982bdd09 100644 --- a/extensions/cli/src/__mocks__/args.ts +++ b/extensions/cli/src/__mocks__/args.ts @@ -1,5 +1,5 @@ import { vi } from "vitest"; export const processPromptOrRule = vi.fn<(spec: string) => Promise>(); -export const processRule = vi.fn<(rule: string) => Promise>(); + export const processPrompt = vi.fn<(prompt: string) => Promise>(); diff --git a/extensions/cli/src/args.prompt.test.ts b/extensions/cli/src/args.prompt.test.ts index aa581559e..121e11b1c 100644 --- a/extensions/cli/src/args.prompt.test.ts +++ b/extensions/cli/src/args.prompt.test.ts @@ -1,13 +1,20 @@ -import { describe, it, expect, beforeEach } from "vitest"; +import { describe, it, expect, beforeEach, afterAll } from "vitest"; -import { parseArgs, processPrompt } from "./args.js"; +import { parseArgs, processPromptOrRule } from "./args.js"; describe("args --prompt flag", () => { + const originalArgv = process.argv; + beforeEach(() => { // Reset process.argv for each test process.argv = ["node", "script.js"]; }); + afterAll(() => { + // Restore original process.argv after all tests + process.argv = originalArgv; + }); + it("should parse single prompt from --prompt flag", () => { process.argv = ["node", "script.js", "--prompt", "my-prompt"]; const result = parseArgs(); @@ -43,7 +50,7 @@ describe("args --prompt flag", () => { }); it("should process direct string content", async () => { - const result = await processPrompt("This is a direct prompt"); + const result = await processPromptOrRule("This is a direct prompt"); expect(result).toBe("This is a direct prompt"); }); }); \ No newline at end of file diff --git a/extensions/cli/src/args.test.ts b/extensions/cli/src/args.test.ts index 3db340f73..d20622113 100644 --- a/extensions/cli/src/args.test.ts +++ b/extensions/cli/src/args.test.ts @@ -1,6 +1,6 @@ import { vi } from "vitest"; -import { parseArgs, processRule } from "./args.js"; +import { parseArgs, processPromptOrRule } from "./args.js"; describe("parseArgs", () => { const originalArgv = process.argv; @@ -217,7 +217,7 @@ describe("parseArgs", () => { }); }); -describe("processRule (loadRuleFromHub integration)", () => { +describe("processPromptOrRule (loadRuleFromHub integration)", () => { // Mock fetch for hub tests const originalFetch = global.fetch; const mockFetch = vi.fn() as any; @@ -251,7 +251,7 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - const result = await processRule("continuedev/sentry-nextjs"); + const result = await processPromptOrRule("continuedev/sentry-nextjs"); expect(result).toBe(ruleContent); expect(mockFetch).toHaveBeenCalledWith( @@ -269,7 +269,7 @@ describe("processRule (loadRuleFromHub integration)", () => { statusText: "Not Found", } as Response); - await expect(processRule("continuedev/nonexistent-rule")).rejects.toThrow( + await expect(processPromptOrRule("continuedev/nonexistent-rule")).rejects.toThrow( 'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found', ); }); @@ -277,7 +277,7 @@ describe("processRule (loadRuleFromHub integration)", () => { it("should handle network errors when loading from hub", async () => { mockFetch.mockRejectedValue(new Error("Network error")); - await expect(processRule("continuedev/sentry-nextjs")).rejects.toThrow( + await expect(processPromptOrRule("continuedev/sentry-nextjs")).rejects.toThrow( 'Failed to load rule from hub "continuedev/sentry-nextjs": Network error', ); }); @@ -285,7 +285,7 @@ describe("processRule (loadRuleFromHub integration)", () => { it("should handle invalid slug format", async () => { // "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug // Let's test with a slug that has wrong format but contains "/" - await expect(processRule("invalid/slug/too/many/parts")).rejects.toThrow( + await expect(processPromptOrRule("invalid/slug/too/many/parts")).rejects.toThrow( 'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts', ); }); @@ -300,7 +300,7 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - await expect(processRule("continuedev/empty-rule")).rejects.toThrow( + await expect(processPromptOrRule("continuedev/empty-rule")).rejects.toThrow( 'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file', ); }); @@ -316,7 +316,7 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - await expect(processRule("continuedev/directory-only")).rejects.toThrow( + await expect(processPromptOrRule("continuedev/directory-only")).rejects.toThrow( 'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file', ); }); @@ -338,7 +338,7 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - const result = await processRule("continuedev/mixed-files"); + const result = await processPromptOrRule("continuedev/mixed-files"); expect(result).toBe(mdContent); }); @@ -359,7 +359,7 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - const result = await processRule("continuedev/multiple-rules"); + const result = await processPromptOrRule("continuedev/multiple-rules"); // Should use the first markdown file found (alphabetically) expect(result).toBe(rule1Content); @@ -373,13 +373,13 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(invalidZipBuffer), } as Response); - await expect(processRule("continuedev/corrupted-zip")).rejects.toThrow( + await expect(processPromptOrRule("continuedev/corrupted-zip")).rejects.toThrow( 'Failed to load rule from hub "continuedev/corrupted-zip"', ); }); }); - describe("processRule logic", () => { + describe("processPromptOrRule logic", () => { it("should identify hub slugs correctly", async () => { const JSZip = (await import("jszip")).default; const zip = new JSZip(); @@ -391,14 +391,14 @@ describe("processRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - const result = await processRule("owner/package"); + const result = await processPromptOrRule("owner/package"); expect(result).toBe("# Hub Rule"); expect(mockFetch).toHaveBeenCalled(); }); it("should treat direct strings as content", async () => { const directContent = "This is direct rule content"; - const result = await processRule(directContent); + const result = await processPromptOrRule(directContent); expect(result).toBe(directContent); expect(mockFetch).not.toHaveBeenCalled(); }); @@ -406,7 +406,7 @@ describe("processRule (loadRuleFromHub integration)", () => { it("should distinguish between hub slugs and file paths", async () => { // This would be treated as a file path, not a hub slug // since it starts with "." - await expect(processRule("./owner/package")).rejects.toThrow( + await expect(processPromptOrRule("./owner/package")).rejects.toThrow( 'Failed to read rule file "./owner/package": Rule file not found', ); expect(mockFetch).not.toHaveBeenCalled(); diff --git a/extensions/cli/src/args.ts b/extensions/cli/src/args.ts index 35f97a0f6..272a7a465 100644 --- a/extensions/cli/src/args.ts +++ b/extensions/cli/src/args.ts @@ -183,9 +183,18 @@ export function parseArgs(): CommandLineArgs { if (promptIndices.length > 0) { result.prompts = []; for (const promptIndex of promptIndices) { - if (promptIndex + 1 < args.length) { - result.prompts.push(args[promptIndex + 1]); + if (promptIndex + 1 >= args.length) { + throw new Error("--prompt flag requires a value"); } + + const promptValue = args[promptIndex + 1]; + + // Check if the next argument is actually another flag + if (promptValue.startsWith("--")) { + throw new Error("--prompt flag requires a value, found flag instead"); + } + + result.prompts.push(promptValue); } } diff --git a/extensions/cli/src/services/ConfigService.test.ts b/extensions/cli/src/services/ConfigService.test.ts index 19ba756e6..d671e1519 100644 --- a/extensions/cli/src/services/ConfigService.test.ts +++ b/extensions/cli/src/services/ConfigService.test.ts @@ -73,7 +73,7 @@ describe("ConfigService", () => { config: mockConfig as any, source: { type: "cli-flag", path: "/config.yaml" } as any, }); - vi.mocked(args.processRule).mockImplementation( + vi.mocked(args.processPromptOrRule).mockImplementation( async (rule) => `Processed: ${rule}`, ); diff --git a/extensions/cli/src/systemMessage.test.ts b/extensions/cli/src/systemMessage.test.ts index b76f4fb61..71e4d6df9 100644 --- a/extensions/cli/src/systemMessage.test.ts +++ b/extensions/cli/src/systemMessage.test.ts @@ -11,11 +11,11 @@ vi.mock("./services/ServiceContainer.js", () => ({ }, })); -// Mock processRule to avoid file system operations in tests +// Mock processPromptOrRule to avoid file system operations in tests vi.mock("./args.js", () => ({ - processRule: vi + processPromptOrRule: vi .fn() - .mockImplementation((rule: string) => Promise.resolve(rule)), + .mockImplementation((spec: string) => Promise.resolve(spec)), })); describe("constructSystemMessage", () => { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index fca26ef4c..11deaf24a 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -170,7 +170,7 @@ export function useChat({ const finalMessage = await processAndCombinePrompts(additionalPrompts, initialPrompt); if (finalMessage) { - handleUserMessage(finalMessage); + await handleUserMessage(finalMessage); } }; From 6eded3146b18ac6f50f0706b2cc302777709950f Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Aug 2025 11:28:20 -0700 Subject: [PATCH 36/38] fix: don't fail on compliance checks --- .github/workflows/compliance.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 6ab98b27e..76c21d6b1 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -36,7 +36,7 @@ jobs: else echo "❌ PR title does not follow conventional commit format" echo "valid=false" >> $GITHUB_OUTPUT - exit 1 + # Don't exit with failure - just mark as invalid for comment fi - name: Add PR title guidance comment From c4fed497694ed01f3fe61c52fba67e50bb69e5c2 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Aug 2025 11:28:33 -0700 Subject: [PATCH 37/38] chore: foramt --- extensions/cli/src/args.prompt.test.ts | 38 ++++++++++++++++--- extensions/cli/src/args.test.ts | 24 +++++++++--- extensions/cli/src/args.ts | 26 ++++++------- extensions/cli/src/commands/chat.ts | 9 ++++- extensions/cli/src/ui/hooks/useChat.ts | 18 ++++++--- .../cli/src/util/promptProcessor.test.ts | 13 +++---- extensions/cli/src/util/promptProcessor.ts | 6 +-- 7 files changed, 91 insertions(+), 43 deletions(-) diff --git a/extensions/cli/src/args.prompt.test.ts b/extensions/cli/src/args.prompt.test.ts index 121e11b1c..46b70b4db 100644 --- a/extensions/cli/src/args.prompt.test.ts +++ b/extensions/cli/src/args.prompt.test.ts @@ -22,13 +22,28 @@ describe("args --prompt flag", () => { }); it("should parse multiple prompts from multiple --prompt flags", () => { - process.argv = ["node", "script.js", "--prompt", "prompt1", "--prompt", "prompt2"]; + process.argv = [ + "node", + "script.js", + "--prompt", + "prompt1", + "--prompt", + "prompt2", + ]; const result = parseArgs(); expect(result.prompts).toEqual(["prompt1", "prompt2"]); }); it("should handle mixed flags including --prompt", () => { - process.argv = ["node", "script.js", "--config", "myconfig", "--prompt", "myprompt", "--resume"]; + process.argv = [ + "node", + "script.js", + "--config", + "myconfig", + "--prompt", + "myprompt", + "--resume", + ]; const result = parseArgs(); expect(result.configPath).toBe("myconfig"); expect(result.prompts).toEqual(["myprompt"]); @@ -36,14 +51,27 @@ describe("args --prompt flag", () => { }); it("should not include --prompt value in non-flag arguments", () => { - process.argv = ["node", "script.js", "--prompt", "prompt-value", "actual-prompt"]; + process.argv = [ + "node", + "script.js", + "--prompt", + "prompt-value", + "actual-prompt", + ]; const result = parseArgs(); expect(result.prompts).toEqual(["prompt-value"]); expect(result.prompt).toBe("actual-prompt"); }); it("should handle both --rule and --prompt flags", () => { - process.argv = ["node", "script.js", "--rule", "my-rule", "--prompt", "my-prompt"]; + process.argv = [ + "node", + "script.js", + "--rule", + "my-rule", + "--prompt", + "my-prompt", + ]; const result = parseArgs(); expect(result.rules).toEqual(["my-rule"]); expect(result.prompts).toEqual(["my-prompt"]); @@ -53,4 +81,4 @@ describe("args --prompt flag", () => { const result = await processPromptOrRule("This is a direct prompt"); expect(result).toBe("This is a direct prompt"); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/args.test.ts b/extensions/cli/src/args.test.ts index d20622113..d22333c05 100644 --- a/extensions/cli/src/args.test.ts +++ b/extensions/cli/src/args.test.ts @@ -269,7 +269,9 @@ describe("processPromptOrRule (loadRuleFromHub integration)", () => { statusText: "Not Found", } as Response); - await expect(processPromptOrRule("continuedev/nonexistent-rule")).rejects.toThrow( + await expect( + processPromptOrRule("continuedev/nonexistent-rule"), + ).rejects.toThrow( 'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found', ); }); @@ -277,7 +279,9 @@ describe("processPromptOrRule (loadRuleFromHub integration)", () => { it("should handle network errors when loading from hub", async () => { mockFetch.mockRejectedValue(new Error("Network error")); - await expect(processPromptOrRule("continuedev/sentry-nextjs")).rejects.toThrow( + await expect( + processPromptOrRule("continuedev/sentry-nextjs"), + ).rejects.toThrow( 'Failed to load rule from hub "continuedev/sentry-nextjs": Network error', ); }); @@ -285,7 +289,9 @@ describe("processPromptOrRule (loadRuleFromHub integration)", () => { it("should handle invalid slug format", async () => { // "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug // Let's test with a slug that has wrong format but contains "/" - await expect(processPromptOrRule("invalid/slug/too/many/parts")).rejects.toThrow( + await expect( + processPromptOrRule("invalid/slug/too/many/parts"), + ).rejects.toThrow( 'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts', ); }); @@ -300,7 +306,9 @@ describe("processPromptOrRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - await expect(processPromptOrRule("continuedev/empty-rule")).rejects.toThrow( + await expect( + processPromptOrRule("continuedev/empty-rule"), + ).rejects.toThrow( 'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file', ); }); @@ -316,7 +324,9 @@ describe("processPromptOrRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(zipBuffer), } as Response); - await expect(processPromptOrRule("continuedev/directory-only")).rejects.toThrow( + await expect( + processPromptOrRule("continuedev/directory-only"), + ).rejects.toThrow( 'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file', ); }); @@ -373,7 +383,9 @@ describe("processPromptOrRule (loadRuleFromHub integration)", () => { arrayBuffer: () => Promise.resolve(invalidZipBuffer), } as Response); - await expect(processPromptOrRule("continuedev/corrupted-zip")).rejects.toThrow( + await expect( + processPromptOrRule("continuedev/corrupted-zip"), + ).rejects.toThrow( 'Failed to load rule from hub "continuedev/corrupted-zip"', ); }); diff --git a/extensions/cli/src/args.ts b/extensions/cli/src/args.ts index 272a7a465..2a2c79819 100644 --- a/extensions/cli/src/args.ts +++ b/extensions/cli/src/args.ts @@ -90,20 +90,12 @@ async function loadRuleFromHub(slug: string): Promise { */ export async function processPromptOrRule(spec: string): Promise { // If it looks like a hub slug (contains / but doesn't start with . or /) - if ( - spec.includes("/") && - !spec.startsWith(".") && - !spec.startsWith("/") - ) { + if (spec.includes("/") && !spec.startsWith(".") && !spec.startsWith("/")) { return await loadRuleFromHub(spec); } // If it looks like a file path (contains . or / or ends with common file extensions) - if ( - spec.includes(".") || - spec.includes("/") || - spec.includes("\\") - ) { + if (spec.includes(".") || spec.includes("/") || spec.includes("\\")) { return loadRuleFromFile(spec); } @@ -186,20 +178,26 @@ export function parseArgs(): CommandLineArgs { if (promptIndex + 1 >= args.length) { throw new Error("--prompt flag requires a value"); } - + const promptValue = args[promptIndex + 1]; - + // Check if the next argument is actually another flag if (promptValue.startsWith("--")) { throw new Error("--prompt flag requires a value, found flag instead"); } - + result.prompts.push(promptValue); } } // Find the last argument that's not a flag or a flag value - const flagsWithValues = ["--config", "--org", "--rule", "--prompt", "--format"]; + const flagsWithValues = [ + "--config", + "--org", + "--rule", + "--prompt", + "--format", + ]; const nonFlagArgs = args.filter((arg, index) => { // Skip flags (starting with --) if (arg.startsWith("--") || arg === "-p") return false; diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index adcda2b15..951160110 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -397,8 +397,13 @@ async function runHeadlessMode( } // Handle additional prompts from --prompt flags - const { processAndCombinePrompts } = await import("../util/promptProcessor.js"); - const initialUserInput = await processAndCombinePrompts(options.prompt, prompt); + const { processAndCombinePrompts } = await import( + "../util/promptProcessor.js" + ); + const initialUserInput = await processAndCombinePrompts( + options.prompt, + prompt, + ); let isFirstMessage = true; while (true) { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 59289b832..a8b522260 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -164,16 +164,24 @@ export function useChat({ useEffect(() => { // Only handle initial prompt after chat history is initialized // This prevents race conditions where the prompt runs before system message is loaded - if ((initialPrompt || (additionalPrompts && additionalPrompts.length > 0)) && isChatHistoryInitialized) { + if ( + (initialPrompt || (additionalPrompts && additionalPrompts.length > 0)) && + isChatHistoryInitialized + ) { const processPrompts = async () => { - const { processAndCombinePrompts } = await import("../../util/promptProcessor.js"); - const finalMessage = await processAndCombinePrompts(additionalPrompts, initialPrompt); - + const { processAndCombinePrompts } = await import( + "../../util/promptProcessor.js" + ); + const finalMessage = await processAndCombinePrompts( + additionalPrompts, + initialPrompt, + ); + if (finalMessage) { await handleUserMessage(finalMessage); } }; - + processPrompts().catch(console.error); } }, [initialPrompt, additionalPrompts, isChatHistoryInitialized]); diff --git a/extensions/cli/src/util/promptProcessor.test.ts b/extensions/cli/src/util/promptProcessor.test.ts index 2bc28004d..4644e17c8 100644 --- a/extensions/cli/src/util/promptProcessor.test.ts +++ b/extensions/cli/src/util/promptProcessor.test.ts @@ -82,11 +82,7 @@ describe("promptProcessor", () => { .mockRejectedValueOnce(new Error("processing failed")) .mockResolvedValueOnce("success2"); - const result = await processAndCombinePrompts([ - "good1", - "bad", - "good2", - ]); + const result = await processAndCombinePrompts(["good1", "bad", "good2"]); expect(mockProcessPromptOrRule).toHaveBeenCalledTimes(3); expect(result).toBe("success1\n\nsuccess2"); @@ -98,7 +94,10 @@ describe("promptProcessor", () => { .mockRejectedValueOnce(new Error("fail1")) .mockRejectedValueOnce(new Error("fail2")); - const result = await processAndCombinePrompts(["bad1", "bad2"], "initial"); + const result = await processAndCombinePrompts( + ["bad1", "bad2"], + "initial", + ); expect(result).toBe("initial"); }); @@ -125,4 +124,4 @@ describe("promptProcessor", () => { ); }); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/util/promptProcessor.ts b/extensions/cli/src/util/promptProcessor.ts index ef36bf6ea..60d926cd4 100644 --- a/extensions/cli/src/util/promptProcessor.ts +++ b/extensions/cli/src/util/promptProcessor.ts @@ -22,9 +22,7 @@ export async function processAndCombinePrompts( const processed = await processPromptOrRule(promptSpec); processedPrompts.push(processed); } catch (error: any) { - logger.warn( - `Failed to process prompt "${promptSpec}": ${error.message}`, - ); + logger.warn(`Failed to process prompt "${promptSpec}": ${error.message}`); } } @@ -36,4 +34,4 @@ export async function processAndCombinePrompts( return initialPrompt ? `${combinedPrompts}\n\n${initialPrompt}` : combinedPrompts; -} \ No newline at end of file +} From 6ca57b07bc5899c67f4096eec1ff30711b5f42b4 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 23 Aug 2025 11:30:04 -0700 Subject: [PATCH 38/38] chore: lint --- extensions/cli/src/util/promptProcessor.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/cli/src/util/promptProcessor.ts b/extensions/cli/src/util/promptProcessor.ts index 60d926cd4..c6173738f 100644 --- a/extensions/cli/src/util/promptProcessor.ts +++ b/extensions/cli/src/util/promptProcessor.ts @@ -1,4 +1,5 @@ import { processPromptOrRule } from "../args.js"; + import { logger } from "./logger.js"; /**