From e7d3625b73c85f98d5582860dd4f180dccc51e3f Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 24 Jul 2025 19:09:55 +0530 Subject: [PATCH 001/102] fix: case when reranker returns invalid scores array --- core/context/providers/DocsContextProvider.ts | 10 +++++++--- core/llm/llms/Voyage.ts | 19 ++++++++++++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 0f87a3f61..5c8e0af1b 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -43,9 +43,13 @@ class DocsContextProvider extends BaseContextProvider { try { const scores = await reranker.rerank(fullInput, chunksCopy); - chunksCopy.sort( - (a, b) => scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)], - ); + if (Array.isArray(scores)) { + // reranker model has returned a valid array + chunksCopy.sort( + (a, b) => + scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)], + ); + } chunksCopy = chunksCopy.splice( 0, diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index fe08d8b1d..94c344a56 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -1,7 +1,21 @@ -import { Chunk, LLMOptions } from "../../index.js"; +import { z } from "zod"; +import { Chunk, LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; +/**used to check a valid response from voyage is received + * reference: https://docs.voyageai.com/reference/reranker-api + */ +const VoyageRerankSuccessResponseSchema = z.object({ + data: z.array( + z.object({ + index: z.number(), + relevance_score: z.number(), + document: z.string(), + }), + ), +}); + class Voyage extends OpenAI { static providerName = "voyage"; static defaultOptions: Partial | undefined = { @@ -36,6 +50,9 @@ class Voyage extends OpenAI { const data = (await resp.json()) as { data: Array<{ index: number; relevance_score: number }>; }; + + VoyageRerankSuccessResponseSchema.parse(data); + const results = data.data.sort((a, b) => a.index - b.index); return results.map((result) => result.relevance_score); } From 5d42f29ea5788a1a46eb6be35138ffd1e48deec7 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 31 Jul 2025 11:26:32 +0530 Subject: [PATCH 002/102] fix case for reranker or codebase context --- core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index ad966f89a..fef4a75da 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -27,7 +27,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { let embeddingsChunks: Chunk[] = []; try { - embeddingsChunks = !!config.selectedModelByRole.embed + embeddingsChunks = Boolean(config.selectedModelByRole.embed) ? await this.retrieveEmbeddings(input, nRetrieve) : []; } catch (error) { @@ -116,7 +116,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { const chunkIndexMap = new Map(); chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); - results.sort( + results?.sort( (a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!], ); results = results.slice(-this.options.nFinal); From 1dbba32d085b8794bf55417086058bb26f81f0c8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 1 Aug 2025 13:40:47 -0700 Subject: [PATCH 003/102] Create cli-review.yaml --- .github/workflows/cli-review.yaml | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .github/workflows/cli-review.yaml diff --git a/.github/workflows/cli-review.yaml b/.github/workflows/cli-review.yaml new file mode 100644 index 000000000..c89de643b --- /dev/null +++ b/.github/workflows/cli-review.yaml @@ -0,0 +1,29 @@ +name: CLI Review + +on: + pull_request: + branches: + - main + + push: + branches: + - main + +jobs: + cli-review: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Run Continue CLI Review + run: | + echo "Running Continue CLI with prompt:" + echo "==================================" + cat review_prompt.txt + echo "==================================" + echo "" + + # Run the CLI with the generated prompt and output text directly + cat review_prompt.txt | cn --config "${{ inputs.assistant }}" -p + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} \ No newline at end of file From 1bc77912c5f5750847409eced17ffd5f7ef3d166 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 1 Aug 2025 13:46:32 -0700 Subject: [PATCH 004/102] Update cli-review.yaml --- .github/workflows/cli-review.yaml | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/workflows/cli-review.yaml b/.github/workflows/cli-review.yaml index c89de643b..8a6557be1 100644 --- a/.github/workflows/cli-review.yaml +++ b/.github/workflows/cli-review.yaml @@ -15,15 +15,22 @@ jobs: steps: - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - name: Install Continue CLI + run: npm install -g @continuedev/cli@1.4.21 + - name: Run Continue CLI Review run: | - echo "Running Continue CLI with prompt:" + echo "Running Continue CLI with hardcoded prompt:" echo "==================================" - cat review_prompt.txt + echo "Review this pull request and provide feedback on code quality" echo "==================================" echo "" - # Run the CLI with the generated prompt and output text directly - cat review_prompt.txt | cn --config "${{ inputs.assistant }}" -p + # Run the CLI with a hardcoded prompt and output text directly + echo "Review this pull request and provide feedback on code quality" | cn --config "${{ inputs.assistant }}" -p env: CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} \ No newline at end of file From 37e6c34d0309c8899ccf5fc84c19e88afdd34a39 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Mon, 4 Aug 2025 23:21:53 -0400 Subject: [PATCH 005/102] chore(gui): remove EXAONE icon --- core/llm/toolSupport.ts | 12 ++++++++++ gui/src/pages/AddNewModel/configs/models.ts | 26 +++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index a7edbbd36..177de83ca 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -60,6 +60,11 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = ) { return true; } + // LGAI EXAONE models expose an OpenAI-compatible API with tool + // calling support when served via frameworks like vLLM + if (model.toLowerCase().includes("exaone")) { + return true; + } // firworks-ai https://docs.fireworks.ai/guides/function-calling if (model.startsWith("accounts/fireworks/models/")) { switch (model.substring(26)) { @@ -299,6 +304,8 @@ export function isRecommendedAgentModel(modelName: string): boolean { [/gpt/, /4/], [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/], [/claude/, /opus/, /-4/], + // EXAONE 4.0 and 4.0-1 variants + [/exaone/, /4\.0(-1)?/], ]; for (const combo of recs) { if (combo.every((regex) => modelName.toLowerCase().match(regex))) { @@ -311,6 +318,11 @@ export function modelSupportsNativeTools(modelDescription: ModelDescription) { if (modelDescription.capabilities?.tools !== undefined) { return modelDescription.capabilities.tools; } + // EXAONE 4.0 models advertise tool-calling capability regardless of + // the provider used to serve them. + if (modelDescription.model.toLowerCase().includes("exaone")) { + return true; + } const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; if (!providerSupport) { return false; diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index f68ac0555..c2d10702d 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -302,6 +302,32 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["nebius"], isOpenSource: true, }, + exaone32B: { + title: "EXAONE 4.0-1 32B", + description: + "LG AI Research's 32B model with integrated reasoning and agentic tool use capabilities.", + refUrl: "https://huggingface.co/LGAI-EXAONE/EXAONE-4.0-1.32B", + params: { + title: "EXAONE-4.0-1.32B", + model: "LGAI-EXAONE/EXAONE-4.0-1.32B", + contextLength: 131072, + }, + providerOptions: ["openai"], + isOpenSource: true, + }, + exaone12B: { + title: "EXAONE 4.0-1.2B", + description: + "Compact EXAONE 4.0 model suitable for on-device use while retaining tool calling support.", + refUrl: "https://huggingface.co/LGAI-EXAONE/EXAONE-4.0-1.2B", + params: { + title: "EXAONE-4.0-1.2B", + model: "LGAI-EXAONE/EXAONE-4.0-1.2B", + contextLength: 65536, + }, + providerOptions: ["openai"], + isOpenSource: true, + }, moonshotChat: { title: "Moonshot Chat", description: "Moonshot AI provides high-performance large language models", From 9d60f162b44bd54647f1c292c8af1ee430ca35f5 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Tue, 5 Aug 2025 09:21:56 -0400 Subject: [PATCH 006/102] fix: handle exaone version naming --- core/llm/toolSupport.ts | 4 ++-- gui/src/pages/AddNewModel/configs/models.ts | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 177de83ca..562c315cc 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -304,8 +304,8 @@ export function isRecommendedAgentModel(modelName: string): boolean { [/gpt/, /4/], [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/], [/claude/, /opus/, /-4/], - // EXAONE 4.0 and 4.0-1 variants - [/exaone/, /4\.0(-1)?/], + // EXAONE 4.0, 4.0-1, and 4.0.1 variants + [/exaone/, /4\.0(?:[-.]1)?/], ]; for (const combo of recs) { if (combo.every((regex) => modelName.toLowerCase().match(regex))) { diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index c2d10702d..476a8c9e9 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -303,13 +303,13 @@ export const models: { [key: string]: ModelPackage } = { isOpenSource: true, }, exaone32B: { - title: "EXAONE 4.0-1 32B", + title: "EXAONE 4.0.1-32B", description: "LG AI Research's 32B model with integrated reasoning and agentic tool use capabilities.", - refUrl: "https://huggingface.co/LGAI-EXAONE/EXAONE-4.0-1.32B", + refUrl: "https://huggingface.co/LGAI-EXAONE/EXAONE-4.0.1-32B", params: { - title: "EXAONE-4.0-1.32B", - model: "LGAI-EXAONE/EXAONE-4.0-1.32B", + title: "EXAONE-4.0.1-32B", + model: "LGAI-EXAONE/EXAONE-4.0.1-32B", contextLength: 131072, }, providerOptions: ["openai"], From 97d426bf68f402ff9cfb5691ad6b5384683c3909 Mon Sep 17 00:00:00 2001 From: Keerthana Panyam Date: Tue, 29 Jul 2025 14:38:45 -0400 Subject: [PATCH 007/102] restrict autocomplete context from other files in config.yaml added schema properties and tabAutocompleteOptions schema to to support in YAML config file, allowing proper override of default values from parameters.ts. added .optional() tags to tabAutocompleteOptions properties to enable partial override from the config.yaml file. --- core/config/yaml/loadYaml.ts | 1 + .../mainInput/Lump/EditBlockButton.tsx | 2 +- packages/config-types/src/index.ts | 29 ++++++++++++------- packages/config-yaml/src/load/unroll.ts | 10 ++++++- packages/config-yaml/src/schemas/index.ts | 5 ++++ 5 files changed, 34 insertions(+), 13 deletions(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index dbfd88a08..94aba67be 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -429,6 +429,7 @@ async function configYamlToContinueConfig(options: { })), false, ); + continueConfig.tabAutocompleteOptions = config.tabAutocompleteOptions; return { config: continueConfig, errors: localErrors }; } diff --git a/gui/src/components/mainInput/Lump/EditBlockButton.tsx b/gui/src/components/mainInput/Lump/EditBlockButton.tsx index 19780e875..0bce9f642 100644 --- a/gui/src/components/mainInput/Lump/EditBlockButton.tsx +++ b/gui/src/components/mainInput/Lump/EditBlockButton.tsx @@ -6,7 +6,7 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger"; type SectionKey = Exclude< keyof ConfigYaml, - "name" | "version" | "schema" | "metadata" + "name" | "version" | "schema" | "metadata" | "tabAutocompleteOptions" >; interface EditBlockButtonProps { diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 11c1ca20c..942f75219 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -136,21 +136,28 @@ export const uiOptionsSchema = z.object({ export type UiOptions = z.infer; export const tabAutocompleteOptionsSchema = z.object({ - disable: z.boolean(), - maxPromptTokens: z.number(), - debounceDelay: z.number(), - maxSuffixPercentage: z.number(), - prefixPercentage: z.number(), + disable: z.boolean().optional(), + maxPromptTokens: z.number().optional(), + debounceDelay: z.number().optional(), + maxSuffixPercentage: z.number().optional(), + prefixPercentage: z.number().optional(), transform: z.boolean().optional(), template: z.string().optional(), - multilineCompletions: z.enum(["always", "never", "auto"]), - slidingWindowPrefixPercentage: z.number(), - slidingWindowSize: z.number(), - useCache: z.boolean(), - onlyMyCode: z.boolean(), - useRecentlyEdited: z.boolean(), + multilineCompletions: z.enum(["always", "never", "auto"]).optional(), + slidingWindowPrefixPercentage: z.number().optional(), + slidingWindowSize: z.number().optional(), + useCache: z.boolean().optional(), + onlyMyCode: z.boolean().optional(), + useRecentlyEdited: z.boolean().optional(), + useRecentlyOpened: z.boolean().optional(), disableInFiles: z.array(z.string()).optional(), useImports: z.boolean().optional(), + // Experimental options + experimental_includeClipboard: z.boolean().optional(), + experimental_includeRecentlyVisitedRanges: z.boolean().optional(), + experimental_includeRecentlyEditedRanges: z.boolean().optional(), + experimental_includeDiff: z.boolean().optional(), + experimental_enableStaticContextualization: z.boolean().optional(), }); export type TabAutocompleteOptions = z.infer< typeof tabAutocompleteOptionsSchema diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index adbe45324..6ab35bc21 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -309,11 +309,19 @@ export async function unrollBlocks( const unrolledAssistant: AssistantUnrolled = { name: assistant.name, version: assistant.version, + ...(assistant.tabAutocompleteOptions && { + tabAutocompleteOptions: assistant.tabAutocompleteOptions, + }), }; const sections: (keyof Omit< ConfigYaml, - "name" | "version" | "rules" | "schema" | "metadata" + | "name" + | "version" + | "rules" + | "schema" + | "metadata" + | "tabAutocompleteOptions" >)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"]; // Process all sections in parallel diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index e15a5655d..8ef2c1a61 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -1,4 +1,5 @@ import * as z from "zod"; +import { tabAutocompleteOptionsSchema } from "../../../config-types/src/index.js"; import { commonModelSlugs } from "./commonSlugs.js"; import { dataSchema } from "./data/index.js"; import { @@ -145,6 +146,7 @@ export const configYamlSchema = baseConfigYamlSchema.extend({ .optional(), prompts: z.array(blockOrSchema(promptSchema)).optional(), docs: z.array(blockOrSchema(docSchema)).optional(), + tabAutocompleteOptions: tabAutocompleteOptionsSchema.optional(), }); export type ConfigYaml = z.infer; @@ -157,6 +159,7 @@ export const assistantUnrolledSchema = baseConfigYamlSchema.extend({ rules: z.array(ruleSchema.nullable()).optional(), prompts: z.array(promptSchema.nullable()).optional(), docs: z.array(docSchema.nullable()).optional(), + tabAutocompleteOptions: tabAutocompleteOptionsSchema.optional(), }); export type AssistantUnrolled = z.infer; @@ -169,6 +172,7 @@ export const assistantUnrolledSchemaNonNullable = baseConfigYamlSchema.extend({ rules: z.array(ruleSchema).optional(), prompts: z.array(promptSchema).optional(), docs: z.array(docSchema).optional(), + tabAutocompleteOptions: tabAutocompleteOptionsSchema.optional(), }); export type AssistantUnrolledNonNullable = z.infer< @@ -254,6 +258,7 @@ export const configSchema = z.object({ proxy: z.string().optional(), api_base: z.string().optional(), api_key: z.string().optional(), + tabAutocompleteOptions: tabAutocompleteOptionsSchema.optional(), }); export type Config = z.infer; From f1a6c8eb0c46a04e9056a1accce8f193a32b92cd Mon Sep 17 00:00:00 2001 From: Keerthana Panyam Date: Thu, 31 Jul 2025 13:30:45 -0400 Subject: [PATCH 008/102] changing import from config-types package importing from the built config-types package instead of its src/ --- core/autocomplete/CompletionProvider.ts | 2 +- packages/config-yaml/src/schemas/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index d51c15853..143dbf269 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -10,8 +10,8 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { renderPromptWithTokenLimit } from "./templating/index.js"; import { getAllSnippetsWithoutRace } from "./snippets/index.js"; +import { renderPromptWithTokenLimit } from "./templating/index.js"; import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 8ef2c1a61..dc1ff9c9d 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -1,5 +1,5 @@ +import { tabAutocompleteOptionsSchema } from "@continuedev/config-types"; import * as z from "zod"; -import { tabAutocompleteOptionsSchema } from "../../../config-types/src/index.js"; import { commonModelSlugs } from "./commonSlugs.js"; import { dataSchema } from "./data/index.js"; import { From 8da18259a37c676d8c0cd9c91a11f7e9406e5335 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Tue, 5 Aug 2025 22:33:17 -0400 Subject: [PATCH 009/102] Add lgai-exaone to openrouter options --- core/llm/toolSupport.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 0cd2e32ba..3711eaa1b 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -269,6 +269,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "deepseek/deepseek-chat", "meta-llama/llama-4", "all-hands/openhands-lm-32b", + "lgai-exaone/exaone", ]; for (const prefix of supportedPrefixes) { if (model.toLowerCase().startsWith(prefix)) { From b821fb2448f07ae930e1bba7fa505e7d1217a110 Mon Sep 17 00:00:00 2001 From: vldf Date: Wed, 6 Aug 2025 12:19:47 +0300 Subject: [PATCH 010/102] Feat: disable edit prompt action for the init prompt --- .../components/mainInput/Lump/sections/PromptsSection.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index 10fb767b3..beb4b87e7 100644 --- a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -60,6 +60,9 @@ function PromptRow({ } }; + const canEdit = + prompt.promptFile && !prompt.promptFile.startsWith("builtin:"); + return (
Date: Wed, 6 Aug 2025 09:02:34 -0400 Subject: [PATCH 011/102] Add exaone to ollama provider --- core/llm/toolSupport.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 3711eaa1b..7fc35c104 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -181,6 +181,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "firefunction-v2", "mistral", "devstral", + "exaone", ].some((part) => modelName.toLowerCase().includes(part)) ) { return true; From 75fd68d8c97fb977f7ee3242934af358cbcff406 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Wed, 6 Aug 2025 23:07:30 -0400 Subject: [PATCH 012/102] Remove EXAONE from OpenRouter --- core/llm/toolSupport.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 41e43bf8c..d3a8684d0 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -277,7 +277,6 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "deepseek/deepseek-chat", "meta-llama/llama-4", "all-hands/openhands-lm-32b", - "lgai-exaone/exaone", ]; for (const prefix of supportedPrefixes) { if (model.toLowerCase().startsWith(prefix)) { From d111bc5f3a81df9be92b72bfba1008875785aa67 Mon Sep 17 00:00:00 2001 From: vldf Date: Thu, 7 Aug 2025 11:26:47 +0300 Subject: [PATCH 013/102] Fix: add missing space --- gui/src/components/mainInput/Lump/sections/PromptsSection.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index beb4b87e7..ce7721d8c 100644 --- a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -81,7 +81,7 @@ function PromptRow({
From aed9153e6ad11861e2f7db27aaa9031522006d93 Mon Sep 17 00:00:00 2001 From: vldf Date: Thu, 7 Aug 2025 13:37:04 +0300 Subject: [PATCH 014/102] Fix: remove redundant `call` word from the default agent system 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 edb5753fb..eebcc8510 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -61,7 +61,7 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ You are in agent mode. - If you need to use multiple tools, you can call call multiple read only tools simultaneously. + If you need to use multiple tools, you can call multiple read only tools simultaneously. ${CODEBLOCK_FORMATTING_INSTRUCTIONS} `; From a266903de19567701152d24577c24a406fb663b5 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 7 Aug 2025 18:55:19 +0530 Subject: [PATCH 015/102] improve: tool call spacing and margins --- .../StyledMarkdownPreview/StepContainerPreToolbar/index.tsx | 2 +- gui/src/pages/gui/ToolCallDiv/index.tsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index fd5f0150a..4679c232c 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -263,7 +263,7 @@ export function StepContainerPreToolbar({ } return ( -
+
+
( -
+
{renderToolCall(toolCallState)}
)); From e394a9aa95079b45ebff1d4c95a97a1f74d41eec Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 7 Aug 2025 19:42:51 +0530 Subject: [PATCH 016/102] improve: open conversation summary be default --- gui/src/components/StepContainer/ConversationSummary.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gui/src/components/StepContainer/ConversationSummary.tsx b/gui/src/components/StepContainer/ConversationSummary.tsx index 5260da58f..392b757da 100644 --- a/gui/src/components/StepContainer/ConversationSummary.tsx +++ b/gui/src/components/StepContainer/ConversationSummary.tsx @@ -1,12 +1,12 @@ -import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid"; import { TrashIcon } from "@heroicons/react/24/outline"; +import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid"; import { ChatHistoryItem } from "core"; import { useState } from "react"; -import { AnimatedEllipsis } from "../AnimatedEllipsis"; import { useAppSelector } from "../../redux/hooks"; -import StyledMarkdownPreview from "../StyledMarkdownPreview"; import { useDeleteCompaction } from "../../util/compactConversation"; +import { AnimatedEllipsis } from "../AnimatedEllipsis"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; interface ConversationSummaryProps { item: ChatHistoryItem; @@ -14,7 +14,7 @@ interface ConversationSummaryProps { } export default function ConversationSummary(props: ConversationSummaryProps) { - const [open, setOpen] = useState(false); + const [open, setOpen] = useState(true); const isLoading = useAppSelector( (state) => state.session.compactionLoading[props.index] || false, ); From bc3375e818acc7f80b987c16ad3a7ace009f40c9 Mon Sep 17 00:00:00 2001 From: Jazzcort Date: Tue, 22 Jul 2025 09:43:02 -0400 Subject: [PATCH 017/102] Fix: Remove duplicate blocks and provide config warnings This patch is to address the following cases that duplicate blocks appear in the UI and confuse users: 1. When users refer to a local block with "- uses", if the block is already in the default directories (e.g. ~/.continue/models or /.continue/models) and users don't override its name attribute, the duplicate block will appear in the UI. 2. When users have duplicate block names among each block type in their assistant config. 3. When the injected blocks have duplicate names with the assistant config for the corresponding block type. The duplicate blocks in the UI is confusing, especially in the model selection. This patch add a blockDuplicationDetector to detect duplication. When a duplication is detected, we remove the duplicate item and push a config error to the result to warn the users that having duplicate names is not the best practice to set up their config. The detecting order: assistant config -> injected blocks To detect duplication, all block types use "name" as the identifier except for rules and context. For rules, if it's an rule object, we use the "name" attribute. Otherwise, we use its string content as the identifier. For context, the "provider" attribute is used as the identifier. The detection only happens under assistant level, which means you can have assistants with duplicate names. --- .../config-yaml/src/__tests__/index.test.ts | 82 +++++++++++++++++-- .../local-files/duplicate-test-assistant.yaml | 39 +++++++++ .../src/__tests__/local-files/mcpServer.yaml | 8 ++ .../src/__tests__/local-files/prompt.yaml | 7 ++ .../src/__tests__/local-files/rules.yaml | 6 ++ .../src/load/blockDuplicationDetector.ts | 76 +++++++++++++++++ packages/config-yaml/src/load/unroll.ts | 35 ++++++-- 7 files changed, 242 insertions(+), 11 deletions(-) create mode 100644 packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml create mode 100644 packages/config-yaml/src/__tests__/local-files/mcpServer.yaml create mode 100644 packages/config-yaml/src/__tests__/local-files/prompt.yaml create mode 100644 packages/config-yaml/src/__tests__/local-files/rules.yaml create mode 100644 packages/config-yaml/src/load/blockDuplicationDetector.ts diff --git a/packages/config-yaml/src/__tests__/index.test.ts b/packages/config-yaml/src/__tests__/index.test.ts index af11cf0c4..5e0a3cdb9 100644 --- a/packages/config-yaml/src/__tests__/index.test.ts +++ b/packages/config-yaml/src/__tests__/index.test.ts @@ -93,9 +93,11 @@ describe("E2E Scenarios", () => { const registry: Registry = { getContent: async function (id: PackageIdentifier): Promise { const slug = packageIdentifierToShorthandSlug(id); - return fs - .readFileSync(`./src/__tests__/packages/${slug}.yaml`) - .toString(); + const filePath = + id.uriType === "slug" + ? `./src/__tests__/packages/${slug}.yaml` + : id.filePath; + return fs.readFileSync(filePath).toString(); }, }; @@ -230,7 +232,7 @@ describe("E2E Scenarios", () => { orgScopeId: "test-org", currentUserSlug: "test-user", onPremProxyUrl: null, - // Add an injected block + // Add injected blocks injectBlocks: [ { uriType: "slug", @@ -240,11 +242,16 @@ describe("E2E Scenarios", () => { versionSlug: "latest", }, }, + { + uriType: "file", + filePath: "./src/__tests__/local-files/rules.yaml", + }, ], }, ); const config = unrolledConfig.config; + const errors = unrolledConfig.errors; // The original rules array should have two items expect(config?.rules?.length).toBe(3); // Now 3 with the injected block @@ -255,7 +262,72 @@ describe("E2E Scenarios", () => { ); // Check the injected doc block was added - expect(config?.rules?.[2]).toBe("Be kind"); + expect( + typeof config?.rules?.[2] !== "string" && + config?.rules?.[2]?.rule === "Be humble", + ); + + // Check if we receive one error that is caused by duplicate rules + expect(errors?.length).toBe(1); + expect(errors?.[0].message.includes("Duplicate rules detected")); + }); + + it("duplicate detection should happen in the assistant config first and then the intected blocks", async () => { + const unrolledConfig = await unrollAssistant( + { + uriType: "file", + filePath: "./src/__tests__/local-files/duplicate-test-assistant.yaml", + }, + registry, + { + renderSecrets: true, + platformClient, + orgScopeId: "test-org", + currentUserSlug: "test-user", + onPremProxyUrl: null, + // Add injected blocks + injectBlocks: [ + { + uriType: "file", + filePath: "./src/__tests__/local-files/rules.yaml", + }, + { + uriType: "file", + filePath: "./src/__tests__/local-files/mcpServer.yaml", + }, + { + uriType: "file", + filePath: "./src/__tests__/local-files/prompt.yaml", + }, + ], + }, + ); + + const config = unrolledConfig.config; + const errors = unrolledConfig.errors; + + // Check if all the duplicate blocks get removed + expect(config?.models?.length).toBe(1); + expect(config?.context?.length).toBe(1); + expect(config?.mcpServers?.length).toBe(1); + expect(config?.rules?.length).toBe(1); + expect(config?.prompts?.length).toBe(1); + expect(config?.docs?.length).toBe(1); + + // Check if there are 8 duplication detected + expect(errors?.length).toBe(8); + + // Beginning of the assistant config duplication check + expect( + errors?.[0].message.includes("Duplicate models named gpt-5 detected"), + ).toBe(true); + // Beginning of the injected blocks duplication check + expect(errors?.[4].message.includes("Duplicate rules detected")).toBe(true); + expect( + errors?.[6].message.includes( + "Duplicate mcpServers named Browser search detected", + ), + ).toBe(true); }); it.skip("should prioritize org over user / package secrets", () => {}); diff --git a/packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml b/packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml new file mode 100644 index 000000000..7f5eca13a --- /dev/null +++ b/packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml @@ -0,0 +1,39 @@ +name: Duplicate Test Assistant +version: 0.0.1 +schema: v1 + +docs: + - name: React + startUrl: https://react.dev + - name: React + startUrl: https://react.dev + +rules: + - Be humble + - uses: ./src/__tests__/local-files/rules.yaml + +models: + - name: gpt-5 + provider: openai + model: gpt-5 + apiKey: ${{ secrets.OPENAI_API_KEY }} + roles: + - chat + + - name: gpt-5 + provider: openai + model: gpt-5 + apiKey: ${{ secrets.OPENAI_API_KEY }} + roles: + - chat + +mcpServers: + - uses: ./src/__tests__/local-files/mcpServer.yaml + +prompts: + - uses: ./src/__tests__/local-files/prompt.yaml + - uses: ./src/__tests__/local-files/prompt.yaml + +context: + - provider: doc + - provider: doc diff --git a/packages/config-yaml/src/__tests__/local-files/mcpServer.yaml b/packages/config-yaml/src/__tests__/local-files/mcpServer.yaml new file mode 100644 index 000000000..b6be73016 --- /dev/null +++ b/packages/config-yaml/src/__tests__/local-files/mcpServer.yaml @@ -0,0 +1,8 @@ +name: Local MCP Server +version: 0.0.1 +schema: v1 +mcpServers: + - name: Browser search + command: npx + args: + - "@playwright/mcp@latest" diff --git a/packages/config-yaml/src/__tests__/local-files/prompt.yaml b/packages/config-yaml/src/__tests__/local-files/prompt.yaml new file mode 100644 index 000000000..7ea2c2707 --- /dev/null +++ b/packages/config-yaml/src/__tests__/local-files/prompt.yaml @@ -0,0 +1,7 @@ +name: Local prompt +version: 0.0.1 +schema: v1 +prompts: + - name: duplication test + description: test purpose + prompt: Please check that this prompt should only appear once diff --git a/packages/config-yaml/src/__tests__/local-files/rules.yaml b/packages/config-yaml/src/__tests__/local-files/rules.yaml new file mode 100644 index 000000000..6bfca2423 --- /dev/null +++ b/packages/config-yaml/src/__tests__/local-files/rules.yaml @@ -0,0 +1,6 @@ +name: Rules +version: 0.0.1 +schema: v1 + +rules: + - Be humble diff --git a/packages/config-yaml/src/load/blockDuplicationDetector.ts b/packages/config-yaml/src/load/blockDuplicationDetector.ts new file mode 100644 index 000000000..78e5ce980 --- /dev/null +++ b/packages/config-yaml/src/load/blockDuplicationDetector.ts @@ -0,0 +1,76 @@ +import { BLOCK_TYPES, BlockType } from "./getBlockType.js"; + +export class BlockDuplicationDetector { + private records: Map>; + + constructor() { + this.records = new Map(); + for (const blockType of BLOCK_TYPES) { + this.records.set(blockType, new Set()); + } + } + + private isRuleDuplicated(rule: any): boolean { + if (typeof rule === "string") { + return this.check(rule, "rules"); + } else { + return this.check(rule.name, "rules"); + } + } + + private isContextDuplicated(context: any): boolean { + return this.check(context.provider, "context"); + } + + private isCommonBlockDuplicated(block: any, blockType: BlockType): boolean { + return this.check(block.name, blockType); + } + + private check(identifier: string, blockType: BlockType): boolean { + if (this.records.get(blockType)!.has(identifier)) { + return true; + } else { + this.records.get(blockType)!.add(identifier); + return false; + } + } + + // Check if the name is duplicated within the same blockType + isDuplicated( + block: any, + blockType: BlockType, + injectError?: (errorMsg: string) => void, + ): boolean { + // Not checking any null or undefined object + if (block === null || block === undefined) { + return false; + } + + switch (blockType) { + case "rules": + if (this.isRuleDuplicated(block)) { + injectError?.( + `Duplicate rules${typeof block === "string" ? "" : ` named ${block.name}`} detected. The duplicate one has been deleted for preventing unexpected behavior.`, + ); + return true; + } + return false; + case "context": + if (this.isContextDuplicated(block)) { + injectError?.( + `Duplicate ${block.provider} context providers detected. The duplicate one has been deleted for preventing unexpected behavior.`, + ); + return true; + } + return false; + default: + if (this.isCommonBlockDuplicated(block, blockType)) { + injectError?.( + `Duplicate ${blockType} named ${block.name} detected. The duplicate one has been deleted for preventing unexpected behavior.`, + ); + return true; + } + return false; + } + } +} diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index adbe45324..5225f79aa 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -20,6 +20,7 @@ import { Rule, } from "../schemas/index.js"; import { ConfigResult, ConfigValidationError } from "../validation.js"; +import { BlockDuplicationDetector } from "./blockDuplicationDetector.js"; import { packageIdentifierToShorthandSlug, useProxyForUnrenderedSecrets, @@ -306,6 +307,13 @@ export async function unrollBlocks( ): Promise> { const errors: ConfigValidationError[] = []; + function injectDuplicationError(errorMsg: string) { + errors.push({ + fatal: false, + message: errorMsg, + }); + } + const unrolledAssistant: AssistantUnrolled = { name: assistant.name, version: assistant.version, @@ -484,7 +492,7 @@ export async function unrollBlocks( const injectedResults = await Promise.all(injectedBlockPromises); const injectedErrors: ConfigValidationError[] = []; const injectedBlocks: { - blockType: string; + blockType: BlockType; resolvedBlock: any; source?: string; }[] = []; @@ -521,16 +529,27 @@ export async function unrollBlocks( errors.push(...rulesResult.errors); errors.push(...injectedResult.errors); + const detector = new BlockDuplicationDetector(); + // Assign section results for (const sectionResult of sectionResults) { if (sectionResult.blocks) { - unrolledAssistant[sectionResult.section] = sectionResult.blocks; + unrolledAssistant[sectionResult.section] = sectionResult.blocks.filter( + (block) => + !detector.isDuplicated( + block, + sectionResult.section, + injectDuplicationError, + ), + ); } } // Assign rules result if (rulesResult.rules) { - unrolledAssistant.rules = rulesResult.rules; + unrolledAssistant.rules = rulesResult.rules.filter( + (rule) => !detector.isDuplicated(rule, "rules", injectDuplicationError), + ); } // Add injected blocks @@ -539,16 +558,20 @@ export async function unrollBlocks( resolvedBlock, source, } of injectedResult.injectedBlocks) { - const key = blockType as BlockType; + const key = blockType; if (!unrolledAssistant[key]) { unrolledAssistant[key] = []; } - const blocksWithSourceFiles = injectLocalSourceFile( + + const filteredBlocks = injectLocalSourceFile( key, resolvedBlock, source, + ).filter( + (block: any) => + !detector.isDuplicated(block, blockType, injectDuplicationError), ); - unrolledAssistant[key]?.push(...blocksWithSourceFiles); + unrolledAssistant[key]?.push(...filteredBlocks); } const configResult: ConfigResult = { From ab4bb9c1579b591bffb713b90e7cd207586f4dc2 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Aug 2025 11:56:31 -0700 Subject: [PATCH 018/102] fix: jetbrains release script (#7050) * fix: jetbrains release script - build only option * fix: channel name --- .github/workflows/jetbrains-release.yaml | 117 ++++++++++++++--------- 1 file changed, 73 insertions(+), 44 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index d2eb53938..72bd84235 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -9,10 +9,18 @@ on: types: [prereleased] workflow_dispatch: inputs: - publish_build: - description: "Whether or not to publish the built extension to the JetBrains marketplace" + build_only: + description: "If true, only build the extension for the given channels, don't publish" required: true - default: false + default: "true" + eap_channel: + description: "If true, build/publish the extension to the EAP channel" + required: true + default: "true" + stable_channel: + description: "If true, build/publish the extension to the Stable channel" + required: true + default: "true" defaults: run: @@ -37,50 +45,50 @@ jobs: echo "should_run=false" >> $GITHUB_OUTPUT fi - bump-version: - runs-on: ubuntu-latest - needs: - - check_release_name - if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true' - permissions: - contents: write - pull-requests: write - steps: - # 0. Setup git - - name: Checkout - uses: actions/checkout@v4 + # bump-version: + # runs-on: ubuntu-latest + # needs: + # - check_release_name + # if: github.event_name != 'workflow_dispatch' || github.event.inputs.eap_channel == 'true' || github.event.inputs.stable_channel == 'true' + # permissions: + # contents: write + # pull-requests: write + # steps: + # # 0. Setup git + # - name: Checkout + # uses: actions/checkout@v4 - - name: Set up Git - run: | - git config --local user.email "action@github.com" - git config --local user.name "GitHub Action" + # - name: Set up Git + # run: | + # git config --local user.email "action@github.com" + # git config --local user.name "GitHub Action" - - name: Create PR branch - run: | - BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)" - git checkout -b $BRANCH_NAME - echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV + # - name: Create PR branch + # run: | + # BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)" + # git checkout -b $BRANCH_NAME + # echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV - - name: Bump version in gradle.properties - run: | - awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties - rm -rf tmp - NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2) - echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV + # - name: Bump version in gradle.properties + # run: | + # awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties + # rm -rf tmp + # NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2) + # echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV - - name: Create Pull Request - uses: peter-evans/create-pull-request@v7 - with: - token: ${{ secrets.CI_GITHUB_TOKEN }} - commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" - title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" - body: | - Automated PR to bump the JetBrains extension version after successful pre-release publication. + # - name: Create Pull Request + # uses: peter-evans/create-pull-request@v7 + # with: + # token: ${{ secrets.CI_GITHUB_TOKEN }} + # commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" + # title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" + # body: | + # Automated PR to bump the JetBrains extension version after successful pre-release publication. - - Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }} - branch: ${{ env.BRANCH_NAME }} - base: main - delete-branch: true + # - Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }} + # branch: ${{ env.BRANCH_NAME }} + # base: main + # delete-branch: true # Prepare and publish the plugin to JetBrains Marketplace repository build: @@ -223,9 +231,30 @@ jobs: # apple-product-id: dev.continue.continue-binary # options: --options runtime --entitlements entitlements.xml + # Build the plugin if not publishing + - name: Build EAP Plugin (no publish) + if: github.event_name != 'release' && github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only == 'true' + env: + PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + RELEASE_CHANNEL: eap + run: ./gradlew buildPlugin --info --stacktrace + + - name: Build Stable Plugin (no publish) + if: github.event_name != 'release' && github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only == 'true' + env: + PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + RELEASE_CHANNEL: default + run: ./gradlew buildPlugin --info --stacktrace + # Publish the plugin to JetBrains Marketplace - name: Publish EAP Plugin - if: github.event_name == 'release' || github.event.inputs.publish_build == 'true' + if: github.event_name == 'release' || (github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only != 'true') env: PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} @@ -235,7 +264,7 @@ jobs: run: ./gradlew publishPlugin --info --stacktrace - name: Publish Stable Plugin - if: github.event_name == 'release' || github.event.inputs.publish_build == 'true' + if: github.event_name == 'release' || (github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only != 'true') env: PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} From 01812e598f2e5b3f201c1329388d3133b0c935b7 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Aug 2025 13:36:26 -0700 Subject: [PATCH 019/102] feat: gpt-5 support (#7054) * fix: gpt-5 support * fix: gpt 5 context length * fix: broken test file --- core/llm/llms/OpenAI.test.ts | 32 +++++++++---------- core/llm/llms/OpenAI.ts | 16 +++++----- core/llm/toolSupport.ts | 10 +++--- gui/src/pages/AddNewModel/configs/models.ts | 12 +++++++ .../pages/AddNewModel/configs/providers.ts | 5 +-- packages/llm-info/src/providers/openai.ts | 9 ++++++ packages/openai-adapters/src/apis/OpenAI.ts | 2 +- 7 files changed, 55 insertions(+), 31 deletions(-) diff --git a/core/llm/llms/OpenAI.test.ts b/core/llm/llms/OpenAI.test.ts index 46c8b4e23..8daf93852 100644 --- a/core/llm/llms/OpenAI.test.ts +++ b/core/llm/llms/OpenAI.test.ts @@ -5,30 +5,30 @@ describe("OpenAI", () => { const openai = new OpenAI({ model: "o3-mini", }); - expect(openai.isOSeriesModel("o4-mini")).toBeTruthy(); - expect(openai.isOSeriesModel("o3-mini")).toBeTruthy(); - expect(openai.isOSeriesModel("o1-mini")).toBeTruthy(); - expect(openai.isOSeriesModel("o1")).toBeTruthy(); - expect(openai.isOSeriesModel("o3")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o4-mini")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o3-mini")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o1-mini")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o1")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o3")).toBeTruthy(); // artificially correct samples for future models - expect(openai.isOSeriesModel("o5-mini")).toBeTruthy(); - expect(openai.isOSeriesModel("o6")).toBeTruthy(); - expect(openai.isOSeriesModel("o77")).toBeTruthy(); - expect(openai.isOSeriesModel("o54-mini")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o5-mini")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o6")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o77")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o54-mini")).toBeTruthy(); }); test("should identify incorrect o-series models", () => { const openai = new OpenAI({ model: "o3-mini", }); - expect(openai.isOSeriesModel("gpt-o4-mini")).toBeFalsy(); - expect(openai.isOSeriesModel("gpt-4.5")).toBeFalsy(); - expect(openai.isOSeriesModel("gpt-4.1")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("gpt-o4-mini")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("gpt-4.5")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("gpt-4.1")).toBeFalsy(); // artificially wrong samples - expect(openai.isOSeriesModel("os1")).toBeFalsy(); - expect(openai.isOSeriesModel("so1")).toBeFalsy(); - expect(openai.isOSeriesModel("ao31")).toBeFalsy(); - expect(openai.isOSeriesModel("1os")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("os1")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("so1")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("ao31")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("1os")).toBeFalsy(); }); }); diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index c48349f83..27006aea1 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -36,12 +36,12 @@ function isChatOnlyModel(model: string): boolean { return model.startsWith("gpt") || model.startsWith("o"); } -const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => { +const formatMessageForO1OrGpt5 = (messages: ChatCompletionMessageParam[]) => { return messages?.map((message: any) => { if (message?.role === "system") { return { ...message, - role: "user", + role: "developer", }; } @@ -77,8 +77,8 @@ class OpenAI extends BaseLLM { return model; } - public isOSeriesModel(model?: string): boolean { - return !!model && !!model.match(/^o[0-9]+/); + public isOSeriesOrGpt5Model(model?: string): boolean { + return !!model && (!!model.match(/^o[0-9]+/) || model.includes("gpt-5")); } private isFireworksAiModel(model?: string): boolean { @@ -139,13 +139,13 @@ class OpenAI extends BaseLLM { finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); // OpenAI o1-preview and o1-mini or o3-mini: - if (this.isOSeriesModel(options.model)) { + if (this.isOSeriesOrGpt5Model(options.model)) { // a) use max_completion_tokens instead of max_tokens finalOptions.max_completion_tokens = options.maxTokens; finalOptions.max_tokens = undefined; // b) don't support system message - finalOptions.messages = formatMessageForO1(finalOptions.messages); + finalOptions.messages = formatMessageForO1OrGpt5(finalOptions.messages); } if (options.model === "o1") { @@ -241,13 +241,13 @@ class OpenAI extends BaseLLM { body.stop = body.stop?.slice(0, this.getMaxStopWords()); // OpenAI o1-preview and o1-mini or o3-mini: - if (this.isOSeriesModel(body.model)) { + if (this.isOSeriesOrGpt5Model(body.model)) { // a) use max_completion_tokens instead of max_tokens body.max_completion_tokens = body.max_tokens; body.max_tokens = undefined; // b) don't support system message - body.messages = formatMessageForO1(body.messages); + body.messages = formatMessageForO1OrGpt5(body.messages); } if (body.model === "o1") { diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 2700361cc..1417d8307 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -54,18 +54,20 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, openai: (model) => { + const lower = model.toLowerCase(); // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling if ( - model.toLowerCase().startsWith("gpt-4") || - model.toLowerCase().startsWith("o3") + lower.startsWith("gpt-4") || + lower.startsWith("gpt-5") || + lower.startsWith("o3") ) { return true; } - if (model.toLowerCase().includes("gpt-oss")) { + if (lower.includes("gpt-oss")) { return true; } // https://ai.google.dev/gemma/docs/capabilities/function-calling - if (model.toLowerCase().startsWith("gemma")) { + if (lower.startsWith("gemma")) { return true; } // firworks-ai https://docs.fireworks.ai/guides/function-calling diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index d0857d7db..b5c4bbae5 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -1095,6 +1095,18 @@ export const models: { [key: string]: ModelPackage } = { icon: "cohere.png", isOpenSource: false, }, + gpt5: { + title: "GPT-5", + description: "OpenAI's next-generation, high-intelligence flagship model", + params: { + model: "gpt-5", + contextLength: 400_000, + title: "GPT-5", + }, + providerOptions: ["openai"], + icon: "openai.png", + isOpenSource: false, + }, gpt4turbo: { title: "GPT-4 Turbo", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index d210da9d6..071f96be9 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -52,12 +52,13 @@ export const providers: Partial> = { openai: { title: "OpenAI", provider: "openai", - description: "Use gpt-4, gpt-3.5-turbo, or any other OpenAI model", + description: "Use gpt-5, gpt-4, or any other OpenAI model", longDescription: - "Use gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.", + "Use gpt-5, gpt-4, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.", icon: "openai.png", tags: [ModelProviderTags.RequiresApiKey], packages: [ + models.gpt5, models.gpt4o, models.gpt4omini, models.gpt4turbo, diff --git a/packages/llm-info/src/providers/openai.ts b/packages/llm-info/src/providers/openai.ts index a15dd3089..820559308 100644 --- a/packages/llm-info/src/providers/openai.ts +++ b/packages/llm-info/src/providers/openai.ts @@ -75,6 +75,15 @@ export const OpenAi: ModelProvider = { contextLength: 128000, maxCompletionTokens: 4096, }, + // gpt-5 + { + model: "gpt-5", + displayName: "GPT-5", + contextLength: 400000, + maxCompletionTokens: 128000, + regex: /gpt-5/, + recommendedFor: ["chat"], + }, // gpt-4o { model: "gpt-4o", diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index c1e356fa5..714ce67fd 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -38,7 +38,7 @@ export class OpenAIApi implements BaseLlmApi { // o-series models - only apply for official OpenAI API const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/"; if (isOfficialOpenAIAPI) { - if (body.model.startsWith("o")) { + if (body.model.startsWith("o") || body.model.includes("gpt-5")) { // a) use max_completion_tokens instead of max_tokens body.max_completion_tokens = body.max_tokens; body.max_tokens = undefined; From c69ed88bf0a7e156bfff6de763cacc881147e352 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Aug 2025 13:52:41 -0700 Subject: [PATCH 020/102] chore: vscode 1.1.75 --- 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 faf1aa07a..9d15d1bb6 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.74", + "version": "1.1.75", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 9e94a3806c050aab24d35c6f80ebb130d8c9129d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 7 Aug 2025 15:40:14 -0700 Subject: [PATCH 021/102] feat: add utils for model-specific logic --- core/nextEdit/templating/model1.ts | 88 ++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 core/nextEdit/templating/model1.ts diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts new file mode 100644 index 000000000..84a754efd --- /dev/null +++ b/core/nextEdit/templating/model1.ts @@ -0,0 +1,88 @@ +import { Position, Range } from "../.."; +import { + MODEL_1_CONTEXT_FILE_TOKEN, + MODEL_1_EDITABLE_REGION_END_TOKEN, + MODEL_1_EDITABLE_REGION_START_TOKEN, + MODEL_1_SNIPPET_TOKEN, + MODEL_1_USER_CURSOR_IS_HERE_TOKEN, +} from "../constants"; +import { extractMetadataFromUnifiedDiff } from "../context/diffFormatting"; +import { insertCursorToken } from "./utils"; + +export function recentlyViewedCodeSnippetsBlock( + recentlyViewedCodeSnippets: { filepath: string; content: string }[], +) { + return recentlyViewedCodeSnippets.reduce((acc, snippet, i) => { + const block = [ + `${MODEL_1_CONTEXT_FILE_TOKEN}: ${snippet.filepath}`, + `${MODEL_1_SNIPPET_TOKEN}\n${snippet.content}`, + ].join("\n"); + + return ( + acc + block + (i === recentlyViewedCodeSnippets.length - 1 ? "" : "\n") + ); + }, ""); +} + +export function currentFileContentBlock( + currentFileContent: string, + editableRegionStartLine: number, + editableRegionEndLine: number, + cursorPosition: Position, +) { + const currentFileContentLines = currentFileContent.split("\n"); + + const insertedCursorLines = insertCursorToken( + currentFileContentLines, + cursorPosition, + MODEL_1_USER_CURSOR_IS_HERE_TOKEN, + ); + + const instrumentedLines = [ + ...insertedCursorLines.slice(0, editableRegionStartLine), + MODEL_1_EDITABLE_REGION_START_TOKEN, + ...insertedCursorLines.slice( + editableRegionStartLine, + editableRegionEndLine + 1, + ), + MODEL_1_EDITABLE_REGION_END_TOKEN, + ...insertedCursorLines.slice(editableRegionEndLine + 1), + ]; + + return instrumentedLines.join("\n"); +} + +export function editHistoryBlock( + editDiffHistories: string[], // list of unified diffs +) { + // diffHistory is made from createDiff. + // This uses createPatch from npm diff library, which includes an index line and a separator. + // We get rid of these first two lines. + const block: string[] = []; + + editDiffHistories.forEach((diff) => { + const metadata = extractMetadataFromUnifiedDiff(diff); + block.push( + [ + `User edited file \"${metadata.oldFilename}\"`, + "", + "```diff", + `${diff.split("\n").slice(2).join("\n")}`, + "```", + ].join("\n"), + ); + }); + + return block.join("\n"); +} + +function mercuryNextEditTemplateBuilder( + recentlyViewedCodeSnippets: { filepath: string; code: string }[], + currentFileContent: string, + codeToEdit: string, + codeToEditRange: Range, + cursorPosition: Position, + editDiffHistory: string, // could be a singe large unified diff +): string { + return ""; +} From 326785f0226ff7fc338d9b2d98d957ac288052d5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 7 Aug 2025 15:40:24 -0700 Subject: [PATCH 022/102] feat: add tokens --- core/nextEdit/constants.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 153563d11..1c94db662 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -6,6 +6,8 @@ export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5; export const MODEL_1_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; +export const MODEL_1_CONTEXT_FILE_TOKEN = "<|context_file|>"; +export const MODEL_1_SNIPPET_TOKEN = "<|snippet|>"; // Mercury Coder Next Edit-specific tokens. export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN = From eae28a87c1e8adc073eab88eb9b28d1d5fa167a2 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 7 Aug 2025 15:40:34 -0700 Subject: [PATCH 023/102] feat: add more to context --- core/nextEdit/NextEditProvider.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 0b97c4491..825515225 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -545,9 +545,17 @@ export class NextEditProvider { }; } else if (modelName.includes("model-1")) { ctx = { - userEdits: historyDiff ?? this.diffContext, + recentlyViewedCodeSnippets: + snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ + filepath: snip.filepath, + content: snip.content, + })) ?? [], + currentFileContent: helper.fileContents, + editableRegionStartLine, + editableRegionEndLine, + editDiffHistory: this.diffContext, + currentFilePath: helper.filepath, languageShorthand: helper.lang.name, - userExcerpts: helper.fileContents, }; } else { ctx = {}; From a736bcce0eabc5c2595dea1564260e2eb1805ec8 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 7 Aug 2025 15:40:48 -0700 Subject: [PATCH 024/102] feat: add more fields to template --- core/nextEdit/types.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 49a4c0862..2b9d3162c 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -91,9 +91,11 @@ export interface NextEditTemplate { export interface TemplateVars {} export interface Model1TemplateVars extends TemplateVars { - userEdits: string; + recentlyViewedCodeSnippets: string; + currentFileContent: string; + editDiffHistory: string; // could be a singe large unified diff + currentFilePath: string; languageShorthand: string; - userExcerpts: string; } export interface MercuryTemplateVars extends TemplateVars { From 55f081c2061f37122425a7e79abda53413adc377 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Thu, 7 Aug 2025 15:41:17 -0700 Subject: [PATCH 025/102] feat: edit template --- core/nextEdit/templating/NextEditPromptEngine.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 24f16e681..2c9235eb0 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -44,7 +44,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { }, "model-1": { template: - "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```", + "### User Edits:\n\n{{{editDiffHistory}}}\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{currentFileContent}}}```\n### Response:", }, "this field is not used": { template: "NEXT_EDIT", @@ -142,9 +142,18 @@ export async function renderPrompt( ); const model1Ctx: Model1TemplateVars = { - userEdits: ctx.userEdits, + recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( + ctx.recentlyViewedCodeSnippets, + ), + currentFileContent: currentFileContentBlock( + ctx.currentFileContent, + ctx.editableRegionStartLine, + ctx.editableRegionEndLine, + helper.pos, + ), + editDiffHistory: editHistoryBlock(ctx.editDiffHistory), + currentFilePath: ctx.currentFilePath, languageShorthand: ctx.languageShorthand, - userExcerpts: ctx.userExcerpts, }; tv = model1Ctx; From 867b06012ec1a4cdf5b8eba55482dee1c8f592ad Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Aug 2025 15:56:47 -0700 Subject: [PATCH 026/102] fix: indexing toggle copy Co-authored-by: Josh Holmer --- gui/src/pages/config/IndexingSettingsSection.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/pages/config/IndexingSettingsSection.tsx b/gui/src/pages/config/IndexingSettingsSection.tsx index 4e4c670c0..6df4faed0 100644 --- a/gui/src/pages/config/IndexingSettingsSection.tsx +++ b/gui/src/pages/config/IndexingSettingsSection.tsx @@ -15,7 +15,7 @@ export function IndexingSettingsSection() {

Indexing is disabled

- Open settings and toggle Disable Indexing to re-enable + Open settings and toggle Enable Indexing to re-enable

) : ( From ef48171c8a3df54bed0e9719c9f09149ab381000 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Thu, 7 Aug 2025 22:35:36 -0400 Subject: [PATCH 027/102] fix review --- core/llm/toolSupport.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index d3a8684d0..2876ba346 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -277,6 +277,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "deepseek/deepseek-chat", "meta-llama/llama-4", "all-hands/openhands-lm-32b", + "lgai-exaone/exaone" ]; for (const prefix of supportedPrefixes) { if (model.toLowerCase().startsWith(prefix)) { @@ -347,11 +348,7 @@ export function modelSupportsNativeTools(modelDescription: ModelDescription) { if (modelDescription.capabilities?.tools !== undefined) { return modelDescription.capabilities.tools; } - // EXAONE 4.0 models advertise tool-calling capability regardless of - // the provider used to serve them. - if (modelDescription.model.toLowerCase().includes("exaone")) { - return true; - } + const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; if (!providerSupport) { return false; From 3a08e8a591f65af2ab0847adc866c7ec0f16300b Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Thu, 7 Aug 2025 22:52:01 -0400 Subject: [PATCH 028/102] Update toolSupport.ts --- core/llm/toolSupport.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index e96318697..40648c702 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -279,7 +279,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "deepseek/deepseek-chat", "meta-llama/llama-4", "all-hands/openhands-lm-32b", - "lgai-exaone/exaone" + "lgai-exaone/exaone", ]; for (const prefix of supportedPrefixes) { if (model.toLowerCase().startsWith(prefix)) { From 4dea1af5e907b3092b300514ba846d35677f49ba Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 8 Aug 2025 10:52:59 +0530 Subject: [PATCH 029/102] remove schema parser --- core/llm/llms/Voyage.ts | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index 94c344a56..6a3a3dd1f 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -1,21 +1,6 @@ -import { z } from "zod"; - import { Chunk, LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; -/**used to check a valid response from voyage is received - * reference: https://docs.voyageai.com/reference/reranker-api - */ -const VoyageRerankSuccessResponseSchema = z.object({ - data: z.array( - z.object({ - index: z.number(), - relevance_score: z.number(), - document: z.string(), - }), - ), -}); - class Voyage extends OpenAI { static providerName = "voyage"; static defaultOptions: Partial | undefined = { @@ -51,8 +36,6 @@ class Voyage extends OpenAI { data: Array<{ index: number; relevance_score: number }>; }; - VoyageRerankSuccessResponseSchema.parse(data); - const results = data.data.sort((a, b) => a.index - b.index); return results.map((result) => result.relevance_score); } From 6e66c0e694139dd3df762ca624bb3e1d2f4400be Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 8 Aug 2025 11:42:06 +0530 Subject: [PATCH 030/102] fix: remove add model system message --- core/config/util.ts | 7 ------- 1 file changed, 7 deletions(-) diff --git a/core/config/util.ts b/core/config/util.ts index a53027a76..08bf8949b 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -10,7 +10,6 @@ import { JSONModelDescription, PromptTemplate, } from "../"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; @@ -80,12 +79,6 @@ export function addModel( maxStopWords: model.maxStopWords, defaultCompletionOptions: model.completionOptions, }; - if (model.systemMessage) { - desc.chatOptions = { - baseSystemMessage: - DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage, - }; - } config.models.push(desc); return config; }, From 8fd7bd349c6eb96be248d9185a90ab3460907a2d Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 8 Aug 2025 12:24:46 +0530 Subject: [PATCH 031/102] style: prevent mention query input wrapping text --- .../mainInput/AtMentionDropdown/index.tsx | 80 ++++++++++++------- 1 file changed, 51 insertions(+), 29 deletions(-) diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index f9638b37f..8db383dd3 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -32,6 +32,7 @@ import FileIcon from "../../FileIcon"; import SafeImg from "../../SafeImg"; import AddDocsDialog from "../../dialogs/AddDocsDialog"; import HeaderButtonWithToolTip from "../../gui/HeaderButtonWithToolTip"; +import { Button } from "../../ui"; import { NAMED_ICONS } from "../icons"; import type { ComboBoxItem, ComboBoxItemType } from "../types"; @@ -117,6 +118,7 @@ const QueryInput = styled.textarea` background-color: #fff1; border: 1px solid ${lightGray}; border-radius: ${defaultBorderRadius}; + overflow: hidden; padding: 0.2rem 0.4rem; width: 240px; @@ -243,7 +245,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { .run(); // Trigger warning message - ideMessenger.ide.showToast( + void ideMessenger.ide.showToast( "warning", fileSize > 0 ? "File exceeds model's context length" @@ -368,8 +370,9 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { if (item) { if (item.type === "file" && item.query) { - isItemTooBig(item.type, item.query).then(([fileExceeds, fileSize]) => - handleItemTooBig(fileExceeds, fileSize, item), + void isItemTooBig(item.type, item.query).then( + ([fileExceeds, fileSize]) => + handleItemTooBig(fileExceeds, fileSize, item), ); } else { props.command({ ...item, itemType: item.type }); @@ -456,34 +459,53 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { return ( {querySubmenuItem ? ( - { - e.stopPropagation(); - }} - rows={1} - ref={queryInputRef} - placeholder={querySubmenuItem.description} - onKeyDown={(e) => { - if (!queryInputRef.current) { - return; - } - if (e.key === "Enter") { - if (e.shiftKey) { - queryInputRef.current.innerText += "\n"; - } else { - props.command({ - ...querySubmenuItem, - itemType: querySubmenuItem.type, - query: queryInputRef.current.value, - label: `${querySubmenuItem.label}: ${queryInputRef.current.value}`, - }); + + { + e.stopPropagation(); + }} + rows={1} + ref={queryInputRef} + placeholder={querySubmenuItem.description} + onKeyDown={(e) => { + if (!queryInputRef.current) { + return; } - } else if (e.key === "Escape") { - setQuerySubmenuItem(undefined); - setSubMenuTitle(undefined); + if (e.key === "Enter") { + if (e.shiftKey) { + queryInputRef.current.innerText += "\n"; + } else { + props.command({ + ...querySubmenuItem, + itemType: querySubmenuItem.type, + query: queryInputRef.current.value, + label: `${querySubmenuItem.label}: ${queryInputRef.current.value}`, + }); + } + } else if (e.key === "Escape") { + setQuerySubmenuItem(undefined); + setSubMenuTitle(undefined); + } + }} + /> + + ) : ( <> {subMenuTitle && {subMenuTitle}} From e7d82a6290b0954280e03580220b51aa7ed50ff5 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 28 Jul 2025 17:37:28 -0700 Subject: [PATCH 032/102] fix: :bug: Fix terminal use without a workspace --- .../runTerminalCommand.test.ts | 115 +++++++++++++++++- .../implementations/runTerminalCommand.ts | 54 +++++--- 2 files changed, 152 insertions(+), 17 deletions(-) diff --git a/core/tools/implementations/runTerminalCommand.test.ts b/core/tools/implementations/runTerminalCommand.test.ts index d688e4991..2868a51bc 100644 --- a/core/tools/implementations/runTerminalCommand.test.ts +++ b/core/tools/implementations/runTerminalCommand.test.ts @@ -352,4 +352,117 @@ describe("runTerminalCommandImpl", () => { expect(result[0].content).toBe("Command is running in the background..."); expect(result[0].status).toBe("Command is running in the background..."); }); -}); + + it("should handle missing workspace directory gracefully", async () => { + // Mock IDE to return empty workspace directories + const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); + + // Create IDE mock with empty workspace + const mockIde = { + getIdeInfo: jest.fn().mockReturnValue(Promise.resolve({ remoteName: "local" })), + getWorkspaceDirs: mockEmptyWorkspace, + runCommand: jest.fn(), + getIdeSettings: jest.fn(), + getDiff: jest.fn(), + getClipboardContent: jest.fn(), + isTelemetryEnabled: jest.fn(), + readFile: jest.fn(), + writeFile: jest.fn(), + renameFile: jest.fn(), + deleteFile: jest.fn(), + globFiles: jest.fn(), + ls: jest.fn(), + }; + + const extras = { + ide: mockIde as unknown as IDE, + llm: {} as any, + fetch: {} as any, + tool: {} as any, + toolCallId: "test-tool-call", + } as ToolExtras; + + const command = `node -e "console.log('no workspace test')"`; + const args = { command, waitForCompletion: true }; + + const result = await runTerminalCommandImpl(args, extras); + + // Should still work - falling back to HOME or cwd + expect(result).toHaveLength(1); + expect(result[0].name).toBe("Terminal"); + expect(result[0].description).toBe("Terminal command output"); + expect(result[0].content).toContain("no workspace test"); + expect(result[0].status).toBe("Command completed"); + + // Verify workspace dirs was called but returned empty + expect(mockEmptyWorkspace).toHaveBeenCalled(); + }); + + it("should handle case where cwd fallbacks all fail", async () => { + // Mock IDE to return empty workspace directories + const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); + + // Save original environment variables and process.cwd + const originalHome = process.env.HOME; + const originalUserProfile = process.env.USERPROFILE; + const originalCwd = process.cwd; + + try { + // Mock all fallbacks to fail + delete process.env.HOME; + delete process.env.USERPROFILE; + process.cwd = jest.fn().mockImplementation(() => { + throw new Error("Current directory unavailable"); + }); + + // Create IDE mock with empty workspace + const mockIde = { + getIdeInfo: jest.fn().mockReturnValue(Promise.resolve({ remoteName: "local" })), + getWorkspaceDirs: mockEmptyWorkspace, + runCommand: jest.fn(), + getIdeSettings: jest.fn(), + getDiff: jest.fn(), + getClipboardContent: jest.fn(), + isTelemetryEnabled: jest.fn(), + readFile: jest.fn(), + writeFile: jest.fn(), + renameFile: jest.fn(), + deleteFile: jest.fn(), + globFiles: jest.fn(), + ls: jest.fn(), + }; + + const extras = { + ide: mockIde as unknown as IDE, + llm: {} as any, + fetch: {} as any, + tool: {} as any, + toolCallId: "test-tool-call", + } as ToolExtras; + + const command = `node -e "console.log('fallback test')"`; + const args = { command, waitForCompletion: true }; + + // This should now handle the case gracefully by falling back to temp directory + const result = await runTerminalCommandImpl(args, extras); + + // Should work using the temp directory as fallback + expect(result).toHaveLength(1); + expect(result[0].name).toBe("Terminal"); + expect(result[0].content).toContain("fallback test"); + expect(result[0].status).toBe("Command completed"); + + console.log("Successfully handled cwd fallback to temp directory:", result[0].status); + + } finally { + // Always restore original values + if (originalHome !== undefined) { + process.env.HOME = originalHome; + } + if (originalUserProfile !== undefined) { + process.env.USERPROFILE = originalUserProfile; + } + process.cwd = originalCwd; + } + }); +}); \ No newline at end of file diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index c48ba2ade..7486bf810 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -1,5 +1,6 @@ import iconv from "iconv-lite"; import childProcess from "node:child_process"; +import os from "node:os"; import util from "node:util"; // Automatically decode the buffer according to the platform to avoid garbled Chinese function getDecodedOutput(data: Buffer): string { @@ -75,13 +76,25 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { if (ENABLED_FOR_REMOTES.includes(ideInfo.remoteName)) { // For streaming output if (extras.onPartialOutput) { - return new Promise((resolve, reject) => { - try { - const getWorkspaceDirsPromise = extras.ide.getWorkspaceDirs(); - getWorkspaceDirsPromise - .then((workspaceDirs) => { - const cwd = fileURLToPath(workspaceDirs[0]); - let terminalOutput = ""; + try { + const workspaceDirs = await extras.ide.getWorkspaceDirs(); + + // Handle case where no workspace is available + let cwd: string; + if (workspaceDirs.length > 0) { + cwd = fileURLToPath(workspaceDirs[0]); + } else { + // Default to user's home directory with fallbacks + try { + cwd = process.env.HOME || process.env.USERPROFILE || process.cwd(); + } catch (error) { + // Final fallback if even process.cwd() fails - use system temp directory + cwd = os.tmpdir(); + } + } + + return new Promise((resolve, reject) => { + let terminalOutput = ""; if (!waitForCompletion) { const status = "Command is running in the background..."; @@ -229,18 +242,27 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { reject(error); }); - }) - .catch((error) => { - reject(error); }); - } catch (error: any) { - reject(error); - } - }); + } catch (error: any) { + throw error; + } } else { // Fallback to non-streaming for older clients const workspaceDirs = await extras.ide.getWorkspaceDirs(); - const cwd = fileURLToPath(workspaceDirs[0]); + + // Handle case where no workspace is available + let cwd: string; + if (workspaceDirs.length > 0) { + cwd = fileURLToPath(workspaceDirs[0]); + } else { + // Default to user's home directory with fallbacks + try { + cwd = process.env.HOME || process.env.USERPROFILE || process.cwd(); + } catch (error) { + // Final fallback if even process.cwd() fails - use system temp directory + cwd = os.tmpdir(); + } + } if (waitForCompletion) { // Standard execution, waiting for completion @@ -375,4 +397,4 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { status: "Command failed", }, ]; -}; +}; \ No newline at end of file From c78db090371fa8b5d1d28e70292785d741785a76 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 28 Jul 2025 17:41:04 -0700 Subject: [PATCH 033/102] fix: :art: Prettier fixes --- .../runTerminalCommand.test.ts | 30 ++- .../implementations/runTerminalCommand.ts | 223 +++++++++--------- 2 files changed, 134 insertions(+), 119 deletions(-) diff --git a/core/tools/implementations/runTerminalCommand.test.ts b/core/tools/implementations/runTerminalCommand.test.ts index 2868a51bc..9ef39632b 100644 --- a/core/tools/implementations/runTerminalCommand.test.ts +++ b/core/tools/implementations/runTerminalCommand.test.ts @@ -356,10 +356,12 @@ describe("runTerminalCommandImpl", () => { it("should handle missing workspace directory gracefully", async () => { // Mock IDE to return empty workspace directories const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); - + // Create IDE mock with empty workspace const mockIde = { - getIdeInfo: jest.fn().mockReturnValue(Promise.resolve({ remoteName: "local" })), + getIdeInfo: jest + .fn() + .mockReturnValue(Promise.resolve({ remoteName: "local" })), getWorkspaceDirs: mockEmptyWorkspace, runCommand: jest.fn(), getIdeSettings: jest.fn(), @@ -393,7 +395,7 @@ describe("runTerminalCommandImpl", () => { expect(result[0].description).toBe("Terminal command output"); expect(result[0].content).toContain("no workspace test"); expect(result[0].status).toBe("Command completed"); - + // Verify workspace dirs was called but returned empty expect(mockEmptyWorkspace).toHaveBeenCalled(); }); @@ -401,12 +403,12 @@ describe("runTerminalCommandImpl", () => { it("should handle case where cwd fallbacks all fail", async () => { // Mock IDE to return empty workspace directories const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); - + // Save original environment variables and process.cwd const originalHome = process.env.HOME; const originalUserProfile = process.env.USERPROFILE; const originalCwd = process.cwd; - + try { // Mock all fallbacks to fail delete process.env.HOME; @@ -414,10 +416,12 @@ describe("runTerminalCommandImpl", () => { process.cwd = jest.fn().mockImplementation(() => { throw new Error("Current directory unavailable"); }); - + // Create IDE mock with empty workspace const mockIde = { - getIdeInfo: jest.fn().mockReturnValue(Promise.resolve({ remoteName: "local" })), + getIdeInfo: jest + .fn() + .mockReturnValue(Promise.resolve({ remoteName: "local" })), getWorkspaceDirs: mockEmptyWorkspace, runCommand: jest.fn(), getIdeSettings: jest.fn(), @@ -445,15 +449,17 @@ describe("runTerminalCommandImpl", () => { // This should now handle the case gracefully by falling back to temp directory const result = await runTerminalCommandImpl(args, extras); - + // Should work using the temp directory as fallback expect(result).toHaveLength(1); expect(result[0].name).toBe("Terminal"); expect(result[0].content).toContain("fallback test"); expect(result[0].status).toBe("Command completed"); - - console.log("Successfully handled cwd fallback to temp directory:", result[0].status); - + + console.log( + "Successfully handled cwd fallback to temp directory:", + result[0].status, + ); } finally { // Always restore original values if (originalHome !== undefined) { @@ -465,4 +471,4 @@ describe("runTerminalCommandImpl", () => { process.cwd = originalCwd; } }); -}); \ No newline at end of file +}); diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index 7486bf810..919bebdd7 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -78,7 +78,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { if (extras.onPartialOutput) { try { const workspaceDirs = await extras.ide.getWorkspaceDirs(); - + // Handle case where no workspace is available let cwd: string; if (workspaceDirs.length > 0) { @@ -119,58 +119,98 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { cwd, env: getColorEnv(), // Add enhanced environment for colors }); + } + } - childProc.stdout?.on("data", (data) => { - // Skip if this process has been backgrounded - if (isProcessBackgrounded(toolCallId)) return; + // Use spawn with color environment + const childProc = childProcess.spawn(command, { + cwd, + shell: true, + env: getColorEnv(), // Add enhanced environment for colors + }); - const newOutput = getDecodedOutput(data); - terminalOutput += newOutput; + childProc.stdout?.on("data", (data) => { + // Skip if this process has been backgrounded + if (isProcessBackgrounded(toolCallId)) return; - // Send partial output to UI - if (extras.onPartialOutput) { - const status = waitForCompletion - ? "" - : "Command is running in the background..."; - extras.onPartialOutput({ - toolCallId, - contextItems: [ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - status: status, - }, - ], - }); - } + const newOutput = getDecodedOutput(data); + terminalOutput += newOutput; + + // Send partial output to UI + if (extras.onPartialOutput) { + const status = waitForCompletion + ? "" + : "Command is running in the background..."; + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ], }); + } + }); - childProc.stderr?.on("data", (data) => { - // Skip if this process has been backgrounded - if (isProcessBackgrounded(toolCallId)) return; + childProc.stderr?.on("data", (data) => { + // Skip if this process has been backgrounded + if (isProcessBackgrounded(toolCallId)) return; - const newOutput = getDecodedOutput(data); - terminalOutput += newOutput; + const newOutput = getDecodedOutput(data); + terminalOutput += newOutput; - // Send partial output to UI, status is not required - if (extras.onPartialOutput) { - extras.onPartialOutput({ - toolCallId, - contextItems: [ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - }, - ], - }); - } + // Send partial output to UI, status is not required + if (extras.onPartialOutput) { + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + }, + ], }); + } + }); - // If we don't need to wait for completion, resolve immediately - if (!waitForCompletion) { - const status = "Command is running in the background..."; + // If we don't need to wait for completion, resolve immediately + if (!waitForCompletion) { + const status = "Command is running in the background..."; + resolve([ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ]); + } + + childProc.on("close", (code) => { + // If this process has been backgrounded, clean it up from the map and return + if (isProcessBackgrounded(toolCallId)) { + removeBackgroundedProcess(toolCallId); + return; + } + + if (waitForCompletion) { + // Normal completion, resolve now + if (code === 0) { + const status = "Command completed"; + resolve([ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ]); + } else { + const status = `Command failed with exit code ${code}`; resolve([ { name: "Terminal", @@ -180,76 +220,45 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { }, ]); } + } else { + // Already resolved, just update the UI with final output + if (extras.onPartialOutput) { + const status = + code === 0 || !code + ? "\nBackground command completed" + : `\nBackground command failed with exit code ${code}`; + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ], + }); + } + } + }); - childProc.on("close", (code) => { - // If this process has been backgrounded, clean it up from the map and return - if (isProcessBackgrounded(toolCallId)) { - removeBackgroundedProcess(toolCallId); - return; - } + childProc.on("error", (error) => { + // If this process has been backgrounded, clean it up from the map and return + if (isProcessBackgrounded(toolCallId)) { + removeBackgroundedProcess(toolCallId); + return; + } - if (waitForCompletion) { - // Normal completion, resolve now - if (code === 0) { - const status = "Command completed"; - resolve([ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - status: status, - }, - ]); - } else { - const status = `Command failed with exit code ${code}`; - resolve([ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - status: status, - }, - ]); - } - } else { - // Already resolved, just update the UI with final output - if (extras.onPartialOutput) { - const status = - code === 0 || !code - ? "\nBackground command completed" - : `\nBackground command failed with exit code ${code}`; - extras.onPartialOutput({ - toolCallId, - contextItems: [ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - status: status, - }, - ], - }); - } - } - }); - - childProc.on("error", (error) => { - // If this process has been backgrounded, clean it up from the map and return - if (isProcessBackgrounded(toolCallId)) { - removeBackgroundedProcess(toolCallId); - return; - } - - reject(error); - }); - }); + reject(error); + }); + }); } catch (error: any) { throw error; } } else { // Fallback to non-streaming for older clients const workspaceDirs = await extras.ide.getWorkspaceDirs(); - + // Handle case where no workspace is available let cwd: string; if (workspaceDirs.length > 0) { @@ -397,4 +406,4 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { status: "Command failed", }, ]; -}; \ No newline at end of file +}; From 33b23ae09ee19034ac136e558cb5f3d258ef3dcf Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Mon, 28 Jul 2025 17:47:53 -0700 Subject: [PATCH 034/102] fix: :art: Fix typescript error --- core/tools/implementations/runTerminalCommand.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/tools/implementations/runTerminalCommand.test.ts b/core/tools/implementations/runTerminalCommand.test.ts index 9ef39632b..e744ea4f1 100644 --- a/core/tools/implementations/runTerminalCommand.test.ts +++ b/core/tools/implementations/runTerminalCommand.test.ts @@ -415,7 +415,7 @@ describe("runTerminalCommandImpl", () => { delete process.env.USERPROFILE; process.cwd = jest.fn().mockImplementation(() => { throw new Error("Current directory unavailable"); - }); + }) as jest.MockedFunction<() => string>; // Create IDE mock with empty workspace const mockIde = { From 6e0775b0ce414942433c42136a0e4830206c0ee4 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Fri, 8 Aug 2025 00:07:55 -0700 Subject: [PATCH 035/102] fix: :bug: Fix rebase issues --- .../implementations/runTerminalCommand.ts | 39 +++++++------------ 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index 919bebdd7..b106396af 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -96,36 +96,27 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { return new Promise((resolve, reject) => { let terminalOutput = ""; - if (!waitForCompletion) { - const status = "Command is running in the background..."; - if (extras.onPartialOutput) { - extras.onPartialOutput({ - toolCallId, - contextItems: [ - { - name: "Terminal", - description: "Terminal command output", - content: "", - status: status, - }, - ], - }); - } - } - - // Use spawn with color environment - const { shell, args } = getShellCommand(command); - const childProc = childProcess.spawn(shell, args, { - cwd, - env: getColorEnv(), // Add enhanced environment for colors + if (!waitForCompletion) { + const status = "Command is running in the background..."; + if (extras.onPartialOutput) { + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: "", + status: status, + }, + ], }); } } // Use spawn with color environment - const childProc = childProcess.spawn(command, { + const { shell, args } = getShellCommand(command); + const childProc = childProcess.spawn(shell, args, { cwd, - shell: true, env: getColorEnv(), // Add enhanced environment for colors }); From 5b9feccc69efa8631258c499b461f9ed7a25df09 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Fri, 8 Aug 2025 12:42:08 +0530 Subject: [PATCH 036/102] fix: abort controller before clearing --- core/indexing/CodebaseIndexer.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 6e1dab530..b28ece8da 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -735,6 +735,7 @@ export class CodebaseIndexer { }); } if (this.indexingCancellationController === localController) { + this.indexingCancellationController.abort(); // abort before clearing to prevent race condition (multiple starts) this.indexingCancellationController = undefined; } } From 4e5ee6fbb6490c06294e1b6bc2a46e13d52c9c50 Mon Sep 17 00:00:00 2001 From: vldf Date: Fri, 8 Aug 2025 11:40:49 +0300 Subject: [PATCH 037/102] fix: increase `debouncer`'s `interval` value to fix #6199 --- .../listeners/ContinuePluginSelectionListener.kt | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt index adcc86f7f..71e73369f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ContinuePluginSelectionListener.kt @@ -1,29 +1,27 @@ package com.github.continuedev.continueintellijextension.listeners import ToolTipComponent -import com.github.continuedev.continueintellijextension.editor.EditorUtils import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.utils.Debouncer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.editor.event.SelectionEvent import com.intellij.openapi.editor.event.SelectionListener -import com.intellij.openapi.project.DumbAware -import com.intellij.openapi.util.TextRange -import kotlinx.coroutines.CoroutineScope -import com.intellij.openapi.editor.Document -import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor +import com.intellij.openapi.project.DumbAware +import com.intellij.openapi.util.TextRange +import kotlinx.coroutines.CoroutineScope class ContinuePluginSelectionListener( coroutineScope: CoroutineScope, ) : SelectionListener, DumbAware { - private val debouncer = Debouncer(100, coroutineScope) + private val debouncer = Debouncer(200, coroutineScope) private var toolTipComponents: ArrayList = ArrayList() private var lastActiveEditor: Editor? = null @@ -228,5 +226,3 @@ class ContinuePluginSelectionListener( editor.contentComponent.repaint() } } - - From d328ab24dcd05a7b613d790777ddb9af53e9ba6e Mon Sep 17 00:00:00 2001 From: Brian Douglas Date: Fri, 8 Aug 2025 07:48:42 -0700 Subject: [PATCH 038/102] chore: Add action to comment on duplicate issues --- .github/workflows/similar-issues.yml | 289 +++++++++++++++++++++++++++ 1 file changed, 289 insertions(+) create mode 100644 .github/workflows/similar-issues.yml diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml new file mode 100644 index 000000000..74031688b --- /dev/null +++ b/.github/workflows/similar-issues.yml @@ -0,0 +1,289 @@ +name: Similar Issue Search & Discussion Suggestion +on: + issues: + types: [opened] + pull_request: + types: [opened] + +jobs: + analyze: + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + + steps: + - name: Checkout deja-view + uses: actions/checkout@v4 + with: + repository: 'bdougie/deja-view' + path: deja-view + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + + - name: Install dependencies + run: | + cd deja-view + pip install -r requirements.txt + + - name: Search for similar issues + id: search + env: + CHROMA_CLOUD_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }} + CHROMA_CLOUD_API_URL: ${{ secrets.CHROMA_CLOUD_API_URL }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + cd deja-view + + # Determine if this is an issue or PR + if [ "${{ github.event_name }}" = "pull_request" ]; then + TITLE="${{ github.event.pull_request.title }}" + THRESHOLD="0.85" + TOP_K="5" + else + TITLE="${{ github.event.issue.title }}" + THRESHOLD="0.7" + TOP_K="3" + fi + + # Search for similar issues + SIMILAR_ISSUES=$(python cli.py search "$TITLE" \ + --repo "${{ github.repository }}" \ + --top-k $TOP_K \ + --threshold $THRESHOLD \ + --format json) + + # Save to output + echo "similar_issues<> $GITHUB_OUTPUT + echo "$SIMILAR_ISSUES" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + # Check if any similar issues found + if [ "$(echo "$SIMILAR_ISSUES" | jq '. | length')" -gt 0 ]; then + echo "has_similar=true" >> $GITHUB_OUTPUT + else + echo "has_similar=false" >> $GITHUB_OUTPUT + fi + + - name: Check if issue should be a discussion + id: discussion_check + if: github.event_name == 'issues' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + cd deja-view + + # Create a Python script to analyze the issue + cat << 'PYTHON_SCRIPT' > check_discussion.py + import os + import json + import re + from github_similarity_service import SimilarityService + + # Get issue details from environment + issue_title = os.environ.get('ISSUE_TITLE', '') + issue_body = os.environ.get('ISSUE_BODY', '') + issue_labels = json.loads(os.environ.get('ISSUE_LABELS', '[]')) + + # Mock Issue object for analysis + class MockIssue: + def __init__(self): + self.title = issue_title + self.body = issue_body + self.labels = issue_labels + self.state = 'open' + self.number = int(os.environ.get('ISSUE_NUMBER', 0)) + self.created_at = '' + self.updated_at = '' + self.url = '' + + service = SimilarityService() + issue = MockIssue() + + score, reasons = service._calculate_discussion_score(issue) + + result = { + 'score': score, + 'reasons': reasons, + 'should_be_discussion': score >= 0.5, + 'confidence': 'high' if score >= 0.7 else 'medium' if score >= 0.5 else 'low' + } + + print(json.dumps(result)) + PYTHON_SCRIPT + + # Run the analysis + DISCUSSION_ANALYSIS=$(ISSUE_TITLE="${{ github.event.issue.title }}" \ + ISSUE_BODY='${{ github.event.issue.body }}' \ + ISSUE_LABELS='${{ toJson(github.event.issue.labels.*.name) }}' \ + ISSUE_NUMBER="${{ github.event.issue.number }}" \ + python check_discussion.py) + + echo "analysis<> $GITHUB_OUTPUT + echo "$DISCUSSION_ANALYSIS" >> $GITHUB_OUTPUT + echo "EOF" >> $GITHUB_OUTPUT + + # Extract whether it should be a discussion + SHOULD_BE_DISCUSSION=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.should_be_discussion') + echo "should_be_discussion=$SHOULD_BE_DISCUSSION" >> $GITHUB_OUTPUT + + # Extract confidence level + CONFIDENCE=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.confidence') + echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT + + - name: Comment with analysis + uses: actions/github-script@v7 + with: + script: | + let comment = ''; + const hasSimilar = '${{ steps.search.outputs.has_similar }}' === 'true'; + const isPR = '${{ github.event_name }}' === 'pull_request'; + const shouldBeDiscussion = !isPR && '${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true'; + + // Add similar issues section if found + if (hasSimilar) { + const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`); + + if (isPR) { + // Filter only open issues for PRs + const openIssues = similarIssues.filter(issue => issue.state === 'open'); + + if (openIssues.length > 0) { + // Simple table format for PRs + comment += '## 📋 Related Open Issues\n\n'; + comment += 'These open issues appear to be related to this PR (≥85% similarity):\n\n'; + comment += '| # | Title | Similarity |\n'; + comment += '|---|-------|------------|\n'; + + openIssues.forEach(issue => { + const similarity = (issue.similarity * 100).toFixed(0); + const title = issue.title.length > 50 ? issue.title.substring(0, 47) + '...' : issue.title; + comment += `| [#${issue.number}](${issue.url}) | ${title} | ${similarity}% |\n`; + }); + + comment += '\n'; + comment += '_Consider closing related issues if this PR addresses them._\n'; + } else { + // Don't add any comment if no open issues found + return; + } + } else { + // Original format for issues + comment += '## 🔍 Similar Issues Found\n\n'; + comment += 'I found some existing issues that might be related:\n\n'; + + similarIssues.forEach((issue, index) => { + const similarity = (issue.similarity * 100).toFixed(1); + const state = issue.state === 'open' ? '🟢' : '🔴'; + + comment += `${index + 1}. ${state} [#${issue.number}: ${issue.title}](${issue.url}) (${similarity}% similar)\n`; + + if (issue.summary) { + comment += ` > ${issue.summary.substring(0, 150)}${issue.summary.length > 150 ? '...' : ''}\n`; + } + comment += '\n'; + }); + + comment += '\n'; + } + } + + // Add discussion suggestion if applicable + if (shouldBeDiscussion) { + const analysis = JSON.parse(`${{ steps.discussion_check.outputs.analysis }}`); + const confidence = '${{ steps.discussion_check.outputs.confidence }}'; + + if (hasSimilar) { + comment += '---\n\n'; + } + + comment += '## 💬 Discussion Suggestion\n\n'; + + const confidenceEmoji = { + 'high': '🟢', + 'medium': '🟡', + 'low': '🔴' + }; + + comment += `This issue might be better suited as a **GitHub Discussion** ${confidenceEmoji[confidence] || ''}\n\n`; + comment += `**Confidence**: ${confidence.charAt(0).toUpperCase() + confidence.slice(1)} (${(analysis.score * 100).toFixed(0)}%)\n\n`; + + if (analysis.reasons && analysis.reasons.length > 0) { + comment += '**Reasons**:\n'; + analysis.reasons.forEach(reason => { + comment += `- ${reason}\n`; + }); + comment += '\n'; + } + + comment += 'GitHub Discussions are great for:\n'; + comment += '- Questions and help requests\n'; + comment += '- Feature requests and ideas\n'; + comment += '- General feedback and brainstorming\n'; + comment += '- Community conversations\n\n'; + + comment += '_Consider converting this to a discussion if it\'s not a bug report or actionable task._\n'; + } + + // Only comment if we have something to say + if (comment) { + comment += '\n---\n'; + comment += '_This analysis was automatically generated by [deja-view](https://github.com/bdougie/deja-view)._'; + + if ('${{ github.event_name }}' === 'pull_request') { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + body: comment + }); + } else { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + body: comment + }); + } + } + + - name: Add labels + if: github.event_name == 'issues' + uses: actions/github-script@v7 + with: + script: | + const labels = []; + + // Check for duplicate + if ('${{ steps.search.outputs.has_similar }}' === 'true') { + const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`); + const hasDuplicate = similarIssues.some(issue => issue.similarity > 0.9); + + if (hasDuplicate) { + labels.push('potential-duplicate'); + } + } + + // Check for discussion suggestion + if ('${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true') { + const confidence = '${{ steps.discussion_check.outputs.confidence }}'; + + if (confidence === 'high') { + labels.push('should-be-discussion'); + } else if (confidence === 'medium') { + labels.push('discussion'); + } + } + + // Add labels if any + if (labels.length > 0) { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + labels: labels + }); + } From 8fe5077e60a0d315d4e77878ca7ef2856f606566 Mon Sep 17 00:00:00 2001 From: Keerthana Panyam Date: Wed, 6 Aug 2025 11:02:03 -0400 Subject: [PATCH 040/102] move context restriction properties to model level autocompleteOptions - added context restriction properties to model autocompleteOptions schema - discarded changes to add global tabAutocompleteOptions to config schema - added experimental parameters to both config-types. - added YAML alternative note to json reference. - updated YAML configuration example with per-model options. - added reference documentation with parameters for autocomplete options. --- core/autocomplete/CompletionProvider.ts | 2 +- core/config/yaml/loadYaml.ts | 1 - core/util/parameters.ts | 1 + docs/customize/deep-dives/autocomplete.mdx | 31 ++++++++++++++-- docs/reference.mdx | 30 ++++++++++++++- docs/reference/json-reference.mdx | 12 ++++++ .../mainInput/Lump/EditBlockButton.tsx | 2 +- packages/config-types/src/index.ts | 37 ++++++++++--------- packages/config-yaml/src/load/unroll.ts | 10 +---- packages/config-yaml/src/schemas/index.ts | 5 --- packages/config-yaml/src/schemas/models.ts | 10 +++++ 11 files changed, 102 insertions(+), 39 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 143dbf269..d51c15853 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -10,8 +10,8 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { getAllSnippetsWithoutRace } from "./snippets/index.js"; import { renderPromptWithTokenLimit } from "./templating/index.js"; +import { getAllSnippetsWithoutRace } from "./snippets/index.js"; import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 94aba67be..dbfd88a08 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -429,7 +429,6 @@ async function configYamlToContinueConfig(options: { })), false, ); - continueConfig.tabAutocompleteOptions = config.tabAutocompleteOptions; return { config: continueConfig, errors: localErrors }; } diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 147c3979a..fbcdbca66 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -20,6 +20,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { useImports: true, transform: true, showWhateverWeHaveAtXMs: 300, + // Experimental options: true = enabled, false = disabled, number = enabled w priority experimental_includeClipboard: true, experimental_includeRecentlyVisitedRanges: true, experimental_includeRecentlyEditedRanges: true, diff --git a/docs/customize/deep-dives/autocomplete.mdx b/docs/customize/deep-dives/autocomplete.mdx index d1ea3635e..818261ac5 100644 --- a/docs/customize/deep-dives/autocomplete.mdx +++ b/docs/customize/deep-dives/autocomplete.mdx @@ -84,7 +84,7 @@ Then, add the model to your configuration: Once the model has been downloaded, you should begin to see completions in VS Code. -NOTE: Typically, thinking-type models are not recommended as they generate more slowly and are not suitable for scenarios that require speed. +NOTE: Typically, thinking-type models are not recommended as they generate more slowly and are not suitable for scenarios that require speed. However, if you use any thinking-switchable models, you can configure these models for autocomplete functions by turning off the thinking mode. @@ -92,7 +92,7 @@ For example: - ```yaml title="config.yaml" +```yaml title="config.yaml" models: - name: Qwen3 without Thinking for Autocomplete provider: ollama @@ -122,9 +122,32 @@ The following settings can be configured for autocompletion in the IDE extension - `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` - `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt" -### `config.json` Configuration +### Autocomplete Configuration -The `config.json` configuration format (deprecated) offers further configuration options through `tabAutocompleteOptions`. See the [JSON Reference](/reference) for more details. +#### YAML Configuration + +The `config.yaml` format offers model-level configuration using the `autocompleteOptions` field. See the [YAML Reference](/reference#models) for more details. + +```yaml +models: + - name: Codestral + provider: mistral + model: codestral-latest + roles: + - autocomplete + autocompleteOptions: + disable: false + maxPromptTokens: 1024 + debounceDelay: 250 + modelTimeout: 150 + maxSuffixPercentage: 0.2 + prefixPercentage: 0.3 + onlyMyCode: true +``` + +#### JSON Configuration (Deprecated) + +The `config.json` configuration format offers configuration options through `tabAutocompleteOptions`. See the [JSON Reference](/reference/json-reference#tabautocomplete-options) for more details. ## FAQs diff --git a/docs/reference.mdx b/docs/reference.mdx index bf9683e10..ee41e8f18 100644 --- a/docs/reference.mdx +++ b/docs/reference.mdx @@ -176,9 +176,10 @@ The `models` section defines the language models used in your configuration. Mod - `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include: + - `tool_use`: Enables function/tool calling support (required for Agent mode) - `image_input`: Enables image upload and processing support - + Continue automatically detects these capabilities for most models, but you can override this when using custom deployments or if autodetection isn't working correctly. See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for detailed information. - `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. @@ -228,6 +229,21 @@ The `models` section defines the language models used in your configuration. Mod - `key`: Path to the client certificate key file. - `passphrase`: Optional passphrase for the client certificate key file. +- `autocompleteOptions`: If the model includes role `autocomplete`, these settings apply for tab autocompletion: + + - `disable`: If `true`, disables autocomplete for this model. + - `maxPromptTokens`: Maximum number of tokens for the autocomplete prompt. + - `debounceDelay`: Delay before triggering autocomplete in milliseconds. + - `modelTimeout`: Model timeout for autocomplete requests in milliseconds. + - `maxSuffixPercentage`: Maximum percentage of prompt allocated for suffix. + - `prefixPercentage`: Percentage of input allocated for prefix. + - `template`: Custom template for autocomplete using Mustache syntax. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables. + - `onlyMyCode`: Only includes code within the repository for context. + - `useCache`: If `true`, enables caching for completions. + - `useImports`: If `true`, includes imports in context. + - `useRecentlyEdited`: If `true`, includes recently edited files in context. + - `useRecentlyOpened`: If `true`, includes recently opened files in context. + **Example:** ```yaml title="config.yaml" @@ -247,6 +263,10 @@ models: model: codestral-latest roles: - autocomplete + autocompleteOptions: + debounceDelay: 250 + maxPromptTokens: 1024 + onlyMyCode: true - name: My Model - OpenAI-Compatible provider: openai apiBase: http://my-endpoint/v1 @@ -456,6 +476,10 @@ models: model: starcoder roles: - autocomplete + autocompleteOptions: + debounceDelay: 350 + maxPromptTokens: 1024 + onlyMyCode: true defaultCompletionOptions: temperature: 0.3 stop: @@ -531,4 +555,8 @@ models: useLegacyCompletionsEndpoint: false roles: - autocomplete + autocompleteOptions: + debounceDelay: 350 + maxPromptTokens: 1024 + onlyMyCode: true ``` diff --git a/docs/reference/json-reference.mdx b/docs/reference/json-reference.mdx index 7d6f40568..d775b27e5 100644 --- a/docs/reference/json-reference.mdx +++ b/docs/reference/json-reference.mdx @@ -101,6 +101,12 @@ config.json Specifies options for tab autocompletion behavior. + + **Note**: Many of these parameters can also be configured per-model using the + `autocompleteOptions` field in `config.yaml`. See the [YAML + Reference](/reference#models) for more details. + + **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). @@ -468,16 +474,19 @@ Several experimental config parameters are available, as described below: - `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.= - `modelRoles`: + - `inlineEdit`: Model title for inline edits. - `applyCodeBlock`: Model title for applying code blocks. - `repoMapFileSelection`: Model title for repo map selections. - `quickActions`: Array of custom quick actions + - `title` (**required**): Display title for the quick action. - `prompt` (**required**): Prompt for quick action. - `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`. - `contextMenuPrompts`: + - `comment`: Prompt for commenting code. - `docstring`: Prompt for adding docstrings. - `fix`: Prompt for fixing code. @@ -529,15 +538,18 @@ Some deprecated `config.json` settings are no longer stored in config and have b - `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false - `tabAutocompleteOptions` + - `useCache`: This value will override during migration. - `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated) - `multilineCompletions`: This value will override during migration. - `experimental` + - `useChromiumForDocsCrawling`: This value will override during migration. - `readResponseTTS`: This value will override during migration. - `ui` - all will override during migration + - `codeBlockToolbarPosition` - `fontSize` - `codeWrap` diff --git a/gui/src/components/mainInput/Lump/EditBlockButton.tsx b/gui/src/components/mainInput/Lump/EditBlockButton.tsx index 0bce9f642..19780e875 100644 --- a/gui/src/components/mainInput/Lump/EditBlockButton.tsx +++ b/gui/src/components/mainInput/Lump/EditBlockButton.tsx @@ -6,7 +6,7 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger"; type SectionKey = Exclude< keyof ConfigYaml, - "name" | "version" | "schema" | "metadata" | "tabAutocompleteOptions" + "name" | "version" | "schema" | "metadata" >; interface EditBlockButtonProps { diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 942f75219..a22bb00bb 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -136,27 +136,30 @@ export const uiOptionsSchema = z.object({ export type UiOptions = z.infer; export const tabAutocompleteOptionsSchema = z.object({ - disable: z.boolean().optional(), - maxPromptTokens: z.number().optional(), - debounceDelay: z.number().optional(), - maxSuffixPercentage: z.number().optional(), - prefixPercentage: z.number().optional(), + disable: z.boolean(), + maxPromptTokens: z.number(), + debounceDelay: z.number(), + maxSuffixPercentage: z.number(), + prefixPercentage: z.number(), transform: z.boolean().optional(), template: z.string().optional(), - multilineCompletions: z.enum(["always", "never", "auto"]).optional(), - slidingWindowPrefixPercentage: z.number().optional(), - slidingWindowSize: z.number().optional(), - useCache: z.boolean().optional(), - onlyMyCode: z.boolean().optional(), - useRecentlyEdited: z.boolean().optional(), - useRecentlyOpened: z.boolean().optional(), + multilineCompletions: z.enum(["always", "never", "auto"]), + slidingWindowPrefixPercentage: z.number(), + slidingWindowSize: z.number(), + useCache: z.boolean(), + onlyMyCode: z.boolean(), + useRecentlyEdited: z.boolean(), disableInFiles: z.array(z.string()).optional(), useImports: z.boolean().optional(), - // Experimental options - experimental_includeClipboard: z.boolean().optional(), - experimental_includeRecentlyVisitedRanges: z.boolean().optional(), - experimental_includeRecentlyEditedRanges: z.boolean().optional(), - experimental_includeDiff: z.boolean().optional(), + // Experimental options: true = enabled, false = disabled, number = enabled w priority + experimental_includeClipboard: z.union([z.boolean(), z.number()]).optional(), + experimental_includeRecentlyVisitedRanges: z + .union([z.boolean(), z.number()]) + .optional(), + experimental_includeRecentlyEditedRanges: z + .union([z.boolean(), z.number()]) + .optional(), + experimental_includeDiff: z.union([z.boolean(), z.number()]).optional(), experimental_enableStaticContextualization: z.boolean().optional(), }); export type TabAutocompleteOptions = z.infer< diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 6ab35bc21..adbe45324 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -309,19 +309,11 @@ export async function unrollBlocks( const unrolledAssistant: AssistantUnrolled = { name: assistant.name, version: assistant.version, - ...(assistant.tabAutocompleteOptions && { - tabAutocompleteOptions: assistant.tabAutocompleteOptions, - }), }; const sections: (keyof Omit< ConfigYaml, - | "name" - | "version" - | "rules" - | "schema" - | "metadata" - | "tabAutocompleteOptions" + "name" | "version" | "rules" | "schema" | "metadata" >)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"]; // Process all sections in parallel diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index dc1ff9c9d..e15a5655d 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -1,4 +1,3 @@ -import { tabAutocompleteOptionsSchema } from "@continuedev/config-types"; import * as z from "zod"; import { commonModelSlugs } from "./commonSlugs.js"; import { dataSchema } from "./data/index.js"; @@ -146,7 +145,6 @@ export const configYamlSchema = baseConfigYamlSchema.extend({ .optional(), prompts: z.array(blockOrSchema(promptSchema)).optional(), docs: z.array(blockOrSchema(docSchema)).optional(), - tabAutocompleteOptions: tabAutocompleteOptionsSchema.optional(), }); export type ConfigYaml = z.infer; @@ -159,7 +157,6 @@ export const assistantUnrolledSchema = baseConfigYamlSchema.extend({ rules: z.array(ruleSchema.nullable()).optional(), prompts: z.array(promptSchema.nullable()).optional(), docs: z.array(docSchema.nullable()).optional(), - tabAutocompleteOptions: tabAutocompleteOptionsSchema.optional(), }); export type AssistantUnrolled = z.infer; @@ -172,7 +169,6 @@ export const assistantUnrolledSchemaNonNullable = baseConfigYamlSchema.extend({ rules: z.array(ruleSchema).optional(), prompts: z.array(promptSchema).optional(), docs: z.array(docSchema).optional(), - tabAutocompleteOptions: tabAutocompleteOptionsSchema.optional(), }); export type AssistantUnrolledNonNullable = z.infer< @@ -258,7 +254,6 @@ export const configSchema = z.object({ proxy: z.string().optional(), api_base: z.string().optional(), api_key: z.string().optional(), - tabAutocompleteOptions: tabAutocompleteOptionsSchema.optional(), }); export type Config = z.infer; diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 283ec6781..b6e511e2a 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -119,6 +119,16 @@ export const autocompleteOptionsSchema = z.object({ prefixPercentage: z.number().optional(), template: z.string().optional(), onlyMyCode: z.boolean().optional(), + useCache: z.boolean().optional(), + useImports: z.boolean().optional(), + useRecentlyEdited: z.boolean().optional(), + useRecentlyOpened: z.boolean().optional(), + // Experimental options: true = enabled, false = disabled, number = enabled w priority + experimental_includeClipboard: z.boolean().optional(), + experimental_includeRecentlyVisitedRanges: z.boolean().optional(), + experimental_includeRecentlyEditedRanges: z.boolean().optional(), + experimental_includeDiff: z.boolean().optional(), + experimental_enableStaticContextualization: z.boolean().optional(), }); /** Prompt templates use Handlebars syntax */ From 406f3c8e6e25f374aa0101dcca4fcc5733095d39 Mon Sep 17 00:00:00 2001 From: Brian Douglas Date: Fri, 8 Aug 2025 09:19:43 -0700 Subject: [PATCH 041/102] fix: Update similar-issues.yml --- .github/workflows/similar-issues.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml index 74031688b..48f536e84 100644 --- a/.github/workflows/similar-issues.yml +++ b/.github/workflows/similar-issues.yml @@ -17,7 +17,8 @@ jobs: uses: actions/checkout@v4 with: repository: 'bdougie/deja-view' - path: deja-view + # Option 1: Pin to specific commit (most secure) + ref: '45e7696' # Pin to specific commit for stability - name: Setup Python uses: actions/setup-python@v5 From b11e1d80f7b52d59603a42fabc17c5859dbf6a0c Mon Sep 17 00:00:00 2001 From: Brian Douglas Date: Fri, 8 Aug 2025 09:20:11 -0700 Subject: [PATCH 042/102] fix: similar-issues.yml --- .github/workflows/similar-issues.yml | 78 +++++++++++++++++++++++----- 1 file changed, 65 insertions(+), 13 deletions(-) diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml index 48f536e84..13ebcf269 100644 --- a/.github/workflows/similar-issues.yml +++ b/.github/workflows/similar-issues.yml @@ -11,7 +11,7 @@ jobs: permissions: issues: write pull-requests: write - + steps: - name: Checkout deja-view uses: actions/checkout@v4 @@ -19,43 +19,92 @@ jobs: repository: 'bdougie/deja-view' # Option 1: Pin to specific commit (most secure) ref: '45e7696' # Pin to specific commit for stability - + + # Option 2: Use a tag (recommended after creating releases) + # ref: 'v1.0.0' + + # Option 3: Use main branch (least secure, gets latest changes) + # ref: 'main' + + path: deja-view + - name: Setup Python uses: actions/setup-python@v5 with: python-version: '3.11' - + - name: Install dependencies run: | cd deja-view pip install -r requirements.txt + - name: Index repository if needed + env: + CHROMA_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }} + CHROMA_TENANT: ${{ secrets.CHROMA_TENANT }} + CHROMA_DATABASE: ${{ secrets.CHROMA_DATABASE }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + cd deja-view + + # Index the repository (this will update existing index) + python cli.py index "${{ github.repository }}" --max-issues 200 || true + - name: Search for similar issues id: search env: - CHROMA_CLOUD_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }} - CHROMA_CLOUD_API_URL: ${{ secrets.CHROMA_CLOUD_API_URL }} + CHROMA_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }} + CHROMA_TENANT: ${{ secrets.CHROMA_TENANT }} + CHROMA_DATABASE: ${{ secrets.CHROMA_DATABASE }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | cd deja-view # Determine if this is an issue or PR if [ "${{ github.event_name }}" = "pull_request" ]; then - TITLE="${{ github.event.pull_request.title }}" + ISSUE_URL="https://github.com/${{ github.repository }}/pull/${{ github.event.pull_request.number }}" THRESHOLD="0.85" TOP_K="5" else - TITLE="${{ github.event.issue.title }}" + ISSUE_URL="https://github.com/${{ github.repository }}/issues/${{ github.event.issue.number }}" THRESHOLD="0.7" - TOP_K="3" + TOP_K="5" fi + # Create a Python script to search and format as JSON + cat << 'PYTHON_SCRIPT' > search_similar.py + import sys + import json + import os + from github_similarity_service import SimilarityService + + issue_url = sys.argv[1] + threshold = float(sys.argv[2]) + top_k = int(sys.argv[3]) + + # Parse issue number from URL + issue_number = int(issue_url.split('/')[-1]) + repo_parts = issue_url.split('/') + owner = repo_parts[3] + repo = repo_parts[4] + + service = SimilarityService() + + # Find similar issues + similar = service.find_similar_issues( + owner=owner, + repo=repo, + issue_number=issue_number, + top_k=top_k, + min_similarity=threshold + ) + + # Format as JSON + print(json.dumps(similar)) + PYTHON_SCRIPT + # Search for similar issues - SIMILAR_ISSUES=$(python cli.py search "$TITLE" \ - --repo "${{ github.repository }}" \ - --top-k $TOP_K \ - --threshold $THRESHOLD \ - --format json) + SIMILAR_ISSUES=$(python search_similar.py "$ISSUE_URL" "$THRESHOLD" "$TOP_K") # Save to output echo "similar_issues<> $GITHUB_OUTPUT @@ -73,6 +122,9 @@ jobs: id: discussion_check if: github.event_name == 'issues' env: + CHROMA_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }} + CHROMA_TENANT: ${{ secrets.CHROMA_TENANT }} + CHROMA_DATABASE: ${{ secrets.CHROMA_DATABASE }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | cd deja-view From 1c41a7fd7027a42f4205aa974a0009928081513d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 10:28:18 -0700 Subject: [PATCH 043/102] feat: keep track of autocomplete context --- core/nextEdit/NextEditProvider.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 825515225..78690f200 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -59,6 +59,8 @@ import { PromptMetadata, RecentlyEditedRange, } from "./types.js"; +import { getAutocompleteContext } from "./context/autocompleteContextFetching.js"; +import { EditAggregator } from "./context/aggregateEdits.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -82,6 +84,7 @@ export class NextEditProvider { private contextRetrievalService: ContextRetrievalService; private endpointType: "default" | "fineTuned"; private diffContext: string = ""; + private autocompleteContext: string = ""; private promptMetadata: PromptMetadata | null = null; private currentEditChainId: string | null = null; private previousRequest: AutocompleteInput | null = null; @@ -136,6 +139,10 @@ export class NextEditProvider { this.diffContext = diff; } + public addAutocompleteContext(ctx: string): void { + this.autocompleteContext = ctx; + } + private async _prepareLlm(): Promise { const llm = await this._injectedGetLlm(); @@ -545,11 +552,7 @@ export class NextEditProvider { }; } else if (modelName.includes("model-1")) { ctx = { - recentlyViewedCodeSnippets: - snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ - filepath: snip.filepath, - content: snip.content, - })) ?? [], + contextSnippets: this.autocompleteContext, currentFileContent: helper.fileContents, editableRegionStartLine, editableRegionEndLine, From 92f60e2d15b7a0c5a1855a0d153db067f9ab7107 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 10:29:05 -0700 Subject: [PATCH 044/102] feat: add to autocomplete context on small edit --- core/nextEdit/context/processNextEditData.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/nextEdit/context/processNextEditData.ts b/core/nextEdit/context/processNextEditData.ts index aaa89d33a..0cecfe33e 100644 --- a/core/nextEdit/context/processNextEditData.ts +++ b/core/nextEdit/context/processNextEditData.ts @@ -3,6 +3,7 @@ import { AutocompleteCodeSnippet } from "../../autocomplete/snippets/types"; import { GetLspDefinitionsFunction } from "../../autocomplete/types"; import { ConfigHandler } from "../../config/ConfigHandler"; import { DataLogger } from "../../data/log"; +import { NextEditProvider } from "../NextEditProvider"; import { RecentlyEditedRange } from "../types"; import { getAutocompleteContext } from "./autocompleteContextFetching"; import { createDiff, DiffFormatType } from "./diffFormatting"; @@ -75,6 +76,8 @@ export const processNextEditData = async ({ modelName, ); + NextEditProvider.getInstance().addAutocompleteContext(autocompleteContext); + // console.log( // createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified), // ); From db87e89126882f7df5d60214b9ed01ad4d950655 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 10:30:01 -0700 Subject: [PATCH 045/102] feat: use contextSnippets instead of recentlyViewedCodeSnippets --- core/nextEdit/templating/NextEditPromptEngine.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 2c9235eb0..00e573646 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -30,6 +30,7 @@ import { insertCursorToken, insertEditableRegionTokensWithStaticRange, } from "./utils"; +import { contextSnippetsBlock } from "./model1"; type TemplateRenderer = (vars: TemplateVars) => string; @@ -142,9 +143,7 @@ export async function renderPrompt( ); const model1Ctx: Model1TemplateVars = { - recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( - ctx.recentlyViewedCodeSnippets, - ), + contextSnippets: contextSnippetsBlock(ctx.contextSnippets), currentFileContent: currentFileContentBlock( ctx.currentFileContent, ctx.editableRegionStartLine, From b4c7df46cdff342bda5dcfcb0b7f865fd0511ff9 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 10:30:30 -0700 Subject: [PATCH 046/102] feat: replace field --- core/nextEdit/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 2b9d3162c..4c50e0291 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -91,7 +91,7 @@ export interface NextEditTemplate { export interface TemplateVars {} export interface Model1TemplateVars extends TemplateVars { - recentlyViewedCodeSnippets: string; + contextSnippets: string; currentFileContent: string; editDiffHistory: string; // could be a singe large unified diff currentFilePath: string; From 534e4531848f94518bbe9b0ea8cff10de8bdb781 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 10:31:28 -0700 Subject: [PATCH 047/102] feat: add a helper function to parse contextSnippets --- core/nextEdit/templating/model1.ts | 49 ++++++++++++++++-------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts index 84a754efd..3248d6a05 100644 --- a/core/nextEdit/templating/model1.ts +++ b/core/nextEdit/templating/model1.ts @@ -9,19 +9,33 @@ import { import { extractMetadataFromUnifiedDiff } from "../context/diffFormatting"; import { insertCursorToken } from "./utils"; -export function recentlyViewedCodeSnippetsBlock( - recentlyViewedCodeSnippets: { filepath: string; content: string }[], -) { - return recentlyViewedCodeSnippets.reduce((acc, snippet, i) => { - const block = [ - `${MODEL_1_CONTEXT_FILE_TOKEN}: ${snippet.filepath}`, - `${MODEL_1_SNIPPET_TOKEN}\n${snippet.content}`, - ].join("\n"); +/** + * @param contextSnippets Codestral style snippet with +++++ filename\ncontent or an empty string. + */ +export function contextSnippetsBlock(contextSnippets: string) { + const headerRegex = /^(\+\+\+\+\+ )(.*)/g; + const lines = contextSnippets.split("\n"); - return ( - acc + block + (i === recentlyViewedCodeSnippets.length - 1 ? "" : "\n") - ); - }, ""); + return lines + .reduce((acc, line) => { + const matches = line.match(headerRegex); + if (matches) { + acc.push("\n"); + const filename = matches[2]; + acc.push(`${MODEL_1_CONTEXT_FILE_TOKEN}: ${filename}`); + } else { + if ( + acc.length > 0 && + acc[acc.length - 1].match(headerRegex) // if header was added just before + ) { + acc.push(`${MODEL_1_SNIPPET_TOKEN}`); + } + acc.push(line); + } + + return acc; + }, []) + .join("\n"); } export function currentFileContentBlock( @@ -75,14 +89,3 @@ export function editHistoryBlock( return block.join("\n"); } - -function mercuryNextEditTemplateBuilder( - recentlyViewedCodeSnippets: { filepath: string; code: string }[], - currentFileContent: string, - codeToEdit: string, - codeToEditRange: Range, - cursorPosition: Position, - editDiffHistory: string, // could be a singe large unified diff -): string { - return ""; -} From 712b8525c13946faa0f32d7f9dbddc254d4b8c9c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 8 Aug 2025 10:34:04 -0700 Subject: [PATCH 048/102] chore: jetbrains 1.0.35 (#7057) --- extensions/intellij/gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 175993fa2..75b2d5bd8 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,6 +1,6 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginRepositoryUrl=https://github.com/continuedev/continue -pluginVersion=1.0.34 +pluginVersion=1.0.35 pluginSinceBuild=223 platformType=IC platformVersion=2022.3.3 From faa6c0f6c52f36f9fb4b99193d91a0c69d479bee Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:04:56 -0700 Subject: [PATCH 049/102] test: add vitest for helper functions --- core/nextEdit/templating/model1.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts index 3248d6a05..3a7a617c0 100644 --- a/core/nextEdit/templating/model1.ts +++ b/core/nextEdit/templating/model1.ts @@ -1,4 +1,4 @@ -import { Position, Range } from "../.."; +import { Position } from "../.."; import { MODEL_1_CONTEXT_FILE_TOKEN, MODEL_1_EDITABLE_REGION_END_TOKEN, @@ -13,20 +13,19 @@ import { insertCursorToken } from "./utils"; * @param contextSnippets Codestral style snippet with +++++ filename\ncontent or an empty string. */ export function contextSnippetsBlock(contextSnippets: string) { - const headerRegex = /^(\+\+\+\+\+ )(.*)/g; + const headerRegex = /^(\+\+\+\+\+ )(.*)/; const lines = contextSnippets.split("\n"); return lines .reduce((acc, line) => { const matches = line.match(headerRegex); if (matches) { - acc.push("\n"); const filename = matches[2]; acc.push(`${MODEL_1_CONTEXT_FILE_TOKEN}: ${filename}`); } else { if ( acc.length > 0 && - acc[acc.length - 1].match(headerRegex) // if header was added just before + acc[acc.length - 1].startsWith(MODEL_1_CONTEXT_FILE_TOKEN) // if header was added just before ) { acc.push(`${MODEL_1_SNIPPET_TOKEN}`); } @@ -75,13 +74,14 @@ export function editHistoryBlock( const block: string[] = []; editDiffHistories.forEach((diff) => { - const metadata = extractMetadataFromUnifiedDiff(diff); + const diffWithoutHeader = diff.split("\n").slice(2).join("\n"); + const metadata = extractMetadataFromUnifiedDiff(diffWithoutHeader); block.push( [ `User edited file \"${metadata.oldFilename}\"`, "", "```diff", - `${diff.split("\n").slice(2).join("\n")}`, + `${diffWithoutHeader}`, "```", ].join("\n"), ); From 9652276380fd79a2109c558c48ef4db8523e79f3 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:05:13 -0700 Subject: [PATCH 050/102] feat: add helper for diffFormatting --- .continue/rules/comment-periods.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .continue/rules/comment-periods.md diff --git a/.continue/rules/comment-periods.md b/.continue/rules/comment-periods.md new file mode 100644 index 000000000..bfbcc0ae1 --- /dev/null +++ b/.continue/rules/comment-periods.md @@ -0,0 +1,5 @@ +--- +alwaysApply: true +--- + +End your comments with a period. From 5e38626a3419d4bcb38df5504f53a2558d0ba287 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:05:26 -0700 Subject: [PATCH 051/102] test: add vitest for templating --- core/nextEdit/templating/model1.vitest.ts | 402 ++++++++++++++++++++++ 1 file changed, 402 insertions(+) create mode 100644 core/nextEdit/templating/model1.vitest.ts diff --git a/core/nextEdit/templating/model1.vitest.ts b/core/nextEdit/templating/model1.vitest.ts new file mode 100644 index 000000000..3facc6f6d --- /dev/null +++ b/core/nextEdit/templating/model1.vitest.ts @@ -0,0 +1,402 @@ +import { describe, expect, test } from "vitest"; +import { Position } from "../.."; +import { + contextSnippetsBlock, + currentFileContentBlock, + editHistoryBlock, +} from "./model1"; + +describe("contextSnippetsBlock", () => { + test("should format empty context snippets", () => { + const result = contextSnippetsBlock(""); + expect(result).toBe(""); + }); + + test("should format single context snippet with codestral style header", () => { + const input = `+++++ src/utils.ts +function helper() { + return "test"; +}`; + + const expected = `<|context_file|>: src/utils.ts +<|snippet|> +function helper() { + return "test"; +}`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should format multiple context snippets", () => { + const input = `+++++ src/file1.ts +const var1 = "value1"; + ++++++ src/file2.ts +const var2 = "value2"; +function test() {}`; + + const expected = `<|context_file|>: src/file1.ts +<|snippet|> +const var1 = "value1"; + +<|context_file|>: src/file2.ts +<|snippet|> +const var2 = "value2"; +function test() {}`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should handle context snippet without content", () => { + const input = "+++++ src/empty.ts"; + + const expected = `<|context_file|>: src/empty.ts`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should handle malformed headers gracefully", () => { + const input = `not a header ++++++ src/valid.ts +valid content`; + + const expected = `not a header +<|context_file|>: src/valid.ts +<|snippet|> +valid content`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); + + test("should handle multiple consecutive headers", () => { + const input = `+++++ src/file1.ts ++++++ src/file2.ts +content after headers`; + + const expected = `<|context_file|>: src/file1.ts +<|context_file|>: src/file2.ts +<|snippet|> +content after headers`; + + const result = contextSnippetsBlock(input); + expect(result).toBe(expected); + }); +}); + +describe("currentFileContentBlock", () => { + test("should insert cursor and editable region tokens correctly", () => { + const content = `line 0 +line 1 +line 2 +line 3 +line 4`; + const cursorPosition: Position = { line: 2, character: 4 }; + const editableRegionStartLine = 1; + const editableRegionEndLine = 3; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `line 0 +<|editable_region_start|> +line 1 +line<|user_cursor_is_here|> 2 +line 3 +<|editable_region_end|> +line 4`; + + expect(result).toBe(expected); + }); + + test("should handle cursor at beginning of line", () => { + const content = `line 0 +line 1 +line 2`; + const cursorPosition: Position = { line: 1, character: 0 }; + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +<|user_cursor_is_here|>line 1 +line 2 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); + + test("should handle cursor at end of line", () => { + const content = `line 0 +line 1 +line 2`; + const cursorPosition: Position = { line: 1, character: 6 }; // end of "line 1" + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +line 1<|user_cursor_is_here|> +line 2 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); + + test("should handle single line editable region", () => { + const content = `line 0 +line 1 +line 2`; + const cursorPosition: Position = { line: 1, character: 2 }; + const editableRegionStartLine = 1; + const editableRegionEndLine = 1; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `line 0 +<|editable_region_start|> +li<|user_cursor_is_here|>ne 1 +<|editable_region_end|> +line 2`; + + expect(result).toBe(expected); + }); + + test("should handle cursor outside bounds gracefully", () => { + const content = `line 0 +line 1`; + const cursorPosition: Position = { line: 10, character: 0 }; // out of bounds + const editableRegionStartLine = 0; + const editableRegionEndLine = 1; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +line 1 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); + + test("should handle editable region covering entire file", () => { + const content = `line 0 +line 1 +line 2`; + const cursorPosition: Position = { line: 1, character: 0 }; + const editableRegionStartLine = 0; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `<|editable_region_start|> +line 0 +<|user_cursor_is_here|>line 1 +line 2 +<|editable_region_end|>`; + + expect(result).toBe(expected); + }); +}); + +describe("editHistoryBlock", () => { + test("should format empty edit history", () => { + const result = editHistoryBlock([]); + expect(result).toBe(""); + }); + + test("should format single diff history entry", () => { + const diff = `Index: test.js +=================================================================== +--- a/test.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/test.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1,3 +1,3 @@ + function test() { +- console.log("old"); ++ console.log("new"); + }`; + + const result = editHistoryBlock([diff]); + const expected = `User edited file "test.js" + +\`\`\`diff +--- a/test.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/test.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1,3 +1,3 @@ + function test() { +- console.log("old"); ++ console.log("new"); + } +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should format multiple diff history entries", () => { + const diff1 = `Index: file1.js +=================================================================== +--- a/file1.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/file1.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1 +1 @@ +-const old = 1; ++const new = 1;`; + + const diff2 = `Index: file2.js +=================================================================== +--- a/file2.js 2023-01-01 10:02:00.000000000 +0000 ++++ b/file2.js 2023-01-01 10:03:00.000000000 +0000 +@@ -1 +1 @@ +-let x = "old"; ++let x = "new";`; + + const result = editHistoryBlock([diff1, diff2]); + const expected = `User edited file "file1.js" + +\`\`\`diff +--- a/file1.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/file1.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1 +1 @@ +-const old = 1; ++const new = 1; +\`\`\` +User edited file "file2.js" + +\`\`\`diff +--- a/file2.js 2023-01-01 10:02:00.000000000 +0000 ++++ b/file2.js 2023-01-01 10:03:00.000000000 +0000 +@@ -1 +1 @@ +-let x = "old"; ++let x = "new"; +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle diff with complex filename paths", () => { + const diff = `Index: src/components/Button/Button.tsx +=================================================================== +--- a/src/components/Button/Button.tsx 2023-01-01 10:00:00.000000000 +0000 ++++ b/src/components/Button/Button.tsx 2023-01-01 10:01:00.000000000 +0000 +@@ -1,2 +1,2 @@ +-export const Button = () => ; ++export const Button = () => ;`; + + const result = editHistoryBlock([diff]); + const expected = `User edited file "src/components/Button/Button.tsx" + +\`\`\`diff +--- a/src/components/Button/Button.tsx 2023-01-01 10:00:00.000000000 +0000 ++++ b/src/components/Button/Button.tsx 2023-01-01 10:01:00.000000000 +0000 +@@ -1,2 +1,2 @@ +-export const Button = () => ; ++export const Button = () => ; +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle diff with new file creation", () => { + const diff = `Index: newfile.js +=================================================================== +--- /dev/null 2023-01-01 10:00:00.000000000 +0000 ++++ b/newfile.js 2023-01-01 10:01:00.000000000 +0000 +@@ -0,0 +1,3 @@ ++function newFunction() { ++ return "hello world"; ++}`; + + const result = editHistoryBlock([diff]); + const expected = `User edited file "/dev/null" + +\`\`\`diff +--- /dev/null 2023-01-01 10:00:00.000000000 +0000 ++++ b/newfile.js 2023-01-01 10:01:00.000000000 +0000 +@@ -0,0 +1,3 @@ ++function newFunction() { ++ return "hello world"; ++} +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle diff with file deletion", () => { + const diff = `Index: deletedfile.js +=================================================================== +--- a/deletedfile.js 2023-01-01 10:00:00.000000000 +0000 ++++ /dev/null 2023-01-01 10:01:00.000000000 +0000 +@@ -1,3 +0,0 @@ +-function deletedFunction() { +- return "goodbye"; +-}`; + + const result = editHistoryBlock([diff]); + const expected = `User edited file "deletedfile.js" + +\`\`\`diff +--- a/deletedfile.js 2023-01-01 10:00:00.000000000 +0000 ++++ /dev/null 2023-01-01 10:01:00.000000000 +0000 +@@ -1,3 +0,0 @@ +-function deletedFunction() { +- return "goodbye"; +-} +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should handle minimal diff format", () => { + const diff = `Index: simple.txt +=================================================================== +@@ -1 +1 @@ +-old text ++new text`; + + const result = editHistoryBlock([diff]); + const expected = `User edited file "undefined" + +\`\`\`diff +@@ -1 +1 @@ +-old text ++new text +\`\`\``; + + expect(result).toBe(expected); + }); +}); From 109ef6e70d05ce117f48d5966b9d420417378fcf Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:05:44 -0700 Subject: [PATCH 052/102] feat: add helper to get metadata from unified diff --- core/nextEdit/context/diffFormatting.ts | 95 +++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts index 465a7106f..7103db88c 100644 --- a/core/nextEdit/context/diffFormatting.ts +++ b/core/nextEdit/context/diffFormatting.ts @@ -95,3 +95,98 @@ const createTokenLineDiff = ( // TODO: Implement token line diff return ""; }; + +export interface DiffMetadata { + oldFilename?: string; // Filename in the original version + newFilename?: string; // Filename in the modified version + oldTimestamp?: string; // Timestamp of the original file + newTimestamp?: string; // Timestamp of the modified file + hunks?: Array<{ + // Information about each change hunk + oldStart: number; // Starting line in original file + oldCount: number; // Number of lines in original file + newStart: number; // Starting line in modified file + newCount: number; // Number of lines in modified file + header?: string; // Optional section header + }>; + isBinary?: boolean; // Whether this is a binary file diff + isNew?: boolean; // Whether this is a new file + isDeleted?: boolean; // Whether this file was deleted + isRename?: boolean; // Whether this file was renamed +} + +export function extractMetadataFromUnifiedDiff( + unifiedDiff: string, +): DiffMetadata { + const metadata: DiffMetadata = {}; + const lines = unifiedDiff.split("\n"); + + // Parse the header lines (first two lines) + if (lines.length >= 2) { + // Parse original file info (--- line) + const oldFileMatch = lines[0].match( + /^--- (a\/)?([^\t\s]+)(?:[\t\s]+(.+))?$/, + ); + if (oldFileMatch) { + metadata.oldFilename = oldFileMatch[2]; + metadata.oldTimestamp = oldFileMatch[3]; + + // Check if this is a new file + if (metadata.oldFilename === "/dev/null") { + metadata.isNew = true; + } + } + + // Parse modified file info (+++ line) + const newFileMatch = lines[1].match( + /^\+\+\+ (b\/)?([^\t\s]+)(?:[\t\s]+(.+))?$/, + ); + if (newFileMatch) { + metadata.newFilename = newFileMatch[2]; + metadata.newTimestamp = newFileMatch[3]; + + // Check if this file was deleted + if (metadata.newFilename === "/dev/null") { + metadata.isDeleted = true; + } + } + + // Check if this is a rename (different old and new names) + if ( + metadata.oldFilename && + metadata.newFilename && + metadata.oldFilename !== "/dev/null" && + metadata.newFilename !== "/dev/null" && + metadata.oldFilename !== metadata.newFilename + ) { + metadata.isRename = true; + } + } + + // Parse hunk headers + metadata.hunks = []; + const hunkHeaderRegex = + /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s(.*))?$/; + + for (let i = 2; i < lines.length; i++) { + const line = lines[i]; + const hunkMatch = line.match(hunkHeaderRegex); + + if (hunkMatch) { + metadata.hunks.push({ + oldStart: parseInt(hunkMatch[1], 10), + oldCount: hunkMatch[2] ? parseInt(hunkMatch[2], 10) : 1, + newStart: parseInt(hunkMatch[3], 10), + newCount: hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1, + header: hunkMatch[5], + }); + } + + // Check for binary file marker + if (line.includes("Binary files") || line.includes("GIT binary patch")) { + metadata.isBinary = true; + } + } + + return metadata; +} From 5918041cc086d38743efc1f24e7e674c97541430 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:10:22 -0700 Subject: [PATCH 053/102] test: add vitest for diffFormatting --- .../nextEdit/context/diffFormatting.vitest.ts | 397 ++++++++++++++++++ 1 file changed, 397 insertions(+) create mode 100644 core/nextEdit/context/diffFormatting.vitest.ts diff --git a/core/nextEdit/context/diffFormatting.vitest.ts b/core/nextEdit/context/diffFormatting.vitest.ts new file mode 100644 index 000000000..05561d52b --- /dev/null +++ b/core/nextEdit/context/diffFormatting.vitest.ts @@ -0,0 +1,397 @@ +import { describe, expect, it } from "vitest"; +import { + BeforeAfterDiff, + createBeforeAfterDiff, + createDiff, + CreateDiffArgs, + DiffFormatType, + DiffMetadata, + extractMetadataFromUnifiedDiff, +} from "./diffFormatting"; + +describe("diffFormatting", () => { + const sampleFilePath = "test/sample.js"; + const beforeContent = "const a = 1;\nconst b = 2;"; + const afterContent = "const a = 1;\nconst b = 3;\nconst c = 4;"; + + describe("createDiff", () => { + it("should create unified diff when specified", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("---"); + expect(result).toContain("+++"); + expect(result).toContain("@@"); + expect(result).toContain("-const b = 2;"); + expect(result).toContain("+const b = 3;"); + expect(result).toContain("+const c = 4;"); + }); + + it("should create token line diff when specified", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: sampleFilePath, + diffType: DiffFormatType.TokenLineDiff, + contextLines: 3, + }; + + const result = createDiff(args); + + // Currently returns empty string as TODO + expect(result).toBe(""); + }); + + it("should return empty string for unsupported diff types", () => { + const args: CreateDiffArgs = { + beforeContent, + afterContent, + filePath: sampleFilePath, + diffType: DiffFormatType.RawBeforeAfter, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toBe(""); + }); + + it("should handle empty content", () => { + const args: CreateDiffArgs = { + beforeContent: "", + afterContent: "new content", + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("+++"); + expect(result).toContain("+new content"); + }); + + it("should handle deletion", () => { + const args: CreateDiffArgs = { + beforeContent: "old content", + afterContent: "", + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("---"); + expect(result).toContain("-old content"); + }); + + it("should handle content without newlines", () => { + const args: CreateDiffArgs = { + beforeContent: "line1", + afterContent: "line2", + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }; + + const result = createDiff(args); + + expect(result).toContain("-line1"); + expect(result).toContain("+line2"); + }); + + it("should respect contextLines parameter", () => { + const multiLineContent = Array(10) + .fill("line") + .map((l, i) => `${l}${i}`) + .join("\n"); + const modifiedContent = multiLineContent.replace("line5", "modified5"); + + const args: CreateDiffArgs = { + beforeContent: multiLineContent, + afterContent: modifiedContent, + filePath: sampleFilePath, + diffType: DiffFormatType.Unified, + contextLines: 2, + }; + + const result = createDiff(args); + + expect(result).toContain("@@ -4,5 +4,5 @@"); + }); + }); + + describe("createBeforeAfterDiff", () => { + it("should return BeforeAfterDiff with normalized content", () => { + const result: BeforeAfterDiff = createBeforeAfterDiff( + beforeContent, + afterContent, + sampleFilePath, + ); + + expect(result).toEqual({ + filePath: sampleFilePath, + beforeContent: beforeContent + "\n", + afterContent: afterContent + "\n", + }); + }); + + it("should not add extra newline if content already ends with one", () => { + const contentWithNewline = "const a = 1;\n"; + const result: BeforeAfterDiff = createBeforeAfterDiff( + contentWithNewline, + contentWithNewline, + sampleFilePath, + ); + + expect(result.beforeContent).toBe(contentWithNewline); + expect(result.afterContent).toBe(contentWithNewline); + }); + + it("should handle empty content", () => { + const result: BeforeAfterDiff = createBeforeAfterDiff( + "", + "", + sampleFilePath, + ); + + expect(result).toEqual({ + filePath: sampleFilePath, + beforeContent: "\n", + afterContent: "\n", + }); + }); + + it("should handle mixed newline scenarios", () => { + const beforeWithNewline = "line1\n"; + const afterWithoutNewline = "line2"; + const result: BeforeAfterDiff = createBeforeAfterDiff( + beforeWithNewline, + afterWithoutNewline, + sampleFilePath, + ); + + expect(result.beforeContent).toBe("line1\n"); + expect(result.afterContent).toBe("line2\n"); + }); + }); + + describe("extractMetadataFromUnifiedDiff", () => { + it("should extract basic file information", () => { + const unifiedDiff = `--- a/old.js\ttimestamp1 ++++ b/new.js\ttimestamp2 +@@ -1,3 +1,3 @@ + line1 +-line2 ++modified2 + line3`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("old.js"); + expect(metadata.newFilename).toBe("new.js"); + expect(metadata.oldTimestamp).toBe("timestamp1"); + expect(metadata.newTimestamp).toBe("timestamp2"); + expect(metadata.isNew).toBeFalsy(); + expect(metadata.isDeleted).toBeFalsy(); + expect(metadata.isRename).toBeTruthy(); + }); + + it("should detect new files", () => { + const unifiedDiff = `--- /dev/null ++++ b/new.js +@@ -0,0 +1,2 @@ ++line1 ++line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("/dev/null"); + expect(metadata.newFilename).toBe("new.js"); + expect(metadata.isNew).toBeTruthy(); + expect(metadata.isDeleted).toBeFalsy(); + expect(metadata.isRename).toBeFalsy(); + }); + + it("should detect deleted files", () => { + const unifiedDiff = `--- a/old.js ++++ /dev/null +@@ -1,2 +0,0 @@ +-line1 +-line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("old.js"); + expect(metadata.newFilename).toBe("/dev/null"); + expect(metadata.isNew).toBeFalsy(); + expect(metadata.isDeleted).toBeTruthy(); + expect(metadata.isRename).toBeFalsy(); + }); + + it("should parse hunk information", () => { + const unifiedDiff = `--- a/file.js ++++ b/file.js +@@ -1,5 +1,6 @@ function header + line1 +-line2 ++modified2 ++newline + line3 +@@ -10,3 +11,3 @@ + line10 +-line11 ++modified11 + line12`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.hunks).toHaveLength(2); + expect(metadata.hunks![0]).toEqual({ + oldStart: 1, + oldCount: 5, + newStart: 1, + newCount: 6, + header: "function header", + }); + expect(metadata.hunks![1]).toEqual({ + oldStart: 10, + oldCount: 3, + newStart: 11, + newCount: 3, + header: undefined, + }); + }); + + it("should handle single line hunks", () => { + const unifiedDiff = `--- a/file.js ++++ b/file.js +@@ -1 +1 @@ +-old ++new`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.hunks).toHaveLength(1); + expect(metadata.hunks![0]).toEqual({ + oldStart: 1, + oldCount: 1, + newStart: 1, + newCount: 1, + header: undefined, + }); + }); + + it("should detect binary files", () => { + const unifiedDiff = `--- a/image.png ++++ b/image.png +Binary files a/image.png and b/image.png differ`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.isBinary).toBeTruthy(); + }); + + it("should detect git binary patches", () => { + const unifiedDiff = `--- a/file.bin ++++ b/file.bin +GIT binary patch +delta 123 +...`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.isBinary).toBeTruthy(); + }); + + it("should handle files without a/ b/ prefixes", () => { + const unifiedDiff = `--- old.js ++++ new.js +@@ -1,2 +1,2 @@ +-line1 ++modified1 + line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("old.js"); + expect(metadata.newFilename).toBe("new.js"); + }); + + it("should handle empty diff", () => { + const metadata: DiffMetadata = extractMetadataFromUnifiedDiff(""); + + expect(metadata.oldFilename).toBeUndefined(); + expect(metadata.newFilename).toBeUndefined(); + expect(metadata.hunks).toEqual([]); + expect(metadata.isBinary).toBeFalsy(); + }); + + it("should handle malformed diff gracefully", () => { + const malformedDiff = `not a diff +random text`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(malformedDiff); + + expect(metadata.oldFilename).toBeUndefined(); + expect(metadata.newFilename).toBeUndefined(); + expect(metadata.hunks).toEqual([]); + }); + + it("should not consider same filenames as rename", () => { + const unifiedDiff = `--- a/file.js ++++ b/file.js +@@ -1,2 +1,2 @@ +-line1 ++modified1 + line2`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.isRename).toBeFalsy(); + }); + + it("should handle files with spaces in names", () => { + const unifiedDiff = `--- a/my file.js\t2023-01-01 00:00:00 ++++ b/my new file.js\t2023-01-01 00:01:00 +@@ -1,1 +1,1 @@ +-content ++new content`; + + const metadata: DiffMetadata = + extractMetadataFromUnifiedDiff(unifiedDiff); + + expect(metadata.oldFilename).toBe("my file.js"); + expect(metadata.newFilename).toBe("my new file.js"); + expect(metadata.oldTimestamp).toBe("2023-01-01 00:00:00"); + expect(metadata.newTimestamp).toBe("2023-01-01 00:01:00"); + expect(metadata.isRename).toBeTruthy(); + }); + }); + + describe("DiffFormatType enum", () => { + it("should have correct enum values", () => { + expect(DiffFormatType.Unified).toBe("unified"); + expect(DiffFormatType.RawBeforeAfter).toBe("beforeAfter"); + expect(DiffFormatType.TokenLineDiff).toBe("linediff"); + }); + }); +}); From 59a37c95404dc86c9c01853a9d41e8f96cb6e173 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:10:39 -0700 Subject: [PATCH 054/102] fix: handle cases where filename includes spaces --- core/nextEdit/context/diffFormatting.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts index 7103db88c..c9c0ffa41 100644 --- a/core/nextEdit/context/diffFormatting.ts +++ b/core/nextEdit/context/diffFormatting.ts @@ -124,9 +124,7 @@ export function extractMetadataFromUnifiedDiff( // Parse the header lines (first two lines) if (lines.length >= 2) { // Parse original file info (--- line) - const oldFileMatch = lines[0].match( - /^--- (a\/)?([^\t\s]+)(?:[\t\s]+(.+))?$/, - ); + const oldFileMatch = lines[0].match(/^--- (a\/)?(.+?)(?:\t(.+))?$/); if (oldFileMatch) { metadata.oldFilename = oldFileMatch[2]; metadata.oldTimestamp = oldFileMatch[3]; @@ -138,9 +136,7 @@ export function extractMetadataFromUnifiedDiff( } // Parse modified file info (+++ line) - const newFileMatch = lines[1].match( - /^\+\+\+ (b\/)?([^\t\s]+)(?:[\t\s]+(.+))?$/, - ); + const newFileMatch = lines[1].match(/^\+\+\+ (b\/)?(.+?)(?:\t(.+))?$/); if (newFileMatch) { metadata.newFilename = newFileMatch[2]; metadata.newTimestamp = newFileMatch[3]; From 65cd7d47aa92ff7e40cf5d5fa0559a6f97ad5c1e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 11:17:05 -0700 Subject: [PATCH 055/102] fix: recover from bad merge --- core/nextEdit/templating/NextEditPromptEngine.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 94f80775c..6bd9c21d8 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -41,7 +41,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { }, "model-1": { template: - "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```", + "### User Edits:\n\n{{{editDiffHistory}}}\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{currentFileContent}}}```\n### Response:", }, }; From 4a6fe51fe21e346668629ca5ab58a99203611f9a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 12:10:44 -0700 Subject: [PATCH 056/102] feat: enrich model request with system and user prompt prefix --- core/nextEdit/NextEditProvider.ts | 7 +++--- core/nextEdit/constants.ts | 25 +++++++++++++++++++ .../templating/NextEditPromptEngine.ts | 4 +-- 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index ca5c23eaa..8f9f55527 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -37,6 +37,7 @@ import { replaceEscapedCharacters } from "../util/text.js"; import { MERCURY_CODE_TO_EDIT_OPEN, MERCURY_SYSTEM_PROMPT, + MODEL_1_SYSTEM_PROMPT, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; @@ -60,8 +61,6 @@ import { PromptMetadata, RecentlyEditedRange, } from "./types.js"; -import { getAutocompleteContext } from "./context/autocompleteContextFetching.js"; -import { EditAggregator } from "./context/aggregateEdits.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -578,7 +577,9 @@ export class NextEditProvider { const systemPrompt: Prompt = { role: "system", - content: MERCURY_SYSTEM_PROMPT, + content: modelName.includes("mercury-coder-nextedit") + ? MERCURY_SYSTEM_PROMPT + : MODEL_1_SYSTEM_PROMPT, }; return [systemPrompt, promptMetadata.prompt]; diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 1c94db662..21e249b96 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -8,6 +8,31 @@ export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; export const MODEL_1_CONTEXT_FILE_TOKEN = "<|context_file|>"; export const MODEL_1_SNIPPET_TOKEN = "<|snippet|>"; +export const MODEL_1_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags. + +You have access to the following information to help you make informed suggestions: + +- Context: In the section marked "### Context", there are context items from potentially relevant files in the developer's codebase. Each context item consists of a <|context_file|> marker, the filepath, a <|snippet|> marker, and then some content from that file, in that order. Keep in mind that not all of the context information may be relevant to the task, so use your judgement to determine which parts to consider. +- User Edits: In the section marked "### User Edits:", there is a record of the most recent changes made to the code, helping you understand the evolution of the code and the developer's intentions. These changes are listed from most recent to least recent. It's possible that some of the edit diff history is entirely irrelevant to the developer's change. The changes are provided in a unified line-diff format, i.e. with pluses and minuses for additions and deletions to the code. +- User Excerpt: In the section marked "### User Excerpt:", there is a filepath to the developer's current file, and then an excerpt from that file. The <|editable_region_start|> and <|editable_region_end|> markers are within this excerpt. Your job is to rewrite only this editable region, not the whole excerpt. The excerpt provides additional context on the surroundings of the developer's edit. +- Cursor Position: Within the user excerpt's editable region, the <|user_cursor_is_here|> flag indicates where the developer's cursor is currently located, which can be crucial for understanding what part of the code they are focusing on. Do not produce this marker in your output; simply take it into account. + +Your task is to predict and complete the changes the developer would have made next in the editable region. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they're following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn't get distracted by ensuring your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes. + +# Steps + +1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location. +2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements. +3. **Suggest Edits**: If changes are required, ensure they align with the developer's patterns and improve code quality. +4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style. + +# Output Format + +- Provide only the revised code within the tags. Do not include the tags in your output. +- Ensure that you do not output duplicate code that exists outside of these tags. +- Avoid undoing or reverting the developer's last change unless there are obvious typos or errors.`; +export const MODEL_1_USER_PROMPT_PREFIX = + "Reference the user excerpt, user edits, and the snippets to understand the developer's intent. Update the editable region of the user excerpt by predicting and completing the changes they would have made next. This may be a deletion, addition, or modification of code."; // Mercury Coder Next Edit-specific tokens. export const MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN = diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 6bd9c21d8..deb1b60c6 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -12,6 +12,7 @@ import { MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, MODEL_1_USER_CURSOR_IS_HERE_TOKEN, + MODEL_1_USER_PROMPT_PREFIX, } from "../constants"; import { MercuryTemplateVars, @@ -40,8 +41,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { 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\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, "model-1": { - template: - "### User Edits:\n\n{{{editDiffHistory}}}\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{currentFileContent}}}```\n### Response:", + template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, }, }; From 345e90eb28fae30999647a5e6b2afc7cf7161796 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 12:15:45 -0700 Subject: [PATCH 057/102] fix: use proper import aliases --- core/nextEdit/templating/NextEditPromptEngine.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index deb1b60c6..7d4eb5b80 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -28,7 +28,11 @@ import { editHistoryBlock, recentlyViewedCodeSnippetsBlock, } from "./mercuryCoderNextEdit"; -import { contextSnippetsBlock } from "./model1"; +import { + contextSnippetsBlock, + currentFileContentBlock as model1CurrentFileContentBlock, + editHistoryBlock as model1EditHistoryBlock, +} from "./model1"; import { insertCursorToken, insertEditableRegionTokensWithStaticRange, @@ -41,7 +45,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { 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\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, "model-1": { - template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, + template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, }, }; @@ -126,13 +130,13 @@ export async function renderPrompt( const model1Ctx: Model1TemplateVars = { contextSnippets: contextSnippetsBlock(ctx.contextSnippets), - currentFileContent: currentFileContentBlock( + currentFileContent: model1CurrentFileContentBlock( ctx.currentFileContent, ctx.editableRegionStartLine, ctx.editableRegionEndLine, helper.pos, ), - editDiffHistory: editHistoryBlock(ctx.editDiffHistory), + editDiffHistory: model1EditHistoryBlock(ctx.editDiffHistory), currentFilePath: ctx.currentFilePath, languageShorthand: ctx.languageShorthand, }; From 7106c9dd15f3c84452d7f1b63e0546aba1bd137f Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 12:15:59 -0700 Subject: [PATCH 058/102] feat: use 5 lines as context --- core/nextEdit/context/processSmallEdit.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/nextEdit/context/processSmallEdit.ts b/core/nextEdit/context/processSmallEdit.ts index 5824191b3..a98233cfe 100644 --- a/core/nextEdit/context/processSmallEdit.ts +++ b/core/nextEdit/context/processSmallEdit.ts @@ -20,7 +20,7 @@ export const processSmallEdit = async ( afterContent: beforeAfterdiff.afterContent, filePath: beforeAfterdiff.filePath, diffType: DiffFormatType.Unified, - contextLines: 3, // NOTE: This can change depending on experiments! + contextLines: 5, // NOTE: This can change depending on experiments! }), ); From fc08da2c29ed58dd683be6fbae572d8212eecd3e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 12:29:37 -0700 Subject: [PATCH 059/102] refactor: pass window range as well --- core/nextEdit/NextEditProvider.ts | 23 +++++++++++++++++-- .../templating/NextEditPromptEngine.ts | 2 ++ core/nextEdit/templating/model1.ts | 6 +++-- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 8f9f55527..67f7d1cf0 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -559,11 +559,30 @@ export class NextEditProvider { currentFilePath: helper.filepath, }; } else if (modelName.includes("model-1")) { + // 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 - 1); + const actualEditableEnd = Math.min( + helper.fileLines.length - 1, + helper.pos.line + 5, + ); + + // Ensure editable region boundaries are within the window. + const adjustedEditableStart = Math.max(windowStart, actualEditableStart); + const adjustedEditableEnd = Math.min(windowEnd, actualEditableEnd); ctx = { contextSnippets: this.autocompleteContext, currentFileContent: helper.fileContents, - editableRegionStartLine, - editableRegionEndLine, + windowStart, + windowEnd, + adjustedEditableStart, + adjustedEditableEnd, editDiffHistory: this.diffContext, currentFilePath: helper.filepath, languageShorthand: helper.lang.name, diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 7d4eb5b80..cf7748c17 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -132,6 +132,8 @@ export async function renderPrompt( contextSnippets: contextSnippetsBlock(ctx.contextSnippets), currentFileContent: model1CurrentFileContentBlock( ctx.currentFileContent, + ctx.windowStart, + ctx.windowEnd, ctx.editableRegionStartLine, ctx.editableRegionEndLine, helper.pos, diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts index 3a7a617c0..ad547b549 100644 --- a/core/nextEdit/templating/model1.ts +++ b/core/nextEdit/templating/model1.ts @@ -39,6 +39,8 @@ export function contextSnippetsBlock(contextSnippets: string) { export function currentFileContentBlock( currentFileContent: string, + windowStart: number, + windowEnd: number, editableRegionStartLine: number, editableRegionEndLine: number, cursorPosition: Position, @@ -52,14 +54,14 @@ export function currentFileContentBlock( ); const instrumentedLines = [ - ...insertedCursorLines.slice(0, editableRegionStartLine), + ...insertedCursorLines.slice(windowStart, editableRegionStartLine), MODEL_1_EDITABLE_REGION_START_TOKEN, ...insertedCursorLines.slice( editableRegionStartLine, editableRegionEndLine + 1, ), MODEL_1_EDITABLE_REGION_END_TOKEN, - ...insertedCursorLines.slice(editableRegionEndLine + 1), + ...insertedCursorLines.slice(editableRegionEndLine + 1, windowEnd + 1), ]; return instrumentedLines.join("\n"); From 5314fcbe25ae55980a0a745caa2117300eab62d1 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 12:30:02 -0700 Subject: [PATCH 060/102] test: update test --- core/nextEdit/templating/model1.vitest.ts | 56 ++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/templating/model1.vitest.ts b/core/nextEdit/templating/model1.vitest.ts index 3facc6f6d..c2e603da0 100644 --- a/core/nextEdit/templating/model1.vitest.ts +++ b/core/nextEdit/templating/model1.vitest.ts @@ -94,12 +94,16 @@ line 1 line 2 line 3 line 4`; + const windowStart = 0; + const windowEnd = 4; const cursorPosition: Position = { line: 2, character: 4 }; const editableRegionStartLine = 1; const editableRegionEndLine = 3; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -120,12 +124,16 @@ line 4`; const content = `line 0 line 1 line 2`; + const windowStart = 0; + const windowEnd = 2; const cursorPosition: Position = { line: 1, character: 0 }; const editableRegionStartLine = 0; const editableRegionEndLine = 2; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -144,12 +152,16 @@ line 2 const content = `line 0 line 1 line 2`; + const windowStart = 0; + const windowEnd = 2; const cursorPosition: Position = { line: 1, character: 6 }; // end of "line 1" const editableRegionStartLine = 0; const editableRegionEndLine = 2; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -168,12 +180,16 @@ line 2 const content = `line 0 line 1 line 2`; + const windowStart = 0; + const windowEnd = 2; const cursorPosition: Position = { line: 1, character: 2 }; const editableRegionStartLine = 1; const editableRegionEndLine = 1; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -188,15 +204,19 @@ line 2`; expect(result).toBe(expected); }); - test("should handle cursor outside bounds gracefully", () => { + test("should handle cursor outside bounds gracefully (this shouldn't happen)", () => { const content = `line 0 line 1`; + const windowStart = 0; + const windowEnd = 1; const cursorPosition: Position = { line: 10, character: 0 }; // out of bounds const editableRegionStartLine = 0; const editableRegionEndLine = 1; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -214,12 +234,16 @@ line 1 const content = `line 0 line 1 line 2`; + const windowStart = 0; + const windowEnd = 2; const cursorPosition: Position = { line: 1, character: 0 }; const editableRegionStartLine = 0; const editableRegionEndLine = 2; const result = currentFileContentBlock( content, + windowStart, + windowEnd, editableRegionStartLine, editableRegionEndLine, cursorPosition, @@ -233,6 +257,36 @@ line 2 expect(result).toBe(expected); }); + + test("should handle windowing - content outside window not included", () => { + const content = `line 0 +line 1 +line 2 +line 3 +line 4`; + const windowStart = 1; + const windowEnd = 3; + const cursorPosition: Position = { line: 2, character: 2 }; + const editableRegionStartLine = 2; + const editableRegionEndLine = 2; + + const result = currentFileContentBlock( + content, + windowStart, + windowEnd, + editableRegionStartLine, + editableRegionEndLine, + cursorPosition, + ); + + const expected = `line 1 +<|editable_region_start|> +li<|user_cursor_is_here|>ne 2 +<|editable_region_end|> +line 3`; + + expect(result).toBe(expected); + }); }); describe("editHistoryBlock", () => { From 9937209bb7bfa8037e5ea8a2a24c9d54e25393f5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:13:48 -0700 Subject: [PATCH 061/102] feat: add hunk details to metadata --- core/nextEdit/context/diffFormatting.ts | 61 +++++++++++++++++++++---- 1 file changed, 53 insertions(+), 8 deletions(-) diff --git a/core/nextEdit/context/diffFormatting.ts b/core/nextEdit/context/diffFormatting.ts index c9c0ffa41..38a76b051 100644 --- a/core/nextEdit/context/diffFormatting.ts +++ b/core/nextEdit/context/diffFormatting.ts @@ -108,6 +108,12 @@ export interface DiffMetadata { newStart: number; // Starting line in modified file newCount: number; // Number of lines in modified file header?: string; // Optional section header + lines: Array<{ + type: "context" | "addition" | "deletion"; + content: string; + oldLineNumber?: number; + newLineNumber?: number; + }>; }>; isBinary?: boolean; // Whether this is a binary file diff isNew?: boolean; // Whether this is a new file @@ -159,23 +165,62 @@ export function extractMetadataFromUnifiedDiff( } } - // Parse hunk headers + // Parse hunk headers and content metadata.hunks = []; const hunkHeaderRegex = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(?:\s(.*))?$/; + let currentHunk: NonNullable[0] | null = null; + let oldLineNumber = 0; + let newLineNumber = 0; + for (let i = 2; i < lines.length; i++) { const line = lines[i]; const hunkMatch = line.match(hunkHeaderRegex); if (hunkMatch) { - metadata.hunks.push({ - oldStart: parseInt(hunkMatch[1], 10), - oldCount: hunkMatch[2] ? parseInt(hunkMatch[2], 10) : 1, - newStart: parseInt(hunkMatch[3], 10), - newCount: hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1, - header: hunkMatch[5], - }); + currentHunk = { + oldStart: parseInt(hunkMatch[1], 10), // line number where changes start in original file + oldCount: hunkMatch[2] ? parseInt(hunkMatch[2], 10) : 1, // number of changed lines in original file, default to 1 if not specified + newStart: parseInt(hunkMatch[3], 10), // line number where changes start in modified file + newCount: hunkMatch[4] ? parseInt(hunkMatch[4], 10) : 1, // number of changed lines in modified file, default to 1 if not specified + header: hunkMatch[5], // the line starting with @@ + lines: [], // the actual line changes + }; + + oldLineNumber = currentHunk.oldStart; + newLineNumber = currentHunk.newStart; + + metadata.hunks.push(currentHunk); + } else if ( + currentHunk && + (line.startsWith(" ") || line.startsWith("+") || line.startsWith("-")) + ) { + // Process hunk content lines. + const lineType = line[0]; + const content = line.slice(1); + + if (lineType === " ") { + // Context line (unchanged). + currentHunk.lines.push({ + type: "context", + content, + oldLineNumber: oldLineNumber++, + newLineNumber: newLineNumber++, + }); + } else if (lineType === "+") { + currentHunk.lines.push({ + type: "addition", + content, + newLineNumber: newLineNumber++, + }); + } else if (lineType === "-") { + currentHunk.lines.push({ + type: "deletion", + content, + oldLineNumber: oldLineNumber++, + }); + } } // Check for binary file marker From 4cfe12f5e05cb5c4a2877f7da595882d98cf8a36 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:13:56 -0700 Subject: [PATCH 062/102] test: update test --- .../nextEdit/context/diffFormatting.vitest.ts | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/core/nextEdit/context/diffFormatting.vitest.ts b/core/nextEdit/context/diffFormatting.vitest.ts index 05561d52b..b010f7837 100644 --- a/core/nextEdit/context/diffFormatting.vitest.ts +++ b/core/nextEdit/context/diffFormatting.vitest.ts @@ -265,6 +265,35 @@ describe("diffFormatting", () => { newStart: 1, newCount: 6, header: "function header", + lines: [ + { + content: "line1", + newLineNumber: 1, + oldLineNumber: 1, + type: "context", + }, + { + content: "line2", + oldLineNumber: 2, + type: "deletion", + }, + { + content: "modified2", + newLineNumber: 2, + type: "addition", + }, + { + content: "newline", + newLineNumber: 3, + type: "addition", + }, + { + content: "line3", + newLineNumber: 4, + oldLineNumber: 3, + type: "context", + }, + ], }); expect(metadata.hunks![1]).toEqual({ oldStart: 10, @@ -272,6 +301,30 @@ describe("diffFormatting", () => { newStart: 11, newCount: 3, header: undefined, + lines: [ + { + content: "line10", + newLineNumber: 11, + oldLineNumber: 10, + type: "context", + }, + { + content: "line11", + oldLineNumber: 11, + type: "deletion", + }, + { + content: "modified11", + newLineNumber: 12, + type: "addition", + }, + { + content: "line12", + newLineNumber: 13, + oldLineNumber: 12, + type: "context", + }, + ], }); }); @@ -292,6 +345,18 @@ describe("diffFormatting", () => { newStart: 1, newCount: 1, header: undefined, + lines: [ + { + content: "old", + oldLineNumber: 1, + type: "deletion", + }, + { + content: "new", + newLineNumber: 1, + type: "addition", + }, + ], }); }); From 3c5d91aaaa6d18e8216476f28dd142394e718644 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:16:09 -0700 Subject: [PATCH 063/102] feat: add hunk to prompt --- core/nextEdit/templating/model1.ts | 68 +++++++++++++++++++++--------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/model1.ts index ad547b549..821d46d3b 100644 --- a/core/nextEdit/templating/model1.ts +++ b/core/nextEdit/templating/model1.ts @@ -6,7 +6,6 @@ import { MODEL_1_SNIPPET_TOKEN, MODEL_1_USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; -import { extractMetadataFromUnifiedDiff } from "../context/diffFormatting"; import { insertCursorToken } from "./utils"; /** @@ -68,26 +67,57 @@ export function currentFileContentBlock( } export function editHistoryBlock( - editDiffHistories: string[], // list of unified diffs + editDiffHistories: string, // unified diffs with Index headers ) { - // diffHistory is made from createDiff. - // This uses createPatch from npm diff library, which includes an index line and a separator. - // We get rid of these first two lines. - const block: string[] = []; + if (!editDiffHistories.trim()) { + return ""; + } - editDiffHistories.forEach((diff) => { - const diffWithoutHeader = diff.split("\n").slice(2).join("\n"); - const metadata = extractMetadataFromUnifiedDiff(diffWithoutHeader); - block.push( - [ - `User edited file \"${metadata.oldFilename}\"`, - "", - "```diff", - `${diffWithoutHeader}`, - "```", - ].join("\n"), + const blocks: string[] = []; + + // Split on Index: lines to get the unified diff. + const diffSections = editDiffHistories + .split(/^Index: /m) + .filter((section) => section.trim()); + + for (const section of diffSections) { + const lines = section.split("\n"); + + // Extract filename from the first line (after "Index: " was split off). + const filename = lines[0]; + + // Find the start of the actual diff content (skip ---, +++, and === lines). + const diffLines = lines + .filter( + (line) => + !line.startsWith("---") && + !line.startsWith("+++") && + !line.startsWith("===") && + line.trim() !== "", // remove empty lines from header section + ) + .slice(1); // remove the filename line + + // Only include lines that are actual diff content (@@, +, -, or context lines). + const actualDiffContent = diffLines.filter( + (line) => + line.startsWith("@@") || + line.startsWith("+") || + line.startsWith("-") || + line.startsWith(" "), // context lines ); - }); - return block.join("\n"); + if (actualDiffContent.length === 0) continue; + + const diffBlock = [ + `User edited file "${filename}"`, + "", + "```diff", + actualDiffContent.join("\n"), + "```", + ].join("\n"); + + blocks.push(diffBlock); + } + + return blocks.join("\n"); } From 15a78628f094da80f1d5f2c7111d209cd17fb267 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:16:16 -0700 Subject: [PATCH 064/102] test: update test --- core/nextEdit/templating/model1.vitest.ts | 41 +++++++++-------------- 1 file changed, 15 insertions(+), 26 deletions(-) diff --git a/core/nextEdit/templating/model1.vitest.ts b/core/nextEdit/templating/model1.vitest.ts index c2e603da0..b1020f040 100644 --- a/core/nextEdit/templating/model1.vitest.ts +++ b/core/nextEdit/templating/model1.vitest.ts @@ -291,7 +291,7 @@ line 3`; describe("editHistoryBlock", () => { test("should format empty edit history", () => { - const result = editHistoryBlock([]); + const result = editHistoryBlock(""); expect(result).toBe(""); }); @@ -306,12 +306,10 @@ describe("editHistoryBlock", () => { + console.log("new"); }`; - const result = editHistoryBlock([diff]); + const result = editHistoryBlock(diff); const expected = `User edited file "test.js" \`\`\`diff ---- a/test.js 2023-01-01 10:00:00.000000000 +0000 -+++ b/test.js 2023-01-01 10:01:00.000000000 +0000 @@ -1,3 +1,3 @@ function test() { - console.log("old"); @@ -322,16 +320,16 @@ describe("editHistoryBlock", () => { expect(result).toBe(expected); }); - test("should format multiple diff history entries", () => { - const diff1 = `Index: file1.js + test("should format multiple diff history entries in unified format", () => { + // Multiple diffs should be concatenated into a single string + const unifiedDiff = `Index: file1.js =================================================================== --- a/file1.js 2023-01-01 10:00:00.000000000 +0000 +++ b/file1.js 2023-01-01 10:01:00.000000000 +0000 @@ -1 +1 @@ -const old = 1; -+const new = 1;`; - - const diff2 = `Index: file2.js ++const new = 1; +Index: file2.js =================================================================== --- a/file2.js 2023-01-01 10:02:00.000000000 +0000 +++ b/file2.js 2023-01-01 10:03:00.000000000 +0000 @@ -339,12 +337,10 @@ describe("editHistoryBlock", () => { -let x = "old"; +let x = "new";`; - const result = editHistoryBlock([diff1, diff2]); + const result = editHistoryBlock(unifiedDiff); const expected = `User edited file "file1.js" \`\`\`diff ---- a/file1.js 2023-01-01 10:00:00.000000000 +0000 -+++ b/file1.js 2023-01-01 10:01:00.000000000 +0000 @@ -1 +1 @@ -const old = 1; +const new = 1; @@ -352,8 +348,6 @@ describe("editHistoryBlock", () => { User edited file "file2.js" \`\`\`diff ---- a/file2.js 2023-01-01 10:02:00.000000000 +0000 -+++ b/file2.js 2023-01-01 10:03:00.000000000 +0000 @@ -1 +1 @@ -let x = "old"; +let x = "new"; @@ -362,6 +356,7 @@ User edited file "file2.js" expect(result).toBe(expected); }); + // Fix remaining tests to pass strings instead of arrays test("should handle diff with complex filename paths", () => { const diff = `Index: src/components/Button/Button.tsx =================================================================== @@ -371,12 +366,10 @@ User edited file "file2.js" -export const Button = () => ; +export const Button = () => ;`; - const result = editHistoryBlock([diff]); + const result = editHistoryBlock(diff); const expected = `User edited file "src/components/Button/Button.tsx" \`\`\`diff ---- a/src/components/Button/Button.tsx 2023-01-01 10:00:00.000000000 +0000 -+++ b/src/components/Button/Button.tsx 2023-01-01 10:01:00.000000000 +0000 @@ -1,2 +1,2 @@ -export const Button = () => ; +export const Button = () => ; @@ -395,12 +388,10 @@ User edited file "file2.js" + return "hello world"; +}`; - const result = editHistoryBlock([diff]); - const expected = `User edited file "/dev/null" + const result = editHistoryBlock(diff); + const expected = `User edited file "newfile.js" \`\`\`diff ---- /dev/null 2023-01-01 10:00:00.000000000 +0000 -+++ b/newfile.js 2023-01-01 10:01:00.000000000 +0000 @@ -0,0 +1,3 @@ +function newFunction() { + return "hello world"; @@ -420,12 +411,10 @@ User edited file "file2.js" - return "goodbye"; -}`; - const result = editHistoryBlock([diff]); + const result = editHistoryBlock(diff); const expected = `User edited file "deletedfile.js" \`\`\`diff ---- a/deletedfile.js 2023-01-01 10:00:00.000000000 +0000 -+++ /dev/null 2023-01-01 10:01:00.000000000 +0000 @@ -1,3 +0,0 @@ -function deletedFunction() { - return "goodbye"; @@ -442,8 +431,8 @@ User edited file "file2.js" -old text +new text`; - const result = editHistoryBlock([diff]); - const expected = `User edited file "undefined" + const result = editHistoryBlock(diff); + const expected = `User edited file "simple.txt" \`\`\`diff @@ -1 +1 @@ From 43dd4f622e9147260eb27384db6ca9adb761a8cb Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:16:38 -0700 Subject: [PATCH 065/102] fix: prompt and userEdits --- core/nextEdit/templating/NextEditPromptEngine.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index cf7748c17..326ac4d84 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -45,7 +45,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { 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\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, "model-1": { - template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### Context:\n{{{recentlyViewedCodeSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, + template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, }, }; @@ -120,7 +120,7 @@ export async function renderPrompt( break; } case "model-1": { - userEdits = ctx.userEdits; + userEdits = ctx.editDiffHistory; editedCodeWithTokens = insertTokens( helper.fileContents.split("\n"), From ea02b4b4469b99741f66599811aae361bf02a1b5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Fri, 8 Aug 2025 15:16:45 -0700 Subject: [PATCH 066/102] test: update test --- .../templating/NextEditPromptEngine.vitest.ts | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index 785dd79cc..23ae1d7cb 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -3,6 +3,7 @@ import { Position } from "../.."; import { SnippetPayload } from "../../autocomplete/snippets"; import { AutocompleteSnippetType } from "../../autocomplete/snippets/types"; import { HelperVars } from "../../autocomplete/util/HelperVars"; +import { NEXT_EDIT_MODELS } from "../../llm/constants"; import { MERCURY_CURRENT_FILE_CONTENT_CLOSE, MERCURY_CURRENT_FILE_CONTENT_OPEN, @@ -12,13 +13,13 @@ import { MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, MODEL_1_USER_CURSOR_IS_HERE_TOKEN, + MODEL_1_USER_PROMPT_PREFIX, } from "../constants"; import { renderDefaultSystemPrompt, renderDefaultUserPrompt, renderPrompt, } from "./NextEditPromptEngine"; -import { NEXT_EDIT_MODELS } from "../../llm/constants"; describe("NextEditPromptEngine", () => { describe("renderPrompt", () => { @@ -81,15 +82,33 @@ describe("NextEditPromptEngine", () => { }); it("should render model-1 prompt correctly", async () => { - const result = await renderPrompt(model1Helper, ctx); + // Create proper model-1 context structure matching NextEditProvider.ts + const model1Ctx = { + contextSnippets: + "+++++ /path/to/context.ts\nconst contextVar = 'test';", + currentFileContent: model1Helper.fileContents, + windowStart: 0, // Math.max(0, helper.pos.line - 25) + windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25) + adjustedEditableStart: 0, // Math.max(0, helper.pos.line - 1) within window + adjustedEditableEnd: 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(model1Helper, model1Ctx); + console.log(result); expect(result).toHaveProperty("prompt"); expect(result.prompt.role).toBe("user"); + expect(result.prompt.content).toContain(MODEL_1_USER_PROMPT_PREFIX); + expect(result.prompt.content).toContain("### Context:"); expect(result.prompt.content).toContain("### User Edits:"); expect(result.prompt.content).toContain("### User Excerpts:"); expect(result.prompt.content).toContain("```ts"); - expect(result.userEdits).toBe(ctx.userEdits); + expect(result.userEdits).toBe(model1Ctx.editDiffHistory); expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN); }); From 85314e54130c9c0c9af4ee282d357b08d5362e3b Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Fri, 8 Aug 2025 15:55:16 -0700 Subject: [PATCH 067/102] Delete .continue/rules/comment-periods.md --- .continue/rules/comment-periods.md | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 .continue/rules/comment-periods.md diff --git a/.continue/rules/comment-periods.md b/.continue/rules/comment-periods.md deleted file mode 100644 index bfbcc0ae1..000000000 --- a/.continue/rules/comment-periods.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -alwaysApply: true ---- - -End your comments with a period. From 8d54cfcefbb19851cd3cef2e54599df01af238f0 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 11 Aug 2025 08:19:31 +0530 Subject: [PATCH 068/102] remove system message from models.ts --- gui/src/pages/AddNewModel/configs/models.ts | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index b5c4bbae5..4e032ca7d 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -653,7 +653,6 @@ export const models: { [key: string]: ModelPackage } = { model: "granite-code", contextLength: 20_000, title: "Granite Code", - systemMessage: `You are Granite Chat, an AI language model developed by IBM. You are a cautious assistant. You carefully follow instructions. You are helpful and harmless and you follow ethical guidelines and promote positive behavior. You always respond to greetings (for example, hi, hello, g'day, morning, afternoon, evening, night, what's up, nice to meet you, sup, etc) with "Hello! I am Granite Chat, created by IBM. How can I help you today?". Please do not say anything else and do not start a conversation.`, }, providerOptions: ["ollama", "lmstudio", "llama.cpp", "replicate"], icon: "ibm.png", @@ -1128,8 +1127,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-4o", contextLength: 128_000, title: "GPT-4o", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["openai", "askSage"], icon: "openai.png", @@ -1143,8 +1140,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-4o-mini", contextLength: 128_000, title: "GPT-4o mini", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["openai", "askSage"], icon: "openai.png", @@ -1398,8 +1393,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt4-gov", contextLength: 128_000, title: "GPT-4 gov", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed }, providerOptions: ["askSage"], icon: "openai.png", @@ -1413,8 +1406,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-4o-gov", contextLength: 128_000, title: "GPT-4o-gov", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed }, providerOptions: ["askSage"], icon: "openai.png", @@ -1427,8 +1418,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-gov", contextLength: 8096, title: "GPT-3.5-Turbo gov", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed }, providerOptions: ["askSage"], icon: "openai.png", @@ -1442,8 +1431,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-4o-mini-gov", contextLength: 128_000, title: "GPT-4o-mini gov", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", // Need to set this on the Ask Sage side or just configure it in here to be discussed }, providerOptions: ["askSage"], icon: "openai.png", @@ -1483,8 +1470,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-o1", contextLength: 128_000, title: "GPT-o1", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["askSage"], icon: "openai.png", @@ -1498,8 +1483,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-o1-mini", contextLength: 128_000, title: "GPT-o1-mini", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["askSage"], icon: "openai.png", @@ -1513,8 +1496,6 @@ export const models: { [key: string]: ModelPackage } = { model: "gpt-o3-mini", contextLength: 200_000, title: "GPT-o3-mini", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["askSage"], icon: "openai.png", @@ -1528,8 +1509,6 @@ export const models: { [key: string]: ModelPackage } = { model: "aws-bedrock-claude-35-sonnet-gov", contextLength: 200_000, title: "Claude 3.5 Sonnet gov", - systemMessage: - "You are an expert software developer. You give helpful and concise responses.", }, providerOptions: ["askSage"], icon: "anthropic.png", From 4ea64921775d5c86e7220f01c6dbace44b0d0a01 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 11 Aug 2025 08:23:08 +0530 Subject: [PATCH 069/102] Revert "remove schema parser" This reverts commit 4dea1af5e907b3092b300514ba846d35677f49ba. --- core/llm/llms/Voyage.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index 6a3a3dd1f..94c344a56 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -1,6 +1,21 @@ +import { z } from "zod"; + import { Chunk, LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; +/**used to check a valid response from voyage is received + * reference: https://docs.voyageai.com/reference/reranker-api + */ +const VoyageRerankSuccessResponseSchema = z.object({ + data: z.array( + z.object({ + index: z.number(), + relevance_score: z.number(), + document: z.string(), + }), + ), +}); + class Voyage extends OpenAI { static providerName = "voyage"; static defaultOptions: Partial | undefined = { @@ -36,6 +51,8 @@ class Voyage extends OpenAI { data: Array<{ index: number; relevance_score: number }>; }; + VoyageRerankSuccessResponseSchema.parse(data); + const results = data.data.sort((a, b) => a.index - b.index); return results.map((result) => result.relevance_score); } From 4e181804f69eeac186a07b319732b03db28aa8ae Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 12 Aug 2025 00:47:34 +0530 Subject: [PATCH 070/102] use safe parsed schema --- core/llm/llms/Voyage.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index 94c344a56..9ba43554e 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -51,9 +51,9 @@ class Voyage extends OpenAI { data: Array<{ index: number; relevance_score: number }>; }; - VoyageRerankSuccessResponseSchema.parse(data); + const parsedData = VoyageRerankSuccessResponseSchema.parse(data); - const results = data.data.sort((a, b) => a.index - b.index); + const results = parsedData.data.sort((a, b) => a.index - b.index); return results.map((result) => result.relevance_score); } } From d1f06da04e9e62120ec93f6663611d6c644e4194 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 17:44:11 -0700 Subject: [PATCH 071/102] refactor: rename model 1 to instinct --- core/llm/autodetect.ts | 2 +- core/llm/autodetect.vitest.ts | 12 ++++---- core/llm/constants.ts | 2 +- core/nextEdit/constants.ts | 27 ++++++++++++----- .../templating/NextEditPromptEngine.vitest.ts | 30 +++++++++---------- .../templating/{model1.ts => instinct.ts} | 22 +++++++------- .../{model1.vitest.ts => instinct.vitest.ts} | 2 +- core/nextEdit/templating/utils.ts | 8 ++--- core/nextEdit/templating/utils.vitest.ts | 12 ++++---- core/nextEdit/types.ts | 2 +- 10 files changed, 67 insertions(+), 52 deletions(-) rename core/nextEdit/templating/{model1.ts => instinct.ts} (84%) rename core/nextEdit/templating/{model1.vitest.ts => instinct.vitest.ts} (99%) diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index b2943e316..f167d02f9 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -178,7 +178,7 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired( // update core/nextEdit/templating/NextEditPromptEngine.ts as well. const MODEL_SUPPORTS_NEXT_EDIT: string[] = [ NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, - NEXT_EDIT_MODELS.MODEL_1, + NEXT_EDIT_MODELS.INSTINCT, ]; function modelSupportsNextEdit( diff --git a/core/llm/autodetect.vitest.ts b/core/llm/autodetect.vitest.ts index 01d48aacc..4e250f1ad 100644 --- a/core/llm/autodetect.vitest.ts +++ b/core/llm/autodetect.vitest.ts @@ -245,8 +245,10 @@ describe("modelSupportsNextEdit", () => { ).toBe(true); }); - it("should return true for model-1", () => { - expect(modelSupportsNextEdit(undefined, "model-1", undefined)).toBe(true); + it("should return true for instinct", () => { + expect(modelSupportsNextEdit(undefined, "instinct", undefined)).toBe( + true, + ); }); it("should return true when model contains supported model name as substring", () => { @@ -269,9 +271,9 @@ describe("modelSupportsNextEdit", () => { ).toBe(true); }); - it("should return true when title contains model-1", () => { + it("should return true when title contains instinct", () => { expect( - modelSupportsNextEdit(undefined, "some-model", "model-1 deployment"), + modelSupportsNextEdit(undefined, "some-model", "instinct deployment"), ).toBe(true); }); @@ -317,7 +319,7 @@ describe("modelSupportsNextEdit", () => { it("should handle case sensitivity correctly", () => { expect( - modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "MODEL-1"), + modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"), ).toBe(true); }); diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 5b93048e9..704931af5 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -21,7 +21,7 @@ export enum LLMConfigurationStatuses { export enum NEXT_EDIT_MODELS { MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit", - MODEL_1 = "model-1", + INSTINCT = "instinct", } export { diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 21e249b96..27a743dcc 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -1,14 +1,27 @@ +import { NEXT_EDIT_MODELS } from "../llm/constants"; + export const IS_NEXT_EDIT_ACTIVE = false; export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0; export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5; +export const MODEL_WINDOW_SIZES: Record< + NEXT_EDIT_MODELS, + { topMargin: number; bottomMargin: number } +> = { + "mercury-coder-nextedit": { + topMargin: 0, + bottomMargin: 5, + }, // mercury coder nextedit uses full file diff, so this should be unnecessary + instinct: { topMargin: 1, bottomMargin: 5 }, +}; + // Model 1-specific tokens. -export const MODEL_1_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; -export const MODEL_1_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; -export const MODEL_1_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; -export const MODEL_1_CONTEXT_FILE_TOKEN = "<|context_file|>"; -export const MODEL_1_SNIPPET_TOKEN = "<|snippet|>"; -export const MODEL_1_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags. +export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; +export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; +export const INSTINCT_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; +export const INSTINCT_CONTEXT_FILE_TOKEN = "<|context_file|>"; +export const INSTINCT_SNIPPET_TOKEN = "<|snippet|>"; +export const INSTINCT_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags. You have access to the following information to help you make informed suggestions: @@ -31,7 +44,7 @@ Your task is to predict and complete the changes the developer would have made n - Provide only the revised code within the tags. Do not include the tags in your output. - Ensure that you do not output duplicate code that exists outside of these tags. - Avoid undoing or reverting the developer's last change unless there are obvious typos or errors.`; -export const MODEL_1_USER_PROMPT_PREFIX = +export const INSTINCT_USER_PROMPT_PREFIX = "Reference the user excerpt, user edits, and the snippets to understand the developer's intent. Update the editable region of the user excerpt by predicting and completing the changes they would have made next. This may be a deletion, addition, or modification of code."; // Mercury Coder Next Edit-specific tokens. diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index 23ae1d7cb..3df88e9f3 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -5,6 +5,8 @@ import { AutocompleteSnippetType } from "../../autocomplete/snippets/types"; import { HelperVars } from "../../autocomplete/util/HelperVars"; 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, @@ -12,8 +14,6 @@ import { MERCURY_EDIT_DIFF_HISTORY_OPEN, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE, MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN, - MODEL_1_USER_CURSOR_IS_HERE_TOKEN, - MODEL_1_USER_PROMPT_PREFIX, } from "../constants"; import { renderDefaultSystemPrompt, @@ -24,7 +24,7 @@ import { describe("NextEditPromptEngine", () => { describe("renderPrompt", () => { let mercuryHelper: HelperVars; - let model1Helper: HelperVars; + let instinctHelper: HelperVars; let testHelper: HelperVars; let unsupportedHelper: HelperVars; let ctx: any; @@ -36,8 +36,8 @@ describe("NextEditPromptEngine", () => { pos: { line: 1, character: 12 } as Position, lang: { name: "typescript" }, } as HelperVars; - model1Helper = { - modelName: "continuedev/model-1" as NEXT_EDIT_MODELS, + 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" }, @@ -81,35 +81,35 @@ describe("NextEditPromptEngine", () => { expect(result.userExcerpts).toContain(MERCURY_CURSOR); }); - it("should render model-1 prompt correctly", async () => { - // Create proper model-1 context structure matching NextEditProvider.ts - const model1Ctx = { + 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: model1Helper.fileContents, + currentFileContent: instinctHelper.fileContents, windowStart: 0, // Math.max(0, helper.pos.line - 25) windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25) - adjustedEditableStart: 0, // Math.max(0, helper.pos.line - 1) within window - adjustedEditableEnd: 2, // Math.min(helper.pos.line + 5) within window + 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(model1Helper, model1Ctx); + const result = await renderPrompt(instinctHelper, instinctCtx); console.log(result); expect(result).toHaveProperty("prompt"); expect(result.prompt.role).toBe("user"); - expect(result.prompt.content).toContain(MODEL_1_USER_PROMPT_PREFIX); + 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 Excerpts:"); expect(result.prompt.content).toContain("```ts"); - expect(result.userEdits).toBe(model1Ctx.editDiffHistory); - expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN); + 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 () => { diff --git a/core/nextEdit/templating/model1.ts b/core/nextEdit/templating/instinct.ts similarity index 84% rename from core/nextEdit/templating/model1.ts rename to core/nextEdit/templating/instinct.ts index 821d46d3b..b7e14f165 100644 --- a/core/nextEdit/templating/model1.ts +++ b/core/nextEdit/templating/instinct.ts @@ -1,10 +1,10 @@ import { Position } from "../.."; import { - MODEL_1_CONTEXT_FILE_TOKEN, - MODEL_1_EDITABLE_REGION_END_TOKEN, - MODEL_1_EDITABLE_REGION_START_TOKEN, - MODEL_1_SNIPPET_TOKEN, - MODEL_1_USER_CURSOR_IS_HERE_TOKEN, + INSTINCT_CONTEXT_FILE_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, + INSTINCT_SNIPPET_TOKEN, + INSTINCT_USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; import { insertCursorToken } from "./utils"; @@ -20,13 +20,13 @@ export function contextSnippetsBlock(contextSnippets: string) { const matches = line.match(headerRegex); if (matches) { const filename = matches[2]; - acc.push(`${MODEL_1_CONTEXT_FILE_TOKEN}: ${filename}`); + acc.push(`${INSTINCT_CONTEXT_FILE_TOKEN}: ${filename}`); } else { if ( acc.length > 0 && - acc[acc.length - 1].startsWith(MODEL_1_CONTEXT_FILE_TOKEN) // if header was added just before + acc[acc.length - 1].startsWith(INSTINCT_CONTEXT_FILE_TOKEN) // if header was added just before ) { - acc.push(`${MODEL_1_SNIPPET_TOKEN}`); + acc.push(`${INSTINCT_SNIPPET_TOKEN}`); } acc.push(line); } @@ -49,17 +49,17 @@ export function currentFileContentBlock( const insertedCursorLines = insertCursorToken( currentFileContentLines, cursorPosition, - MODEL_1_USER_CURSOR_IS_HERE_TOKEN, + INSTINCT_USER_CURSOR_IS_HERE_TOKEN, ); const instrumentedLines = [ ...insertedCursorLines.slice(windowStart, editableRegionStartLine), - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, ...insertedCursorLines.slice( editableRegionStartLine, editableRegionEndLine + 1, ), - MODEL_1_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, ...insertedCursorLines.slice(editableRegionEndLine + 1, windowEnd + 1), ]; diff --git a/core/nextEdit/templating/model1.vitest.ts b/core/nextEdit/templating/instinct.vitest.ts similarity index 99% rename from core/nextEdit/templating/model1.vitest.ts rename to core/nextEdit/templating/instinct.vitest.ts index b1020f040..aa15c2fcd 100644 --- a/core/nextEdit/templating/model1.vitest.ts +++ b/core/nextEdit/templating/instinct.vitest.ts @@ -4,7 +4,7 @@ import { contextSnippetsBlock, currentFileContentBlock, editHistoryBlock, -} from "./model1"; +} from "./instinct"; describe("contextSnippetsBlock", () => { test("should format empty context snippets", () => { diff --git a/core/nextEdit/templating/utils.ts b/core/nextEdit/templating/utils.ts index 586fd1795..89d0f6791 100644 --- a/core/nextEdit/templating/utils.ts +++ b/core/nextEdit/templating/utils.ts @@ -1,7 +1,7 @@ import { Position } from "../.."; import { - MODEL_1_EDITABLE_REGION_END_TOKEN, - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "../constants"; @@ -53,9 +53,9 @@ export function insertEditableRegionTokensWithStaticRange( const instrumentedLines = [ ...lines.slice(0, editableRegionStart), - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, ...lines.slice(editableRegionStart, editableRegionEnd + 1), - MODEL_1_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, ...lines.slice(editableRegionEnd + 1), ]; diff --git a/core/nextEdit/templating/utils.vitest.ts b/core/nextEdit/templating/utils.vitest.ts index f60a26d7d..92bd98c3d 100644 --- a/core/nextEdit/templating/utils.vitest.ts +++ b/core/nextEdit/templating/utils.vitest.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; import { Position } from "../.."; import { - MODEL_1_EDITABLE_REGION_END_TOKEN, - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "../constants"; @@ -88,9 +88,9 @@ describe("insertEditableRegionTokensWithStaticRange", () => { const expected = [ ...lines.slice(0, expectedStart), - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, ...lines.slice(expectedStart, expectedEnd + 1), - MODEL_1_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, ...lines.slice(expectedEnd + 1), ]; @@ -112,11 +112,11 @@ describe("insertEditableRegionTokensWithStaticRange", () => { const expected = [ "line 0", - MODEL_1_EDITABLE_REGION_START_TOKEN, + INSTINCT_EDITABLE_REGION_START_TOKEN, "line 1", "line 2", "line 3", - MODEL_1_EDITABLE_REGION_END_TOKEN, + INSTINCT_EDITABLE_REGION_END_TOKEN, "line 4", ]; diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 4c50e0291..d30d803e0 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -90,7 +90,7 @@ export interface NextEditTemplate { export interface TemplateVars {} -export interface Model1TemplateVars extends TemplateVars { +export interface InstinctTemplateVars extends TemplateVars { contextSnippets: string; currentFileContent: string; editDiffHistory: string; // could be a singe large unified diff From ffa1d64a554ab470f38be75e14da303e7786155c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 17:44:51 -0700 Subject: [PATCH 072/102] fix: accepting next edit does not count as typing --- extensions/vscode/src/extension/VsCodeExtension.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 3861edcb7..4b1d8e6ee 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -113,7 +113,8 @@ export class VsCodeExtension { Date.now() - state.lastDocumentChangeTime; if ( state.isTypingSession && - timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY + timeSinceLastDocChange < this.ARBITRARY_TYPING_DELAY && + !NextEditWindowManager.getInstance().hasAccepted() ) { console.log("VsCodeExtension: typing in progress, preserving chain"); return true; From 10d4d4cda0c252a36bac96178593d13b1ea6f2d6 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 17:45:27 -0700 Subject: [PATCH 073/102] fix: editedCodeWithTokens uses the processed context block --- .../templating/NextEditPromptEngine.ts | 54 ++++++++++--------- 1 file changed, 28 insertions(+), 26 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 326ac4d84..98e23e45b 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -4,35 +4,33 @@ import { SnippetPayload } from "../../autocomplete/snippets"; import { HelperVars } from "../../autocomplete/util/HelperVars"; import { NEXT_EDIT_MODELS } from "../../llm/constants"; import { + 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, - MODEL_1_USER_CURSOR_IS_HERE_TOKEN, - MODEL_1_USER_PROMPT_PREFIX, } from "../constants"; import { + InstinctTemplateVars, MercuryTemplateVars, - Model1TemplateVars, NextEditTemplate, PromptMetadata, SystemPrompt, TemplateVars, UserPrompt, } from "../types"; +import { + contextSnippetsBlock, + currentFileContentBlock as instinctCurrentFileContentBlock, + editHistoryBlock as instinctEditHistoryBlock, +} from "./instinct"; import { currentFileContentBlock, editHistoryBlock, recentlyViewedCodeSnippetsBlock, } from "./mercuryCoderNextEdit"; -import { - contextSnippetsBlock, - currentFileContentBlock as model1CurrentFileContentBlock, - editHistoryBlock as model1EditHistoryBlock, -} from "./model1"; import { insertCursorToken, insertEditableRegionTokensWithStaticRange, @@ -44,8 +42,8 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { "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\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, - "model-1": { - template: `${MODEL_1_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{currentFileContent}}}\`\`\`\n### Response:`, + instinct: { + template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`, }, }; @@ -95,11 +93,11 @@ export async function renderPrompt( case "mercury-coder-nextedit": { userEdits = ctx.editDiffHistory; - editedCodeWithTokens = insertTokens( - helper.fileContents.split("\n"), - helper.pos, - MERCURY_CURSOR, - ); + // editedCodeWithTokens = insertTokens( + // helper.fileContents.split("\n"), + // helper.pos, + // MERCURY_CURSOR, + // ); const mercuryCtx: MercuryTemplateVars = { recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( @@ -117,20 +115,22 @@ export async function renderPrompt( tv = mercuryCtx; + editedCodeWithTokens = mercuryCtx.currentFileContent; + break; } - case "model-1": { + case "instinct": { userEdits = ctx.editDiffHistory; - editedCodeWithTokens = insertTokens( - helper.fileContents.split("\n"), - helper.pos, - MODEL_1_USER_CURSOR_IS_HERE_TOKEN, - ); + // editedCodeWithTokens = insertTokens( + // helper.fileContents.split("\n"), + // helper.pos, + // INSTINCT_USER_CURSOR_IS_HERE_TOKEN, + // ); - const model1Ctx: Model1TemplateVars = { + const instinctCtx: InstinctTemplateVars = { contextSnippets: contextSnippetsBlock(ctx.contextSnippets), - currentFileContent: model1CurrentFileContentBlock( + currentFileContent: instinctCurrentFileContentBlock( ctx.currentFileContent, ctx.windowStart, ctx.windowEnd, @@ -138,12 +138,14 @@ export async function renderPrompt( ctx.editableRegionEndLine, helper.pos, ), - editDiffHistory: model1EditHistoryBlock(ctx.editDiffHistory), + editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory), currentFilePath: ctx.currentFilePath, languageShorthand: ctx.languageShorthand, }; - tv = model1Ctx; + tv = instinctCtx; + + editedCodeWithTokens = instinctCtx.currentFileContent; break; } From 3b878986c587faaa4f4c75358030d9592b73599e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 17:45:57 -0700 Subject: [PATCH 074/102] feat: sliding jump starts at the cursor line and expands outwards --- .../NextEditEditableRegionCalculator.ts | 101 +++++++++++++----- 1 file changed, 72 insertions(+), 29 deletions(-) diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index 7ced3b435..ad6a1afa2 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -1,11 +1,9 @@ import Parser from "web-tree-sitter"; import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from ".."; import { getAst } from "../autocomplete/util/ast"; +import { NEXT_EDIT_MODELS } from "../llm/constants"; import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; -import { - NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, -} from "./constants"; +import { MODEL_WINDOW_SIZES } from "./constants"; export enum EditableRegionStrategy { Naive = "naive", @@ -60,16 +58,16 @@ function naiveJump(ctx: any): RangeInFile[] | null { // Sliding splits the file using into sliding window. function slidingJump(ctx: any): RangeInFile[] | null { - const { fileLines, filepath } = ctx; - if (!fileLines || !filepath) { - console.warn("Missing required context for naive jump"); + const { fileLines, filepath, modelName, currentCursorPos } = ctx; + if (!fileLines || !filepath || !modelName || !currentCursorPos) { + console.warn("Missing required context for sliding jump"); return null; } - const windowSize = - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN + - NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN + - 1; // 1 for current line; + const topMargin = MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].topMargin; + const bottomMargin = + MODEL_WINDOW_SIZES[modelName as NEXT_EDIT_MODELS].bottomMargin; + const windowSize = topMargin + bottomMargin + 1; // 1 for current line if (fileLines.length <= windowSize) { return [ @@ -86,29 +84,74 @@ function slidingJump(ctx: any): RangeInFile[] | null { ]; } - const slidingStep = Math.max(1, Math.floor(windowSize / 2)); const ranges: RangeInFile[] = []; + const cursorLine = currentCursorPos.line; - for ( - let startLine = 0; - startLine < fileLines.length; - startLine += slidingStep - ) { - const endLine = Math.min(startLine + windowSize - 1, fileLines.length - 1); + // Create the first window centered around the cursor position + const firstWindowStart = Math.max(0, cursorLine - topMargin); + const firstWindowEnd = Math.min( + fileLines.length - 1, + cursorLine + bottomMargin, + ); - ranges.push({ - filepath, - range: { - start: { line: startLine, character: 0 }, - end: { - line: endLine, - character: fileLines[endLine].length, - }, + ranges.push({ + filepath, + range: { + start: { line: firstWindowStart, character: 0 }, + end: { + line: firstWindowEnd, + character: fileLines[firstWindowEnd].length, }, - }); + }, + }); - if (endLine >= fileLines.length - 1) { - break; + // Alternating pattern: down once, up once, repeat + const slidingStep = Math.max(1, Math.floor(windowSize / 2)); + let currentStartDown = firstWindowEnd + 1; + let currentStartUp = firstWindowStart - slidingStep; + while (currentStartDown < fileLines.length || currentStartUp >= 0) { + // Go down once + if (currentStartDown < fileLines.length) { + const windowStart = currentStartDown; + const windowEnd = Math.min( + windowStart + windowSize - 1, + fileLines.length - 1, + ); + + ranges.push({ + filepath, + range: { + start: { line: windowStart, character: 0 }, + end: { + line: windowEnd, + character: fileLines[windowEnd].length, + }, + }, + }); + + currentStartDown += slidingStep; + } + + // Go up once + if (currentStartUp >= 0) { + const windowStart = Math.max(0, currentStartUp); + const windowEnd = Math.min( + windowStart + windowSize - 1, + fileLines.length - 1, + ); + + ranges.push({ + filepath, + range: { + start: { line: windowStart, character: 0 }, + end: { + line: windowEnd, + character: fileLines[windowEnd].length, + }, + }, + }); + + currentStartUp -= slidingStep; } } From c34b1d82b161402b84581552b2cddf57219d8230 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 18:19:35 -0700 Subject: [PATCH 075/102] feat: diffContext is now an array --- core/nextEdit/NextEditProvider.ts | 50 ++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 18 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 67f7d1cf0..bd396cf7c 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -35,11 +35,10 @@ import { countTokens } from "../llm/countTokens.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { + INSTINCT_SYSTEM_PROMPT, MERCURY_CODE_TO_EDIT_OPEN, MERCURY_SYSTEM_PROMPT, - MODEL_1_SYSTEM_PROMPT, - NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + MODEL_WINDOW_SIZES, } from "./constants.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; import { @@ -83,7 +82,7 @@ export class NextEditProvider { private loggingService: NextEditLoggingService; private contextRetrievalService: ContextRetrievalService; private endpointType: "default" | "fineTuned"; - private diffContext: string = ""; + private diffContext: string[] = []; private autocompleteContext: string = ""; private promptMetadata: PromptMetadata | null = null; private currentEditChainId: string | null = null; @@ -136,7 +135,10 @@ export class NextEditProvider { } public addDiffToContext(diff: string): void { - this.diffContext = diff; + this.diffContext.push(diff); + if (this.diffContext.length > 5) { + this.diffContext.shift(); + } } public addAutocompleteContext(ctx: string): void { @@ -390,16 +392,20 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); + const modelName = helper.modelName.includes("mercury-coder-nextedit") + ? "mercury-coder-nextedit" + : "instinct"; + const { editableRegionStartLine, editableRegionEndLine } = opts?.usingFullFileDiff ? this._calculateOptimalEditableRegion(helper, "tokenizer") : { editableRegionStartLine: Math.max( - helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin, 0, ), editableRegionEndLine: Math.min( - helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin, helper.fileLines.length - 1, ), }; @@ -558,7 +564,7 @@ export class NextEditProvider { editDiffHistory: this.diffContext, currentFilePath: helper.filepath, }; - } else if (modelName.includes("model-1")) { + } else if (modelName.includes("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( @@ -567,10 +573,13 @@ export class NextEditProvider { ); // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive). - const actualEditableStart = Math.max(0, helper.pos.line - 1); + const actualEditableStart = Math.max( + 0, + helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin, + ); const actualEditableEnd = Math.min( helper.fileLines.length - 1, - helper.pos.line + 5, + helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin, ); // Ensure editable region boundaries are within the window. @@ -581,8 +590,8 @@ export class NextEditProvider { currentFileContent: helper.fileContents, windowStart, windowEnd, - adjustedEditableStart, - adjustedEditableEnd, + editableRegionStartLine: adjustedEditableStart, + editableRegionEndLine: adjustedEditableEnd, editDiffHistory: this.diffContext, currentFilePath: helper.filepath, languageShorthand: helper.lang.name, @@ -598,7 +607,7 @@ export class NextEditProvider { role: "system", content: modelName.includes("mercury-coder-nextedit") ? MERCURY_SYSTEM_PROMPT - : MODEL_1_SYSTEM_PROMPT, + : INSTINCT_SYSTEM_PROMPT, }; return [systemPrompt, promptMetadata.prompt]; @@ -666,6 +675,8 @@ export class NextEditProvider { if (!llm) return undefined; const msg: ChatMessage = await llm.chat(prompts, token); + console.log("message"); + console.log(msg.content); if (typeof msg.content !== "string") { return undefined; @@ -677,16 +688,17 @@ export class NextEditProvider { ? replaceEscapedCharacters( msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1], ).replace(/\n$/, "") - : ""; + : replaceEscapedCharacters(msg.content); if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { return await this._handlePartialFileDiff( + // we could use fillFileDiff helper, + editableRegionStartLine, + editableRegionEndLine, startTime, llm, nextCompletion, - editableRegionStartLine, - editableRegionEndLine, ); } else { return await this._handleFullFileDiff( @@ -702,11 +714,11 @@ export class NextEditProvider { private async _handlePartialFileDiff( helper: HelperVars, + editableRegionStartLine: number, + editableRegionEndLine: number, startTime: number, llm: ILLM, nextCompletion: string, - editableRegionStartLine: number, - editableRegionEndLine: number, ): Promise { const oldEditRangeSlice = helper.fileContents .split("\n") @@ -1016,6 +1028,7 @@ export class NextEditProvider { try { const previousOutcome = this.getPreviousCompletion(); if (!previousOutcome) { + console.log("previousOutcome is undefined"); return undefined; } @@ -1026,6 +1039,7 @@ export class NextEditProvider { ctx, ); if (!input) { + console.log("input is undefined"); return undefined; } From 72399ca5ccad459c32d800a732f4ba3ead6a0217 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 18:20:05 -0700 Subject: [PATCH 076/102] feat: use a list of diffContexts instead of a single one --- core/nextEdit/templating/instinct.ts | 80 ++++++++++--------- core/nextEdit/templating/instinct.vitest.ts | 52 ++++++++++-- .../templating/mercuryCoderNextEdit.ts | 7 +- .../templating/mercuryCoderNextEdit.vitest.ts | 4 +- 4 files changed, 95 insertions(+), 48 deletions(-) diff --git a/core/nextEdit/templating/instinct.ts b/core/nextEdit/templating/instinct.ts index b7e14f165..b2140d1da 100644 --- a/core/nextEdit/templating/instinct.ts +++ b/core/nextEdit/templating/instinct.ts @@ -67,56 +67,62 @@ export function currentFileContentBlock( } export function editHistoryBlock( - editDiffHistories: string, // unified diffs with Index headers + editDiffHistories: string[], // array of unified diffs with Index headers ) { - if (!editDiffHistories.trim()) { + if (!editDiffHistories.length) { return ""; } const blocks: string[] = []; - // Split on Index: lines to get the unified diff. - const diffSections = editDiffHistories - .split(/^Index: /m) - .filter((section) => section.trim()); + for (const editDiffHistory of editDiffHistories) { + if (!editDiffHistory.trim()) { + continue; + } - for (const section of diffSections) { - const lines = section.split("\n"); + // Split on Index: lines to get the unified diff. + const diffSections = editDiffHistory + .split(/^Index: /m) + .filter((section) => section.trim()); - // Extract filename from the first line (after "Index: " was split off). - const filename = lines[0]; + for (const section of diffSections) { + const lines = section.split("\n"); - // Find the start of the actual diff content (skip ---, +++, and === lines). - const diffLines = lines - .filter( + // Extract filename from the first line (after "Index: " was split off). + const filename = lines[0]; + + // Find the start of the actual diff content (skip ---, +++, and === lines). + const diffLines = lines + .filter( + (line) => + !line.startsWith("---") && + !line.startsWith("+++") && + !line.startsWith("===") && + line.trim() !== "", // remove empty lines from header section + ) + .slice(1); // remove the filename line + + // Only include lines that are actual diff content (@@, +, -, or context lines). + const actualDiffContent = diffLines.filter( (line) => - !line.startsWith("---") && - !line.startsWith("+++") && - !line.startsWith("===") && - line.trim() !== "", // remove empty lines from header section - ) - .slice(1); // remove the filename line + line.startsWith("@@") || + line.startsWith("+") || + line.startsWith("-") || + line.startsWith(" "), // context lines + ); - // Only include lines that are actual diff content (@@, +, -, or context lines). - const actualDiffContent = diffLines.filter( - (line) => - line.startsWith("@@") || - line.startsWith("+") || - line.startsWith("-") || - line.startsWith(" "), // context lines - ); + if (actualDiffContent.length === 0) continue; - if (actualDiffContent.length === 0) continue; + const diffBlock = [ + `User edited file "${filename}"`, + "", + "```diff", + actualDiffContent.join("\n"), + "```", + ].join("\n"); - const diffBlock = [ - `User edited file "${filename}"`, - "", - "```diff", - actualDiffContent.join("\n"), - "```", - ].join("\n"); - - blocks.push(diffBlock); + blocks.push(diffBlock); + } } return blocks.join("\n"); diff --git a/core/nextEdit/templating/instinct.vitest.ts b/core/nextEdit/templating/instinct.vitest.ts index aa15c2fcd..b7972dc5d 100644 --- a/core/nextEdit/templating/instinct.vitest.ts +++ b/core/nextEdit/templating/instinct.vitest.ts @@ -291,7 +291,7 @@ line 3`; describe("editHistoryBlock", () => { test("should format empty edit history", () => { - const result = editHistoryBlock(""); + const result = editHistoryBlock([]); expect(result).toBe(""); }); @@ -306,7 +306,7 @@ describe("editHistoryBlock", () => { + console.log("new"); }`; - const result = editHistoryBlock(diff); + const result = editHistoryBlock([diff]); const expected = `User edited file "test.js" \`\`\`diff @@ -337,7 +337,45 @@ Index: file2.js -let x = "old"; +let x = "new";`; - const result = editHistoryBlock(unifiedDiff); + const result = editHistoryBlock([unifiedDiff]); + const expected = `User edited file "file1.js" + +\`\`\`diff +@@ -1 +1 @@ +-const old = 1; ++const new = 1; +\`\`\` +User edited file "file2.js" + +\`\`\`diff +@@ -1 +1 @@ +-let x = "old"; ++let x = "new"; +\`\`\``; + + expect(result).toBe(expected); + }); + + test("should format multiple diff history entries", () => { + // Multiple diffs should be concatenated into a single string + const unifiedDiffs = [ + `Index: file1.js +=================================================================== +--- a/file1.js 2023-01-01 10:00:00.000000000 +0000 ++++ b/file1.js 2023-01-01 10:01:00.000000000 +0000 +@@ -1 +1 @@ +-const old = 1; ++const new = 1;`, + `Index: file2.js +=================================================================== +--- a/file2.js 2023-01-01 10:02:00.000000000 +0000 ++++ b/file2.js 2023-01-01 10:03:00.000000000 +0000 +@@ -1 +1 @@ +-let x = "old"; ++let x = "new";`, + ]; + + const result = editHistoryBlock(unifiedDiffs); const expected = `User edited file "file1.js" \`\`\`diff @@ -366,7 +404,7 @@ User edited file "file2.js" -export const Button = () => ; +export const Button = () => ;`; - const result = editHistoryBlock(diff); + const result = editHistoryBlock([diff]); const expected = `User edited file "src/components/Button/Button.tsx" \`\`\`diff @@ -388,7 +426,7 @@ User edited file "file2.js" + return "hello world"; +}`; - const result = editHistoryBlock(diff); + const result = editHistoryBlock([diff]); const expected = `User edited file "newfile.js" \`\`\`diff @@ -411,7 +449,7 @@ User edited file "file2.js" - return "goodbye"; -}`; - const result = editHistoryBlock(diff); + const result = editHistoryBlock([diff]); const expected = `User edited file "deletedfile.js" \`\`\`diff @@ -431,7 +469,7 @@ User edited file "file2.js" -old text +new text`; - const result = editHistoryBlock(diff); + const result = editHistoryBlock([diff]); const expected = `User edited file "simple.txt" \`\`\`diff diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.ts b/core/nextEdit/templating/mercuryCoderNextEdit.ts index 1d7950e96..80c465fc1 100644 --- a/core/nextEdit/templating/mercuryCoderNextEdit.ts +++ b/core/nextEdit/templating/mercuryCoderNextEdit.ts @@ -50,12 +50,15 @@ export function currentFileContentBlock( } export function editHistoryBlock( - editDiffHistory: string, // could be a singe large unified diff + editDiffHistory: string[], // could be a singe large unified diff ) { // diffHistory is made from createDiff. // This uses createPatch from npm diff library, which includes an index line and a separator. // We get rid of these first two lines. - return editDiffHistory.split("\n").slice(2).join("\n"); + return editDiffHistory + .map((diff) => diff.split("\n").slice(2).join("\n")) + .join("\n"); + // return editDiffHistory.split("\n").slice(2).join("\n"); } function mercuryNextEditTemplateBuilder( diff --git a/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts index 6a1c35c74..24c1520e7 100644 --- a/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts +++ b/core/nextEdit/templating/mercuryCoderNextEdit.vitest.ts @@ -108,12 +108,12 @@ describe("mercuryCoderNextEdit", () => { it("should return the edit diff history unchanged", () => { const diffHistory = "diff --git a/file.ts b/file.ts\n==============================\n@@ -1,3 +1,4 @@"; - const result = editHistoryBlock(diffHistory); + const result = editHistoryBlock([diffHistory]); expect(result).toBe("@@ -1,3 +1,4 @@"); }); it("should handle empty diff history", () => { - const result = editHistoryBlock(""); + const result = editHistoryBlock([]); expect(result).toBe(""); }); }); From f249c23f8ada580243e73b03862eaa59458bcf0e Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 11 Aug 2025 19:19:30 -0700 Subject: [PATCH 077/102] fix: skip redundant calculation --- core/nextEdit/NextEditProvider.ts | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index bd396cf7c..7cc7e8df6 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -572,19 +572,22 @@ export class NextEditProvider { 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, - ); + // // 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, actualEditableStart); - const adjustedEditableEnd = Math.min(windowEnd, actualEditableEnd); + const adjustedEditableStart = Math.max( + windowStart, + editableRegionStartLine, + ); + const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine); ctx = { contextSnippets: this.autocompleteContext, currentFileContent: helper.fileContents, From 56cf2abf20e1321b436adae6310b25e78c7c27be Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 11 Aug 2025 19:20:07 -0700 Subject: [PATCH 078/102] feat: Respect Org Policies (#7087) * fix: allow no selected org, respect policy * feat: respect policies in extension * fix: config handler test * fix: context providers test --- core/config/ConfigHandler.ts | 69 +++++++++++-------- core/config/ConfigHandler.vitest.ts | 2 +- core/config/ProfileLifecycleManager.ts | 2 + core/config/profile/doLoadConfig.ts | 15 +++- .../providers/_context-providers.vitest.ts | 3 +- core/control-plane/PolicySingleton.ts | 15 ++++ core/control-plane/client.ts | 21 ++++++ core/core.ts | 4 +- core/protocol/core.ts | 2 +- .../components/config/FatalErrorNotice.tsx | 8 +-- gui/src/pages/config/UserSettingsForm.tsx | 7 ++ packages/config-yaml/src/browser.ts | 1 + packages/config-yaml/src/schemas/policy.ts | 9 +++ 13 files changed, 120 insertions(+), 38 deletions(-) create mode 100644 core/control-plane/PolicySingleton.ts create mode 100644 packages/config-yaml/src/schemas/policy.ts diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 179e5fad4..9d977d071 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -17,6 +17,7 @@ import { ControlPlaneSessionInfo, } from "../control-plane/AuthTypes.js"; import { getControlPlaneEnv } from "../control-plane/env.js"; +import { PolicySingleton } from "../control-plane/PolicySingleton.js"; import { logger } from "../util/logger.js"; import { Telemetry } from "../util/posthog.js"; import { @@ -45,7 +46,7 @@ export class ConfigHandler { private organizations: OrgWithProfiles[] = []; currentProfile: ProfileLifecycleManager | null; - currentOrg: OrgWithProfiles; + currentOrg: OrgWithProfiles | null; totalConfigReloads: number = 0; public isInitialized: Promise; @@ -83,16 +84,9 @@ export class ConfigHandler { this.ide, ); - // Just to be safe, always force a default personal org with local profile manager - this.currentProfile = this.globalLocalProfileManager; - const personalOrg: OrgWithProfiles = { - currentProfile: this.globalLocalProfileManager, - profiles: [this.globalLocalProfileManager], - ...this.PERSONAL_ORG_DESC, - }; - - this.currentOrg = personalOrg; - this.organizations = [personalOrg]; + this.currentOrg = null; + this.currentProfile = null; + this.organizations = []; this.initter = new EventEmitter(); this.isInitialized = new Promise((resolve) => { @@ -132,10 +126,10 @@ export class ConfigHandler { const firstNonPersonal = orgs.find( (org) => org.id !== this.PERSONAL_ORG_DESC.id, ); - const fallback = firstNonPersonal ?? orgs[0]; - // note, ignoring case of zero orgs since should never happen + const fallback: OrgWithProfiles | null = + firstNonPersonal ?? orgs[0] ?? null; - let selectedOrg: OrgWithProfiles; + let selectedOrg: OrgWithProfiles | null; if (currentSelection) { const match = orgs.find((org) => org.id === currentSelection); if (match) { @@ -153,12 +147,12 @@ export class ConfigHandler { this.globalContext.update("lastSelectedOrgIdForWorkspace", { ...selectedOrgs, - [workspaceId]: selectedOrg.id, + [workspaceId]: selectedOrg?.id, }); this.organizations = orgs; this.currentOrg = selectedOrg; - this.currentProfile = selectedOrg.currentProfile; + this.currentProfile = selectedOrg?.currentProfile; await this.reloadConfig(reason, errors); } catch (e) { @@ -179,10 +173,27 @@ export class ConfigHandler { const isSignedIn = await this.controlPlaneClient.isSignedIn(); if (isSignedIn) { try { - const orgDescs = await this.controlPlaneClient.listOrganizations(); + // TODO use policy returned with org, not policy endpoint + const policyResponse = await this.controlPlaneClient.getPolicy(); + PolicySingleton.getInstance().policy = policyResponse; + const orgDescriptions = + await this.controlPlaneClient.listOrganizations(); + const orgsWithPolicy = orgDescriptions.map((d) => ({ + ...d, + policy: policyResponse?.policy, + })); + + if (policyResponse?.policy?.allowOtherOrgs === false) { + if (orgsWithPolicy.length === 0) { + return { orgs: [] }; + } else { + const firstOrg = await this.getNonPersonalHubOrg(orgsWithPolicy[0]); + return { orgs: [firstOrg] }; + } + } const orgs = await Promise.all([ this.getPersonalHubOrg(), - ...orgDescs.map((org) => this.getNonPersonalHubOrg(org)), + ...orgsWithPolicy.map((org) => this.getNonPersonalHubOrg(org)), ]); // TODO make try/catch more granular here, to catch specific org errors return { orgs }; @@ -426,7 +437,7 @@ export class ConfigHandler { // Org id: check id validity, save selection, switch and reload async setSelectedOrgId(orgId: string, profileId?: string) { - if (orgId === this.currentOrg.id) { + if (orgId === this.currentOrg?.id) { return; } const org = this.organizations.find((org) => org.id === orgId); @@ -454,6 +465,9 @@ export class ConfigHandler { // Profile id: check id validity, save selection, switch and reload async setSelectedProfileId(profileId: string) { + if (!this.currentOrg) { + throw new Error(`No org selected`); + } if ( this.currentProfile && profileId === this.currentProfile.profileDescription.id @@ -490,10 +504,7 @@ export class ConfigHandler { if (!this.currentProfile) { return { config: undefined, - errors: [ - { message: "Current profile not found", fatal: true }, - ...(injectErrors ?? []), - ], + errors: injectErrors, configLoadInterrupted: true, }; } @@ -562,7 +573,7 @@ export class ConfigHandler { if (!this.currentProfile) { return { config: undefined, - errors: [{ message: "Current profile not found", fatal: true }], + errors: undefined, configLoadInterrupted: true, }; } @@ -575,7 +586,7 @@ export class ConfigHandler { if (!this.currentProfile) { return { config: undefined, - errors: [{ message: "Current profile not found", fatal: true }], + errors: undefined, configLoadInterrupted: true, }; } @@ -598,11 +609,15 @@ export class ConfigHandler { if (!openProfileId) { return; } - const profile = this.currentOrg.profiles.find( + const profile = this.currentOrg?.profiles.find( (p) => p.profileDescription.id === openProfileId, ); + if (!profile) { + console.error(`Profile ${profileId} not found`); + return; + } - if (profile?.profileDescription.profileType === "local") { + if (profile.profileDescription.profileType === "local") { const configFile = element?.sourceFile ?? profile.profileDescription.uri; await this.ide.openFile(configFile); } else { diff --git a/core/config/ConfigHandler.vitest.ts b/core/config/ConfigHandler.vitest.ts index f58160044..1307ce6ab 100644 --- a/core/config/ConfigHandler.vitest.ts +++ b/core/config/ConfigHandler.vitest.ts @@ -10,7 +10,7 @@ import { defaultConfig } from "./default"; describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should show only local profile", () => { - const profiles = testConfigHandler.currentOrg.profiles; + const profiles = testConfigHandler.currentOrg?.profiles; expect(profiles?.length).toBe(1); expect(profiles?.[0].profileDescription.id).toBe("local"); diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index f61908e32..e16bb7986 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -2,6 +2,7 @@ import { ConfigResult, ConfigValidationError, FullSlug, + Policy, } from "@continuedev/config-yaml"; import { @@ -30,6 +31,7 @@ export interface OrganizationDescription { iconUrl: string; name: string; slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend + policy?: Policy; } export type OrgWithProfiles = OrganizationDescription & { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index ea6b0bf51..d6528454b 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -26,6 +26,7 @@ import RulesContextProvider from "../../context/providers/RulesContextProvider"; import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { getControlPlaneEnv } from "../../control-plane/env.js"; +import { PolicySingleton } from "../../control-plane/PolicySingleton"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; import { getConfigDependentToolDefinitions } from "../../tools"; @@ -325,8 +326,18 @@ export default async function doLoadConfig(options: { } }); - newConfig.allowAnonymousTelemetry = - newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled()); + if (newConfig.allowAnonymousTelemetry !== false) { + if ((await ide.isTelemetryEnabled()) === false) { + newConfig.allowAnonymousTelemetry = false; + } + } + + if ( + PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry === + false + ) { + newConfig.allowAnonymousTelemetry = false; + } // Setup telemetry only after (and if) we know it is enabled await Telemetry.setup( diff --git a/core/context/providers/_context-providers.vitest.ts b/core/context/providers/_context-providers.vitest.ts index f7096bf87..bde33cec1 100644 --- a/core/context/providers/_context-providers.vitest.ts +++ b/core/context/providers/_context-providers.vitest.ts @@ -36,6 +36,7 @@ async function getContextProviderExtras( llmLogger, Promise.resolve(undefined), ); + await configHandler.isInitialized; const { config } = await configHandler.loadConfig(); if (!config) { throw new Error("Config not found"); @@ -54,7 +55,7 @@ async function getContextProviderExtras( }; } -describe.skip("Should successfully run all context providers", () => { +describe("Should successfully run all context providers", () => { afterAll(() => { tearDownTestDir(); }); diff --git a/core/control-plane/PolicySingleton.ts b/core/control-plane/PolicySingleton.ts new file mode 100644 index 000000000..705e67b49 --- /dev/null +++ b/core/control-plane/PolicySingleton.ts @@ -0,0 +1,15 @@ +import { PolicyResponse } from "./client.js"; + +export class PolicySingleton { + private static instance: PolicySingleton; + public policy: PolicyResponse | null = null; + + private constructor() {} + + public static getInstance(): PolicySingleton { + if (!PolicySingleton.instance) { + PolicySingleton.instance = new PolicySingleton(); + } + return PolicySingleton.instance; + } +} diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index ad6112aa9..d5f99a274 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -4,6 +4,7 @@ import { ConfigResult, FQSN, FullSlug, + Policy, SecretResult, SecretType, } from "@continuedev/config-yaml"; @@ -15,6 +16,11 @@ import { IdeInfo, IdeSettings, ModelDescription } from "../index.js"; import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js"; import { getControlPlaneEnv } from "./env.js"; +export interface PolicyResponse { + orgSlug?: string; + policy?: Policy; +} + export interface ControlPlaneWorkspace { id: string; name: string; @@ -215,6 +221,21 @@ export class ControlPlaneClient { } } + public async getPolicy(): Promise { + if (!(await this.isSignedIn())) { + return null; + } + + try { + const resp = await this.request(`ide/policy`, { + method: "GET", + }); + return (await resp.json()) as PolicyResponse; + } catch (e) { + return null; + } + } + public async getFreeTrialStatus(): Promise { if (!(await this.isSignedIn())) { return null; diff --git a/core/core.ts b/core/core.ts index 905151f07..aa558736c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -184,7 +184,7 @@ export class Core { profileId: this.configHandler.currentProfile?.profileDescription.id || null, organizations: this.configHandler.getSerializedOrgs(), - selectedOrgId: this.configHandler.currentOrg.id, + selectedOrgId: this.configHandler.currentOrg?.id ?? null, }); // update additional submenu context providers registered via VSCode API @@ -465,7 +465,7 @@ export class Core { profileId: this.configHandler.currentProfile?.profileDescription.id ?? null, organizations: this.configHandler.getSerializedOrgs(), - selectedOrgId: this.configHandler.currentOrg.id, + selectedOrgId: this.configHandler.currentOrg?.id ?? null, }; }); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 85bca7242..258feaaa9 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -90,7 +90,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { result: ConfigResult; profileId: string | null; organizations: SerializedOrgWithProfiles[]; - selectedOrgId: string; + selectedOrgId: string | null; }, ]; "config/deleteModel": [{ title: string }, void]; diff --git a/gui/src/components/config/FatalErrorNotice.tsx b/gui/src/components/config/FatalErrorNotice.tsx index 8c0a346c2..3d528e810 100644 --- a/gui/src/components/config/FatalErrorNotice.tsx +++ b/gui/src/components/config/FatalErrorNotice.tsx @@ -32,10 +32,10 @@ export const FatalErrorIndicator = () => { return null; } - const displayName = - selectedProfile?.title ?? - `${selectedProfile?.fullSlug?.ownerSlug}/${selectedProfile?.fullSlug?.packageSlug}` ?? - "assistant"; + const displayName = selectedProfile + ? (selectedProfile.title ?? + `${selectedProfile.fullSlug?.ownerSlug}/${selectedProfile.fullSlug?.packageSlug}`) + : "agent"; return ( diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index 576a6d1c6..28ab1947a 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -20,6 +20,7 @@ import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { updateConfig } from "../../redux/slices/configSlice"; +import { selectCurrentOrg } from "../../redux/slices/profilesSlice"; import { setLocalStorage } from "../../util/localStorage"; import { ContinueFeaturesMenu } from "./ContinueFeaturesMenu"; @@ -28,6 +29,8 @@ export function UserSettingsForm() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const config = useAppSelector((state) => state.config.config); + const currentOrg = useAppSelector(selectCurrentOrg); + const [showExperimental, setShowExperimental] = useState(false); const { session } = useAuth(); @@ -133,6 +136,9 @@ export function UserSettingsForm() { "@continue.dev", ); + const disableTelemetryToggle = + currentOrg?.policy?.allowAnonymousTelemetry === false; + return (
{/* {selectedProfile && isLocalProfile(selectedProfile) ? ( @@ -225,6 +231,7 @@ export function UserSettingsForm() { handleUpdate({ allowAnonymousTelemetry: !allowAnonymousTelemetry, diff --git a/packages/config-yaml/src/browser.ts b/packages/config-yaml/src/browser.ts index b8c5cca1b..9edef65aa 100644 --- a/packages/config-yaml/src/browser.ts +++ b/packages/config-yaml/src/browser.ts @@ -15,4 +15,5 @@ export * from "./modelName.js"; export * from "./schemas/data/index.js"; export * from "./schemas/index.js"; export * from "./schemas/models.js"; +export * from "./schemas/policy.js"; export * from "./validation.js"; diff --git a/packages/config-yaml/src/schemas/policy.ts b/packages/config-yaml/src/schemas/policy.ts new file mode 100644 index 000000000..c9b3d3a0b --- /dev/null +++ b/packages/config-yaml/src/schemas/policy.ts @@ -0,0 +1,9 @@ +import * as z from "zod"; + +export const policySchema = z.object({ + allowAnonymousTelemetry: z.boolean().optional(), + allowOtherOrgs: z.boolean().optional(), + // allowLocalConfigFile: z.boolean().optional(), +}); + +export type Policy = z.infer; From e39881a175fbd6536f638537ef61a003e06c7b84 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 11 Aug 2025 21:16:31 -0700 Subject: [PATCH 080/102] chore: bump versions (#7090) --- extensions/intellij/gradle.properties | 2 +- extensions/vscode/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 75b2d5bd8..6ca982585 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -1,6 +1,6 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginRepositoryUrl=https://github.com/continuedev/continue -pluginVersion=1.0.35 +pluginVersion=1.0.36 pluginSinceBuild=223 platformType=IC platformVersion=2022.3.3 diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9d15d1bb6..1282f2cd4 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.75", + "version": "1.1.76", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From cec4f0f4a3ed5fa35f09586dd3f4e932c27b4044 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 12 Aug 2025 13:05:42 +0530 Subject: [PATCH 081/102] abort controller should not be undefined --- core/indexing/CodebaseIndexer.ts | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index b28ece8da..54e84bf17 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -56,7 +56,7 @@ export class CodebaseIndexer { // and only need to `await` it for tests. public initPromise: Promise; private config!: ContinueConfig; - private indexingCancellationController: AbortController | undefined; + private indexingCancellationController: AbortController; private codebaseIndexingState: IndexingProgressUpdate; private readonly pauseToken: PauseToken; @@ -97,6 +97,9 @@ export class CodebaseIndexer { this.pauseToken = new PauseToken(initialPaused); this.initPromise = this.init(configHandler); + + this.indexingCancellationController = new AbortController(); + this.indexingCancellationController.abort(); // initialize and abort so that a new one can be created } // Initialization - load config and attach config listener @@ -693,7 +696,7 @@ export class CodebaseIndexer { } public async refreshCodebaseIndex(paths: string[]) { - if (this.indexingCancellationController) { + if (!this.indexingCancellationController.signal.aborted) { this.indexingCancellationController.abort(); } const localController = new AbortController(); @@ -735,17 +738,13 @@ export class CodebaseIndexer { }); } if (this.indexingCancellationController === localController) { - this.indexingCancellationController.abort(); // abort before clearing to prevent race condition (multiple starts) - this.indexingCancellationController = undefined; + this.indexingCancellationController.abort(); } } public async refreshCodebaseIndexFiles(files: string[]) { // Can be cancelled by codebase index but not vice versa - if ( - this.indexingCancellationController && - !this.indexingCancellationController.signal.aborted - ) { + if (!this.indexingCancellationController.signal.aborted) { return; } const localController = new AbortController(); @@ -771,7 +770,7 @@ export class CodebaseIndexer { }); } if (this.indexingCancellationController === localController) { - this.indexingCancellationController = undefined; + this.indexingCancellationController.abort(); } } From 51c365c990904097a0c6e0a500cb789778795c0f Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 12 Aug 2025 15:56:52 +0530 Subject: [PATCH 082/102] style: prevent text selection when double clicking tool policy --- .../mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx index 97da69b99..09b64f2ed 100644 --- a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx @@ -118,7 +118,7 @@ function ToolPolicyItem(props: ToolDropdownItemProps) {
Date: Tue, 12 Aug 2025 07:50:53 -0700 Subject: [PATCH 083/102] Update cli-review.yaml --- .github/workflows/cli-review.yaml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/cli-review.yaml b/.github/workflows/cli-review.yaml index 8a6557be1..2deab2871 100644 --- a/.github/workflows/cli-review.yaml +++ b/.github/workflows/cli-review.yaml @@ -14,14 +14,14 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" - + - name: Install Continue CLI run: npm install -g @continuedev/cli@1.4.21 - + - name: Run Continue CLI Review run: | echo "Running Continue CLI with hardcoded prompt:" @@ -31,6 +31,6 @@ jobs: echo "" # Run the CLI with a hardcoded prompt and output text directly - echo "Review this pull request and provide feedback on code quality" | cn --config "${{ inputs.assistant }}" -p + echo "Review this pull request and provide feedback on code quality" | cn -p --org continuedev env: - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} \ No newline at end of file + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} From b04c6f62f37f0313499706be46e36065331c0801 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 07:57:40 -0700 Subject: [PATCH 084/102] Update cli-review.yaml --- .github/workflows/cli-review.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cli-review.yaml b/.github/workflows/cli-review.yaml index 2deab2871..9388bdeaf 100644 --- a/.github/workflows/cli-review.yaml +++ b/.github/workflows/cli-review.yaml @@ -20,7 +20,7 @@ jobs: node-version-file: ".nvmrc" - name: Install Continue CLI - run: npm install -g @continuedev/cli@1.4.21 + run: npm install -g @continuedev/cli@1.4.25 - name: Run Continue CLI Review run: | From 3de7baa8ff3f3646d9b8eeaf9e2fbd74030d7d86 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 08:35:31 -0700 Subject: [PATCH 085/102] feat: add continue-review.yaml --- .github/workflows/continue-review.yaml | 253 +++++++++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 .github/workflows/continue-review.yaml diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml new file mode 100644 index 000000000..8bc8b1519 --- /dev/null +++ b/.github/workflows/continue-review.yaml @@ -0,0 +1,253 @@ +name: Continue CLI Code Review + +on: + workflow_call: + inputs: + assistant: + description: "Assistant configuration to use" + required: false + default: "nate/default-assistant" + type: string + prompt: + description: "Custom prompt to use instead of the default PR review" + required: false + type: string + secrets: + CONTINUE_API_KEY: + required: true + workflow_dispatch: + inputs: + assistant: + description: "Assistant configuration to use" + required: false + default: "nate/default-assistant" + type: string + prompt: + description: "Custom prompt to use instead of the default PR review" + required: false + type: string + +permissions: + contents: read + pull-requests: write + issues: write + +jobs: + code-review: + name: AI Code Review + runs-on: ubuntu-latest + + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 # Fetch full history for better context + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Install Continue CLI + run: npm install -g @continuedev/cli@1.4.25 + + - name: Build PR diff prompt + if: github.event_name == 'pull_request' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request') + run: | + # Get PR number - different methods depending on trigger + if [ "${{ github.event_name }}" = "pull_request" ]; then + PR_NUMBER="${{ github.event.number }}" + else + # For workflow_call triggered by PR, we need to get it from context + PR_NUMBER=$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH" 2>/dev/null || echo "") + fi + + if [ -n "$PR_NUMBER" ] && [ "$PR_NUMBER" != "null" ]; then + # Get PR diff using GitHub CLI + gh pr diff $PR_NUMBER > pr_diff.txt + + # Create comprehensive prompt + cat > review_prompt.txt << 'EOF' + You are conducting a code review for a pull request. Below is the git diff showing all the changes: + + EOF + + echo "--- PR DIFF START ---" >> review_prompt.txt + cat pr_diff.txt >> review_prompt.txt + echo "--- PR DIFF END ---" >> review_prompt.txt + + cat >> review_prompt.txt << 'EOF' + + Please analyze these changes and provide a comprehensive code review. Consider: + + 1. **Code Quality**: Are there any bugs, performance issues, or code smells? + 2. **Best Practices**: Does the code follow established patterns and conventions? + 3. **Security**: Are there any potential security vulnerabilities? + 4. **Testing**: Are appropriate tests included or updated? + 5. **Documentation**: Is documentation adequate for the changes? + 6. **Architecture**: Do the changes fit well with the existing codebase structure? + + You can use the available tools to explore the codebase and understand context better. + + Format your response as a markdown code review with the following structure: + + ## Code Review Summary + + ### ✅ Strengths + - [List positive aspects] + + ### ⚠️ Issues Found + - [List any problems with severity levels] + + ### 💡 Suggestions + - [List improvement recommendations] + + ### 🚀 Overall Assessment + [Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT] + + Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production. + EOF + else + echo "Could not determine PR number, using generic prompt" + cat > review_prompt.txt << 'EOF' + Please review the recent changes to this codebase and provide feedback on code quality, potential issues, and suggestions for improvement. + + Format your response as a markdown code review. + EOF + fi + env: + GH_TOKEN: ${{ github.token }} + + - name: Build custom prompt + if: inputs.prompt != '' + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + # Get PR number for custom prompts too + if [ "${{ github.event_name }}" = "pull_request" ]; then + PR_NUMBER="${{ github.event.number }}" + else + # For workflow_call triggered by PR, we need to get it from context + PR_NUMBER=$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH" 2>/dev/null || echo "") + fi + + if [ -n "$PR_NUMBER" ] && [ "$PR_NUMBER" != "null" ]; then + # Get PR diff using GitHub CLI + gh pr diff $PR_NUMBER > pr_diff.txt + + # Create custom prompt with diff included + echo "${{ inputs.prompt }}" > review_prompt.txt + echo "" >> review_prompt.txt + echo "Below is the git diff showing all the changes:" >> review_prompt.txt + echo "" >> review_prompt.txt + echo "--- PR DIFF START ---" >> review_prompt.txt + cat pr_diff.txt >> review_prompt.txt + echo "--- PR DIFF END ---" >> review_prompt.txt + else + echo "${{ inputs.prompt }}" > review_prompt.txt + fi + + - name: Build default prompt for non-PR triggers + if: inputs.prompt == '' && github.event_name != 'pull_request' && (github.event_name != 'workflow_run' || github.event.workflow_run.event != 'pull_request') + run: | + cat > review_prompt.txt << 'EOF' + Please review the recent changes to this codebase and provide feedback on code quality, potential issues, and suggestions for improvement. You do not need to acknowledge what was done well. + + Format your response as a markdown code review with each comment having only a short description about the problem and suggested solution, each being separated by "\n\n---\n\n". + + EOF + + - name: Run Continue CLI Review + run: | + echo "Running Continue CLI with prompt:" + echo "==================================" + cat review_prompt.txt + echo "==================================" + echo "" + + # Run the CLI with the generated prompt and pipe output to code_review.md + cat review_prompt.txt | cn --auto --config "${{ inputs.assistant }}" -p > code_review.md + env: + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + + - name: Upload Review Results + uses: actions/upload-artifact@v4 + if: always() + with: + name: code-review-results + path: | + code_review.md + review_prompt.txt + pr_diff.txt + retention-days: 30 + + - name: Comment PR with Review + if: always() && (github.event_name == 'pull_request' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request')) + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + + try { + let reviewContent = ''; + + if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) { + reviewContent = fs.readFileSync('code_review.md', 'utf8'); + } else { + reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.'; + } + + // Get PR number + let prNumber; + if (context.payload.pull_request) { + prNumber = context.payload.pull_request.number; + } else if (context.payload.workflow_run && context.payload.workflow_run.pull_requests && context.payload.workflow_run.pull_requests.length > 0) { + prNumber = context.payload.workflow_run.pull_requests[0].number; + } + + if (!prNumber) { + console.log('Could not determine PR number for commenting'); + return; + } + + // Unique identifier for our bot comments + const botSignature = ''; + const newComment = `${botSignature}\n${reviewContent}`; + + // Get all comments on the PR + const { data: comments } = await github.rest.issues.listComments({ per_page: 100, + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + }); + + // Find existing Continue CLI review comment + const existingComment = comments.find(comment => + comment.body.includes(botSignature) + ); + + if (existingComment) { + // Update existing comment + await github.rest.issues.updateComment({ + comment_id: existingComment.id, + owner: context.repo.owner, + repo: context.repo.repo, + body: newComment + }); + console.log(`Successfully updated existing comment #${existingComment.id} on PR #${prNumber}`); + } else { + // Create new comment + await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body: newComment + }); + console.log(`Successfully created new comment on PR #${prNumber}`); + } + } catch (error) { + console.log('Failed to post/update comment:', error.message); + console.log('Error details:', error); + } + env: + GITHUB_TOKEN: ${{ github.token }} From cb591bc577ca80947e7aa8ac9b9cd3f038b8c46d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 12 Aug 2025 15:37:08 +0000 Subject: [PATCH 086/102] 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/auto-release.yml | 4 ++-- .github/workflows/compliance.yaml | 4 ++-- .github/workflows/docs.yml | 2 +- .github/workflows/jetbrains-release.yaml | 12 +++++----- .github/workflows/label-merged-prs.yml | 2 +- .github/workflows/main-build.yaml | 2 +- .github/workflows/main.yaml | 8 +++---- .github/workflows/pr-build-upload-vsix.yaml | 2 +- .github/workflows/pr-checks.yaml | 22 +++++++++---------- .github/workflows/preview.yaml | 6 ++--- .github/workflows/reusable-release.yml | 2 +- .github/workflows/similar-issues.yml | 2 +- .../submit-github-dependency-graph.yml | 2 +- .github/workflows/vscode-version-bump.yml | 2 +- 14 files changed, 36 insertions(+), 36 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 031ed1fbe..2e047b5d0 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -16,7 +16,7 @@ jobs: contents: write # Needed for creating releases steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Get version from package.json id: get_version @@ -45,7 +45,7 @@ jobs: contents: write # Needed for creating releases steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 3b69c00cb..6ab98b27e 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -101,7 +101,7 @@ jobs: contents: read steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Node.js uses: actions/setup-node@v4 @@ -134,7 +134,7 @@ jobs: if: ${{ !github.event.pull_request.draft }} steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Check required files run: | diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index b83567fca..589a8e2ed 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -14,7 +14,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Node.js uses: actions/setup-node@v4 diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 72bd84235..a0aa2d3f0 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -56,7 +56,7 @@ jobs: # steps: # # 0. Setup git # - name: Checkout - # uses: actions/checkout@v4 + # uses: actions/checkout@v5 # - name: Set up Git # run: | @@ -102,7 +102,7 @@ jobs: steps: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: ref: ${{ github.event.release.tag_name }} @@ -362,7 +362,7 @@ jobs: steps: # 1. Check-out repository - name: Check-out repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 # 2. Install npm dependencies - name: Use Node.js from .nvmrc @@ -429,7 +429,7 @@ jobs: steps: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v4 + uses: actions/checkout@v5 # Set up Java environment for the next steps - name: Setup Java @@ -482,7 +482,7 @@ jobs: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v4 + uses: actions/checkout@v5 # Set up Java environment for the next steps - name: Setup Java @@ -513,7 +513,7 @@ jobs: # Check out current repository - name: Fetch Sources - uses: actions/checkout@v4 + uses: actions/checkout@v5 # Set up Java environment for the next steps - name: Setup Java diff --git a/.github/workflows/label-merged-prs.yml b/.github/workflows/label-merged-prs.yml index c3c034117..d6f83eba8 100644 --- a/.github/workflows/label-merged-prs.yml +++ b/.github/workflows/label-merged-prs.yml @@ -13,7 +13,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Check if author is in tier list id: check-author diff --git a/.github/workflows/main-build.yaml b/.github/workflows/main-build.yaml index 75e4104ab..a04afb945 100644 --- a/.github/workflows/main-build.yaml +++ b/.github/workflows/main-build.yaml @@ -18,7 +18,7 @@ jobs: matrix: platform: [Linux, macOS] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 2 # Get the last 2 commits to find the merge commit diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 0a5845f6d..cf276f360 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -66,7 +66,7 @@ jobs: arch: arm64 npm_config_arch: arm64 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 @@ -92,7 +92,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # This ensures all tags are fetched @@ -112,7 +112,7 @@ jobs: - build steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up Git run: | @@ -145,7 +145,7 @@ jobs: steps: # 0. Setup git - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up Git run: | diff --git a/.github/workflows/pr-build-upload-vsix.yaml b/.github/workflows/pr-build-upload-vsix.yaml index 6a8250a83..926855b7c 100644 --- a/.github/workflows/pr-build-upload-vsix.yaml +++ b/.github/workflows/pr-build-upload-vsix.yaml @@ -24,7 +24,7 @@ jobs: runner: macos-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index 63afde345..6aa1429a8 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -14,7 +14,7 @@ jobs: prettier-check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -35,7 +35,7 @@ jobs: core-checks: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup packages uses: ./.github/actions/setup-packages - name: Setup core component @@ -71,7 +71,7 @@ jobs: gui-checks: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup packages uses: ./.github/actions/setup-packages - name: Setup core component @@ -101,7 +101,7 @@ jobs: binary-checks: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup packages uses: ./.github/actions/setup-packages - name: Setup core component @@ -123,7 +123,7 @@ jobs: vscode-checks: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup packages uses: ./.github/actions/setup-packages - name: Setup core component @@ -156,7 +156,7 @@ jobs: outputs: packages: ${{ steps.get-packages.outputs.packages }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Get package list id: get-packages run: | @@ -171,7 +171,7 @@ jobs: matrix: package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Setup packages uses: ./.github/actions/setup-packages @@ -197,7 +197,7 @@ jobs: outputs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -257,7 +257,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 @@ -289,7 +289,7 @@ jobs: test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }} command: ["e2e:ci:run", "e2e:ci:run-yaml"] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Run VS Code E2E test uses: ./.github/actions/run-vscode-e2e-test with: @@ -303,7 +303,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Run JetBrains tests uses: ./.github/actions/run-jetbrains-tests with: diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 84e5399eb..b68a65efd 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -66,7 +66,7 @@ jobs: arch: arm64 npm_config_arch: arm64 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 @@ -96,7 +96,7 @@ jobs: - build steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up Git run: | @@ -131,7 +131,7 @@ jobs: steps: # 0. Setup git - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up Git run: | diff --git a/.github/workflows/reusable-release.yml b/.github/workflows/reusable-release.yml index 80d135e29..7cab0df2a 100644 --- a/.github/workflows/reusable-release.yml +++ b/.github/workflows/reusable-release.yml @@ -47,7 +47,7 @@ jobs: working-directory: ${{ inputs.package-path }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml index 13ebcf269..343982af8 100644 --- a/.github/workflows/similar-issues.yml +++ b/.github/workflows/similar-issues.yml @@ -14,7 +14,7 @@ jobs: steps: - name: Checkout deja-view - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: repository: 'bdougie/deja-view' # Option 1: Pin to specific commit (most secure) diff --git a/.github/workflows/submit-github-dependency-graph.yml b/.github/workflows/submit-github-dependency-graph.yml index 50987cc2c..83611f4b7 100644 --- a/.github/workflows/submit-github-dependency-graph.yml +++ b/.github/workflows/submit-github-dependency-graph.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout sources - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Java uses: actions/setup-java@v4 with: diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml index a7aaee3d5..961fa50ba 100644 --- a/.github/workflows/vscode-version-bump.yml +++ b/.github/workflows/vscode-version-bump.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # Fetch all history and tags From 2b384e7fb5f6b4bc695626bb06a1409505320dbd Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 08:45:44 -0700 Subject: [PATCH 087/102] Update continue-review.yaml --- .github/workflows/continue-review.yaml | 132 ++++--------------------- 1 file changed, 21 insertions(+), 111 deletions(-) diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index 8bc8b1519..c2d989175 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -1,31 +1,8 @@ name: Continue CLI Code Review on: - workflow_call: - inputs: - assistant: - description: "Assistant configuration to use" - required: false - default: "nate/default-assistant" - type: string - prompt: - description: "Custom prompt to use instead of the default PR review" - required: false - type: string - secrets: - CONTINUE_API_KEY: - required: true - workflow_dispatch: - inputs: - assistant: - description: "Assistant configuration to use" - required: false - default: "nate/default-assistant" - type: string - prompt: - description: "Custom prompt to use instead of the default PR review" - required: false - type: string + pull_request: + types: [opened, synchronize, reopened] permissions: contents: read @@ -51,32 +28,22 @@ jobs: - name: Install Continue CLI run: npm install -g @continuedev/cli@1.4.25 - - name: Build PR diff prompt - if: github.event_name == 'pull_request' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request') + - name: Build PR Review Prompt run: | - # Get PR number - different methods depending on trigger - if [ "${{ github.event_name }}" = "pull_request" ]; then - PR_NUMBER="${{ github.event.number }}" - else - # For workflow_call triggered by PR, we need to get it from context - PR_NUMBER=$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH" 2>/dev/null || echo "") - fi - - if [ -n "$PR_NUMBER" ] && [ "$PR_NUMBER" != "null" ]; then - # Get PR diff using GitHub CLI - gh pr diff $PR_NUMBER > pr_diff.txt - - # Create comprehensive prompt - cat > review_prompt.txt << 'EOF' + # Get PR diff + gh pr diff ${{ github.event.number }} > pr_diff.txt + + # Create review prompt + cat > review_prompt.txt << 'EOF' You are conducting a code review for a pull request. Below is the git diff showing all the changes: EOF - - echo "--- PR DIFF START ---" >> review_prompt.txt - cat pr_diff.txt >> review_prompt.txt - echo "--- PR DIFF END ---" >> review_prompt.txt - - cat >> review_prompt.txt << 'EOF' + + echo "--- PR DIFF START ---" >> review_prompt.txt + cat pr_diff.txt >> review_prompt.txt + echo "--- PR DIFF END ---" >> review_prompt.txt + + cat >> review_prompt.txt << 'EOF' Please analyze these changes and provide a comprehensive code review. Consider: @@ -107,56 +74,9 @@ jobs: Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production. EOF - else - echo "Could not determine PR number, using generic prompt" - cat > review_prompt.txt << 'EOF' - Please review the recent changes to this codebase and provide feedback on code quality, potential issues, and suggestions for improvement. - - Format your response as a markdown code review. - EOF - fi env: GH_TOKEN: ${{ github.token }} - - name: Build custom prompt - if: inputs.prompt != '' - env: - GITHUB_TOKEN: ${{ github.token }} - run: | - # Get PR number for custom prompts too - if [ "${{ github.event_name }}" = "pull_request" ]; then - PR_NUMBER="${{ github.event.number }}" - else - # For workflow_call triggered by PR, we need to get it from context - PR_NUMBER=$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH" 2>/dev/null || echo "") - fi - - if [ -n "$PR_NUMBER" ] && [ "$PR_NUMBER" != "null" ]; then - # Get PR diff using GitHub CLI - gh pr diff $PR_NUMBER > pr_diff.txt - - # Create custom prompt with diff included - echo "${{ inputs.prompt }}" > review_prompt.txt - echo "" >> review_prompt.txt - echo "Below is the git diff showing all the changes:" >> review_prompt.txt - echo "" >> review_prompt.txt - echo "--- PR DIFF START ---" >> review_prompt.txt - cat pr_diff.txt >> review_prompt.txt - echo "--- PR DIFF END ---" >> review_prompt.txt - else - echo "${{ inputs.prompt }}" > review_prompt.txt - fi - - - name: Build default prompt for non-PR triggers - if: inputs.prompt == '' && github.event_name != 'pull_request' && (github.event_name != 'workflow_run' || github.event.workflow_run.event != 'pull_request') - run: | - cat > review_prompt.txt << 'EOF' - Please review the recent changes to this codebase and provide feedback on code quality, potential issues, and suggestions for improvement. You do not need to acknowledge what was done well. - - Format your response as a markdown code review with each comment having only a short description about the problem and suggested solution, each being separated by "\n\n---\n\n". - - EOF - - name: Run Continue CLI Review run: | echo "Running Continue CLI with prompt:" @@ -165,8 +85,8 @@ jobs: echo "==================================" echo "" - # Run the CLI with the generated prompt and pipe output to code_review.md - cat review_prompt.txt | cn --auto --config "${{ inputs.assistant }}" -p > code_review.md + # Run the CLI with hardcoded assistant and pipe output to code_review.md + cat review_prompt.txt | cn --auto --config "nate/default-assistant" -p > code_review.md env: CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} @@ -182,7 +102,7 @@ jobs: retention-days: 30 - name: Comment PR with Review - if: always() && (github.event_name == 'pull_request' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request')) + if: always() uses: actions/github-script@v7 with: script: | @@ -197,25 +117,15 @@ jobs: reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.'; } - // Get PR number - let prNumber; - if (context.payload.pull_request) { - prNumber = context.payload.pull_request.number; - } else if (context.payload.workflow_run && context.payload.workflow_run.pull_requests && context.payload.workflow_run.pull_requests.length > 0) { - prNumber = context.payload.workflow_run.pull_requests[0].number; - } - - if (!prNumber) { - console.log('Could not determine PR number for commenting'); - return; - } + const prNumber = context.payload.pull_request.number; // Unique identifier for our bot comments const botSignature = ''; const newComment = `${botSignature}\n${reviewContent}`; // Get all comments on the PR - const { data: comments } = await github.rest.issues.listComments({ per_page: 100, + const { data: comments } = await github.rest.issues.listComments({ + per_page: 100, issue_number: prNumber, owner: context.repo.owner, repo: context.repo.repo, @@ -250,4 +160,4 @@ jobs: console.log('Error details:', error); } env: - GITHUB_TOKEN: ${{ github.token }} + GITHUB_TOKEN: ${{ github.token }} \ No newline at end of file From 8b2686c903dd8cddee17cbdb9265548157116fb4 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 08:46:22 -0700 Subject: [PATCH 088/102] Update continue-review.yaml --- .github/workflows/continue-review.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index c2d989175..8e8e656c3 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -2,7 +2,7 @@ name: Continue CLI Code Review on: pull_request: - types: [opened, synchronize, reopened] + types: [opened, ready_for_review] permissions: contents: read @@ -29,6 +29,7 @@ jobs: run: npm install -g @continuedev/cli@1.4.25 - name: Build PR Review Prompt + if: github.event.pull_request.draft == false run: | # Get PR diff gh pr diff ${{ github.event.number }} > pr_diff.txt From ae028938a94cd3595df51022cd987cbeb0d9b514 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 09:01:35 -0700 Subject: [PATCH 089/102] improv: use org setup --- .github/workflows/continue-review.yaml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index 8e8e656c3..03f97b990 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -33,17 +33,17 @@ jobs: run: | # Get PR diff gh pr diff ${{ github.event.number }} > pr_diff.txt - + # Create review prompt cat > review_prompt.txt << 'EOF' You are conducting a code review for a pull request. Below is the git diff showing all the changes: EOF - + echo "--- PR DIFF START ---" >> review_prompt.txt cat pr_diff.txt >> review_prompt.txt echo "--- PR DIFF END ---" >> review_prompt.txt - + cat >> review_prompt.txt << 'EOF' Please analyze these changes and provide a comprehensive code review. Consider: @@ -87,7 +87,7 @@ jobs: echo "" # Run the CLI with hardcoded assistant and pipe output to code_review.md - cat review_prompt.txt | cn --auto --config "nate/default-assistant" -p > code_review.md + cat review_prompt.txt | cn --auto --org continuedev --config continuedev/review-bot -p > code_review.md env: CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} @@ -161,4 +161,4 @@ jobs: console.log('Error details:', error); } env: - GITHUB_TOKEN: ${{ github.token }} \ No newline at end of file + GITHUB_TOKEN: ${{ github.token }} From 7dec41f8af6916fed02d8de9a6f513d11f61ea70 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 09:16:33 -0700 Subject: [PATCH 090/102] Delete cli-review.yaml --- .github/workflows/cli-review.yaml | 36 ------------------------------- 1 file changed, 36 deletions(-) delete mode 100644 .github/workflows/cli-review.yaml diff --git a/.github/workflows/cli-review.yaml b/.github/workflows/cli-review.yaml deleted file mode 100644 index 9388bdeaf..000000000 --- a/.github/workflows/cli-review.yaml +++ /dev/null @@ -1,36 +0,0 @@ -name: CLI Review - -on: - pull_request: - branches: - - main - - push: - branches: - - main - -jobs: - cli-review: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" - - - name: Install Continue CLI - run: npm install -g @continuedev/cli@1.4.25 - - - name: Run Continue CLI Review - run: | - echo "Running Continue CLI with hardcoded prompt:" - echo "==================================" - echo "Review this pull request and provide feedback on code quality" - echo "==================================" - echo "" - - # Run the CLI with a hardcoded prompt and output text directly - echo "Review this pull request and provide feedback on code quality" | cn -p --org continuedev - env: - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} From f15c140d934328b56e8373e77fb53afcae1797ad Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 09:21:24 -0700 Subject: [PATCH 091/102] improv: always leave a new comment --- .github/workflows/continue-review.yaml | 38 ++++---------------------- 1 file changed, 5 insertions(+), 33 deletions(-) diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index 03f97b990..c269a3985 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -120,44 +120,16 @@ jobs: const prNumber = context.payload.pull_request.number; - // Unique identifier for our bot comments - const botSignature = ''; - const newComment = `${botSignature}\n${reviewContent}`; - - // Get all comments on the PR - const { data: comments } = await github.rest.issues.listComments({ - per_page: 100, + // Create new comment + await github.rest.issues.createComment({ issue_number: prNumber, owner: context.repo.owner, repo: context.repo.repo, + body: reviewContent }); - - // Find existing Continue CLI review comment - const existingComment = comments.find(comment => - comment.body.includes(botSignature) - ); - - if (existingComment) { - // Update existing comment - await github.rest.issues.updateComment({ - comment_id: existingComment.id, - owner: context.repo.owner, - repo: context.repo.repo, - body: newComment - }); - console.log(`Successfully updated existing comment #${existingComment.id} on PR #${prNumber}`); - } else { - // Create new comment - await github.rest.issues.createComment({ - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - body: newComment - }); - console.log(`Successfully created new comment on PR #${prNumber}`); - } + console.log(`Successfully created new comment on PR #${prNumber}`); } catch (error) { - console.log('Failed to post/update comment:', error.message); + console.log('Failed to post comment:', error.message); console.log('Error details:', error); } env: From 7c2cb65ea1073b5965aa7ccaa4578671895f2ae9 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 09:25:17 -0700 Subject: [PATCH 092/102] Update continue-review.yaml --- .github/workflows/continue-review.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index c269a3985..53a68fb2a 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -13,6 +13,7 @@ jobs: code-review: name: AI Code Review runs-on: ubuntu-latest + timeout-minutes: 10 steps: - name: Checkout Repository From a7e2d6f520e386578c4e7e2b526e3c3fdb7bf510 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 10:11:37 -0700 Subject: [PATCH 093/102] feat: summon bot --- .github/workflows/continue-review.yaml | 35 +++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index 53a68fb2a..225a3e351 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -3,6 +3,8 @@ name: Continue CLI Code Review on: pull_request: types: [opened, ready_for_review] + issue_comment: + types: [created] permissions: contents: read @@ -14,6 +16,12 @@ jobs: name: AI Code Review runs-on: ubuntu-latest timeout-minutes: 10 + # Only run if it's a PR event OR if it's a comment with @continue-review on a PR + if: | + github.event_name == 'pull_request' || + (github.event_name == 'issue_comment' && + github.event.issue.pull_request && + contains(github.event.comment.body, '@continue-review')) steps: - name: Checkout Repository @@ -30,10 +38,17 @@ jobs: run: npm install -g @continuedev/cli@1.4.25 - name: Build PR Review Prompt - if: github.event.pull_request.draft == false run: | + # Get PR number based on event type + if [ "${{ github.event_name }}" = "pull_request" ]; then + PR_NUMBER="${{ github.event.number }}" + else + # For issue_comment event on a PR + PR_NUMBER="${{ github.event.issue.number }}" + fi + # Get PR diff - gh pr diff ${{ github.event.number }} > pr_diff.txt + gh pr diff $PR_NUMBER > pr_diff.txt # Create review prompt cat > review_prompt.txt << 'EOF' @@ -119,7 +134,19 @@ jobs: reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.'; } - const prNumber = context.payload.pull_request.number; + // Get PR number based on event type + let prNumber; + if (context.eventName === 'pull_request') { + prNumber = context.payload.pull_request.number; + } else { + // For issue_comment event + prNumber = context.payload.issue.number; + } + + // Add a header if triggered by comment + if (context.eventName === 'issue_comment') { + reviewContent = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewContent}`; + } // Create new comment await github.rest.issues.createComment({ @@ -134,4 +161,4 @@ jobs: console.log('Error details:', error); } env: - GITHUB_TOKEN: ${{ github.token }} + GITHUB_TOKEN: ${{ github.token }} \ No newline at end of file From e623242d3cf06dbe2fb547968d014b13e5443783 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 10:23:52 -0700 Subject: [PATCH 094/102] improv: add temporary permissions checks --- .github/workflows/continue-review.yaml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index 225a3e351..f6f898bec 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -16,9 +16,14 @@ jobs: name: AI Code Review runs-on: ubuntu-latest timeout-minutes: 10 - # Only run if it's a PR event OR if it's a comment with @continue-review on a PR + # Only run if: + # - It's a PR event from a team member (with write/admin permissions) + # - OR it's a comment with @continue-review on a PR (from anyone) if: | - github.event_name == 'pull_request' || + (github.event_name == 'pull_request' && + (github.event.pull_request.author_association == 'OWNER' || + github.event.pull_request.author_association == 'MEMBER' || + github.event.pull_request.author_association == 'COLLABORATOR')) || (github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '@continue-review')) From 45c19fafdfd71a7b6950a951048b6a39b95653fa Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 10:25:49 -0700 Subject: [PATCH 095/102] improv: add AI code reviews --- .github/pull_request_template.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 348566cd8..62ec1fb89 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -2,6 +2,11 @@ [ What changed? Feel free to be brief. ] +## AI Code Review + +- **Team members**: AI review will run automatically when PR is opened or marked ready for review +- **Community contributors**: Request AI review by commenting `@continue-review` on your PR + ## Checklist - [] I've read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md) From fafea05500f447035901b4b6439f058545a9b9ca Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 11:09:49 -0700 Subject: [PATCH 096/102] improv: make it readonly and allow to summon by comment from members only --- .github/pull_request_template.md | 4 ++-- .github/workflows/continue-review.yaml | 9 ++++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 62ec1fb89..281f61c1f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -4,8 +4,8 @@ ## AI Code Review -- **Team members**: AI review will run automatically when PR is opened or marked ready for review -- **Community contributors**: Request AI review by commenting `@continue-review` on your PR +- **Team members only**: AI review runs automatically when PR is opened or marked ready for review +- Team members can also trigger a review by commenting `@continue-review` ## Checklist diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index f6f898bec..6c282ae57 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -18,7 +18,7 @@ jobs: timeout-minutes: 10 # Only run if: # - It's a PR event from a team member (with write/admin permissions) - # - OR it's a comment with @continue-review on a PR (from anyone) + # - OR it's a comment with @continue-review on a PR from a team member if: | (github.event_name == 'pull_request' && (github.event.pull_request.author_association == 'OWNER' || @@ -26,7 +26,10 @@ jobs: github.event.pull_request.author_association == 'COLLABORATOR')) || (github.event_name == 'issue_comment' && github.event.issue.pull_request && - contains(github.event.comment.body, '@continue-review')) + contains(github.event.comment.body, '@continue-review') && + (github.event.comment.author_association == 'OWNER' || + github.event.comment.author_association == 'MEMBER' || + github.event.comment.author_association == 'COLLABORATOR')) steps: - name: Checkout Repository @@ -108,7 +111,7 @@ jobs: echo "" # Run the CLI with hardcoded assistant and pipe output to code_review.md - cat review_prompt.txt | cn --auto --org continuedev --config continuedev/review-bot -p > code_review.md + cat review_prompt.txt | cn --readonly --org continuedev --config continuedev/review-bot -p > code_review.md env: CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} From 9150b6f68028d02a62676448ef295b99f3cad33b Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 12 Aug 2025 11:30:02 -0700 Subject: [PATCH 097/102] improv: prompt --- .github/workflows/continue-review.yaml | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/.github/workflows/continue-review.yaml b/.github/workflows/continue-review.yaml index 6c282ae57..95a9c48ea 100644 --- a/.github/workflows/continue-review.yaml +++ b/.github/workflows/continue-review.yaml @@ -54,7 +54,7 @@ jobs: # For issue_comment event on a PR PR_NUMBER="${{ github.event.issue.number }}" fi - + # Get PR diff gh pr diff $PR_NUMBER > pr_diff.txt @@ -86,13 +86,27 @@ jobs: ## Code Review Summary ### ✅ Strengths - - [List positive aspects] + - **[Aspect]**: [Description of what was done well] ### ⚠️ Issues Found - - [List any problems with severity levels] + + Only include the severity subheaders below if you actually found issues at that level: + + #### Critical + - **[Issue Title]**: [Description of critical issues that must be fixed before merging] + + #### High + - **[Issue Title]**: [Description of high-priority issues that should be fixed] + + #### Medium + - **[Issue Title]**: [Description of issues that should be addressed] + + #### Low + - **[Issue Title]**: [Description of minor issues or nice-to-have improvements] + ### 💡 Suggestions - - [List improvement recommendations] + - **[Suggestion Title]**: [Description of improvement recommendations] ### 🚀 Overall Assessment [Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT] @@ -169,4 +183,4 @@ jobs: console.log('Error details:', error); } env: - GITHUB_TOKEN: ${{ github.token }} \ No newline at end of file + GITHUB_TOKEN: ${{ github.token }} From d5860296fbea16c09f1c7b24eb48eebc9cf2280d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 13:41:44 -0700 Subject: [PATCH 098/102] feat: add debugging log method to peek first three --- core/nextEdit/NextEditPrefetchQueue.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 5cbb7ddc8..5123a841d 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -59,6 +59,11 @@ export class PrefetchQueue { !this.abortController.signal.aborted ) { const location = this.dequeueUnprocessed(); + console.log("processing:"); + console.log( + location?.range.start.line + " to " + location?.range.end.line, + ); + if (!location) break; try { @@ -70,12 +75,20 @@ export class PrefetchQueue { this.usingFullFileDiff, ); - if (!outcome) continue; + if (!outcome) { + console.log("outcome is undefined"); + continue; + } this.enqueueProcessed({ location, outcome, }); + + console.log( + "the length of processed queue after processing is:", + this.processedQueue.length, + ); } catch (error) { if (!this.abortController.signal.aborted) { // Handle error @@ -115,6 +128,16 @@ export class PrefetchQueue { return this.processedQueue[0]; } + peekThreeProcessed(): void { + const count = Math.min(3, this.processedQueue.length); + const firstThree = this.processedQueue.slice(0, count); + firstThree.forEach((item, index) => { + console.log( + `Item ${index + 1}: ${item.location.range.start.line} to ${item.location.range.end.line}`, + ); + }); + } + setPreetchLimit(limit: number): void { this.prefetchLimit = limit; } From e119ae1b6a61c8a060f849b37accae491b24092c Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 13:43:01 -0700 Subject: [PATCH 099/102] feat: peek for better logs --- .../vscode/src/autocomplete/completionProvider.ts | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index b81111e81..db420924c 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -261,18 +261,15 @@ export class ContinueCompletionProvider let outcome: AutocompleteOutcome | NextEditOutcome | undefined; - // console.log( - // "chain exists?", - // this.nextEditProvider.chainExists(), - // ", length:", - // this.nextEditProvider.getChainLength(), - // ", next regions queue:", - // this.nextEditProvider.getNextEditableRegionsInTheCurrentChainLength(), - // ); + // TODO: We can probably decide here if we want to do the jumping logic. + // If we aren't going to jump anyways, then we should be not be using the prefetch queue or the jump manager. + // It would simplify the logic quite substantially. // Determine why this method was triggered. const isJumping = this.jumpManager.isJumpInProgress(); const chainExists = this.nextEditProvider.chainExists(); + console.log("isJumping:", isJumping, "/ chainExists:", chainExists); + this.prefetchQueue.peekThreeProcessed(); if (isJumping && chainExists) { // Case 2: Jumping (chain exists, jump was taken) @@ -340,7 +337,6 @@ export class ContinueCompletionProvider if (isJumpSuggested) { // Store completion to be rendered after a jump. - // TODO: setCompletionAfterJump must have a 1-1 correspondence to the jump location. this.jumpManager.setCompletionAfterJump({ completionId: completionId, outcome, From db14da1cbe0f0fab2c7e2628ef1ef14ea24c0d25 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 13:54:35 -0700 Subject: [PATCH 100/102] fix: update test using the latest editDiffHistory --- .../nextEdit/templating/NextEditPromptEngine.vitest.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index 3df88e9f3..0b90ecda3 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -54,7 +54,7 @@ describe("NextEditPromptEngine", () => { { 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 @@", + editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"], editableRegionStartLine: 0, editableRegionEndLine: 3, userEdits: "Added constant a", @@ -91,8 +91,9 @@ describe("NextEditPromptEngine", () => { 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 + 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", }; @@ -106,7 +107,6 @@ describe("NextEditPromptEngine", () => { expect(result.prompt.content).toContain("### Context:"); expect(result.prompt.content).toContain("### User Edits:"); expect(result.prompt.content).toContain("### User Excerpts:"); - expect(result.prompt.content).toContain("```ts"); expect(result.userEdits).toBe(instinctCtx.editDiffHistory); expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN); @@ -223,7 +223,7 @@ describe("NextEditPromptEngine", () => { { 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 @@", + editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"], editableRegionStartLine: 0, editableRegionEndLine: 3, userEdits: "Added constant a", From 308f685a6ed69811f5465e6d6804b46060e6b6c6 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 12 Aug 2025 17:58:41 -0700 Subject: [PATCH 101/102] docs: clarify apiVersion usage in Azure YAML configuration (#7109) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs: clarify apiVersion usage in Azure YAML configuration - Add info box explaining apiVersion migration from JSON to YAML - Document env section parameters in YAML reference - Add Azure example showing proper apiVersion usage under env - Include link to complete YAML schema Fixes #7098 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude * docs: add apiVersion to Azure YAML examples - Add apiVersion parameter to chat model example - Add apiVersion parameter to embeddings model example - Shows proper placement under env section 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude * remove docs --------- Co-authored-by: Claude --- .../customize/model-providers/top-level/azure.mdx | 15 +++++++-------- docs/reference.mdx | 4 ++-- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/docs/customize/model-providers/top-level/azure.mdx b/docs/customize/model-providers/top-level/azure.mdx index c91404df9..722a2fd97 100644 --- a/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/customize/model-providers/top-level/azure.mdx @@ -5,12 +5,6 @@ slug: ../azure Azure AI Foundry is a cloud-based service that provides access to models from OpenAI, Mistral AI, and others, integrated with the security and enterprise features of the Microsoft Azure platform. To get started, create an Azure AI Foundry resource in the [Azure portal](https://portal.azure.com). - - -For details on OpenAI model setup, see [Azure OpenAI Service configuration](#azure-openai-service-configuration). - - - ## Chat model We recommend configuring **GPT-4o** as your chat model. @@ -27,6 +21,7 @@ We recommend configuring **GPT-4o** as your chat model. env: deployment: apiType: azure-foundry # Or "azure-openai" if using OpenAI models + apiVersion: 2023-07-01-preview # Azure API version ``` @@ -48,10 +43,13 @@ We recommend configuring **GPT-4o** as your chat model. ## Autocomplete model -We recommend configuring **Codestral** as your autocomplete model. +We recommend configuring **Codestral** as your autocomplete model. -**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint required for autocomplete functionality. To use Codestral for autocomplete, deploy it through **Azure Machine Learning Studio** instead, which provides the necessary `/v1/fim/completions` endpoint. + **Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint + required for autocomplete functionality. To use Codestral for autocomplete, + deploy it through **Azure Machine Learning Studio** instead, which provides + the necessary `/v1/fim/completions` endpoint. If you use Azure Machine Learning Studio to deploy Codestral: @@ -100,6 +98,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model. env: deployment: apiType: azure + apiVersion: 2023-07-01-preview ``` diff --git a/docs/reference.mdx b/docs/reference.mdx index c96bd7d96..06393cc2d 100644 --- a/docs/reference.mdx +++ b/docs/reference.mdx @@ -175,11 +175,11 @@ The `models` section defines the language models used in your configuration. Mod - `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. - - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for detailed information. Supported capabilities include: + - `tool_use`: Enables function/tool calling support (required for Agent mode) - `image_input`: Enables image upload and processing support - + Continue automatically detects these capabilities for most models, but you can override this when using custom deployments or if autodetection isn't working correctly. - `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. From 3606665992bbb9ac1a2fa6eb1d7976f5bad407e6 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Tue, 12 Aug 2025 18:25:01 -0700 Subject: [PATCH 102/102] feat: add more next edit endpoints to protocol (#7110) * feat: add endpoint handlers in core * feat: export interface * feat: update protocol to support more next edit endpoints * feat: add new next edit endpoints to passthrough * feat: support new next edit endpoints to jetbrains --- core/core.ts | 69 ++++++++++++++++++- core/nextEdit/NextEditPrefetchQueue.ts | 2 +- core/protocol/core.ts | 39 ++++++++++- core/protocol/passThrough.ts | 8 +++ .../constants/MessageTypes.kt | 8 +++ 5 files changed, 121 insertions(+), 5 deletions(-) diff --git a/core/core.ts b/core/core.ts index aa558736c..d52a51e05 100644 --- a/core/core.ts +++ b/core/core.ts @@ -76,6 +76,7 @@ import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; import { getUriPathBasename } from "./util/uri"; +import { PrefetchQueue } from "./nextEdit/NextEditPrefetchQueue"; const hasRulesFiles = (uris: string[]): boolean => { for (const uri of uris) { @@ -578,18 +579,80 @@ export class Core { // Next Edit on("nextEdit/predict", async (msg) => { const outcome = await this.nextEditProvider.provideInlineCompletionItems( - msg.data, + msg.data.input, undefined, - { withChain: false, usingFullFileDiff: true }, + { + withChain: msg.data.options?.withChain ?? false, + usingFullFileDiff: msg.data.options?.usingFullFileDiff ?? true, + }, ); - return outcome ? [outcome.completion, outcome.originalEditableRange] : []; + return outcome; + // ? [outcome.completion, outcome.originalEditableRange] }); on("nextEdit/accept", async (msg) => { + console.log("nextEdit/accept"); this.nextEditProvider.accept(msg.data.completionId); }); on("nextEdit/reject", async (msg) => { + console.log("nextEdit/reject"); this.nextEditProvider.reject(msg.data.completionId); }); + on("nextEdit/startChain", async (msg) => { + console.log("nextEdit/startChain"); + NextEditProvider.getInstance().startChain(); + return; + }); + + on("nextEdit/deleteChain", async (msg) => { + console.log("nextEdit/deleteChain"); + await NextEditProvider.getInstance().deleteChain(); + return; + }); + + on("nextEdit/isChainAlive", async (msg) => { + console.log("nextEdit/isChainAlive"); + return NextEditProvider.getInstance().chainExists(); + }); + + on("nextEdit/queue/getProcessedCount", async (msg) => { + console.log("nextEdit/queue/getProcessedCount"); + const queue = PrefetchQueue.getInstance(); + console.log(queue.processedCount); + return queue.processedCount; + }); + + on("nextEdit/queue/dequeueProcessed", async (msg) => { + console.log("nextEdit/queue/dequeueProcessed"); + const queue = PrefetchQueue.getInstance(); + return queue.dequeueProcessed() || null; + }); + + on("nextEdit/queue/processOne", async (msg) => { + console.log("nextEdit/queue/processOne"); + const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data; + const queue = PrefetchQueue.getInstance(); + + await queue.process({ + ...ctx, + recentlyVisitedRanges, + recentlyEditedRanges, + }); + return; + }); + + on("nextEdit/queue/clear", async (msg) => { + console.log("nextEdit/queue/clear"); + const queue = PrefetchQueue.getInstance(); + queue.clear(); + return; + }); + + on("nextEdit/queue/abort", async (msg) => { + console.log("nextEdit/queue/abort"); + const queue = PrefetchQueue.getInstance(); + queue.abort(); + return; + }); on("streamDiffLines", async (msg) => { const { config } = await this.configHandler.loadConfig(); diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 5123a841d..8e158d0fa 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -2,7 +2,7 @@ import { RangeInFile } from ".."; import { NextEditProvider } from "./NextEditProvider"; import { NextEditOutcome } from "./types"; -interface ProcessedItem { +export interface ProcessedItem { location: RangeInFile; outcome: NextEditOutcome; // Result from the model } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 258feaaa9..ced0fb546 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -48,6 +48,8 @@ import { ControlPlaneSessionInfo, } from "../control-plane/AuthTypes"; import { FreeTrialStatus } from "../control-plane/client"; +import { NextEditOutcome } from "../nextEdit/types"; +import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue"; export enum OnboardingModes { API_KEY = "API Key", @@ -153,9 +155,44 @@ export type ToCoreFromIdeOrWebviewProtocol = { "context/indexDocs": [{ reIndex: boolean }, void]; "autocomplete/cancel": [undefined, void]; "autocomplete/accept": [{ completionId: string }, void]; - "nextEdit/predict": [AutocompleteInput, string[]]; + "nextEdit/predict": [ + { + input: AutocompleteInput; + options?: { + withChain?: boolean; + usingFullFileDiff?: boolean; + }; + }, + NextEditOutcome | undefined, + ]; "nextEdit/reject": [{ completionId: string }, void]; "nextEdit/accept": [{ completionId: string }, void]; + "nextEdit/startChain": [undefined, void]; + "nextEdit/deleteChain": [undefined, void]; + "nextEdit/isChainAlive": [undefined, boolean]; + "nextEdit/queue/getProcessedCount": [undefined, number]; + "nextEdit/queue/dequeueProcessed": [undefined, ProcessedItem | null]; + "nextEdit/queue/processOne": [ + { + ctx: { + completionId: string; + manuallyPassFileContents?: string; + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + isUntitledFile: boolean; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + }; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + }, + void, + ]; + "nextEdit/queue/clear": [undefined, void]; + "nextEdit/queue/abort": [undefined, void]; "llm/complete": [ { prompt: string; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 967e0262e..7461e366e 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -40,6 +40,14 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "nextEdit/predict", "nextEdit/reject", "nextEdit/accept", + "nextEdit/startChain", + "nextEdit/deleteChain", + "nextEdit/isChainAlive", + "nextEdit/queue/getProcessedCount", + "nextEdit/queue/dequeueProcessed", + "nextEdit/queue/processOne", + "nextEdit/queue/clear", + "nextEdit/queue/abort", "tts/kill", "llm/complete", "llm/streamChat", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 1945bf546..e8eb4332f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -105,6 +105,14 @@ class MessageTypes { "nextEdit/predict", "nextEdit/reject", "nextEdit/accept", + "nextEdit/startChain", + "nextEdit/deleteChain", + "nextEdit/isChainAlive", + "nextEdit/queue/getProcessedCount", + "nextEdit/queue/dequeueProcessed", + "nextEdit/queue/processOne", + "nextEdit/queue/clear", + "nextEdit/queue/abort", "tts/kill", "llm/complete", "llm/streamChat",