From 509bb22fc23cb90c77c05317a332c82e55191000 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 17 Dec 2024 08:54:48 -0800 Subject: [PATCH 01/64] bump version --- 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 ce7338061..37183e9ab 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": "0.8.64", + "version": "0.8.65", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 8f18577169351785173cca4802b6a0f72a656714 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 20 Dec 2024 15:15:15 -0500 Subject: [PATCH 02/64] bump vscode version --- 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 37183e9ab..65bfdd730 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": "0.8.65", + "version": "0.8.66", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From cb138998d47abf98789d4df47960c0bcf024822a Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 20 Dec 2024 14:41:32 -0500 Subject: [PATCH 03/64] roll back openai-adapters for Azure --- core/llm/llms/Azure.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index 5b3ba4338..b2beae921 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -1,4 +1,5 @@ import { LLMOptions } from "../../index.js"; +import { LlmApiRequestType } from "../openaiTypeConverters.js"; import OpenAI from "./OpenAI.js"; @@ -9,6 +10,8 @@ class Azure extends OpenAI { return false; } + protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = []; + static defaultOptions: Partial = { apiVersion: "2024-02-15-preview", apiType: "azure", From d6c8c067c2066002188f63d44b5544c742537b30 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 20 Dec 2024 15:17:18 -0500 Subject: [PATCH 04/64] changelog --- .changes/extensions/vscode/0.8.66.md | 9 +++++++++ .changes/unreleased/Changed-20241213-091505.yaml | 4 ---- .changes/unreleased/Fixed-20241213-091454.yaml | 4 ---- .changes/unreleased/Fixed-20241213-091519.yaml | 4 ---- .changes/unreleased/Fixed-20241216-220802.yaml | 4 ---- .changes/unreleased/Fixed-20241216-220818.yaml | 4 ---- extensions/vscode/CHANGELOG.md | 3 ++- 7 files changed, 11 insertions(+), 21 deletions(-) create mode 100644 .changes/extensions/vscode/0.8.66.md delete mode 100644 .changes/unreleased/Changed-20241213-091505.yaml delete mode 100644 .changes/unreleased/Fixed-20241213-091454.yaml delete mode 100644 .changes/unreleased/Fixed-20241213-091519.yaml delete mode 100644 .changes/unreleased/Fixed-20241216-220802.yaml delete mode 100644 .changes/unreleased/Fixed-20241216-220818.yaml diff --git a/.changes/extensions/vscode/0.8.66.md b/.changes/extensions/vscode/0.8.66.md new file mode 100644 index 000000000..4a1930978 --- /dev/null +++ b/.changes/extensions/vscode/0.8.66.md @@ -0,0 +1,9 @@ +## 0.8.66 - 2024-12-20 +### Changed +* Improved autocomplete in untitled files +### Fixed +* Display more mid-line completions +* Restored syntax highlighting +* Fix tool use bug for models that don't support tools +* Autodetect mistral API key type +* Fixes Azure OpenAI regressions diff --git a/.changes/unreleased/Changed-20241213-091505.yaml b/.changes/unreleased/Changed-20241213-091505.yaml deleted file mode 100644 index 0ce6136ae..000000000 --- a/.changes/unreleased/Changed-20241213-091505.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Changed -body: Improved autocomplete in untitled files -time: 2024-12-13T09:15:05.552877-08:00 diff --git a/.changes/unreleased/Fixed-20241213-091454.yaml b/.changes/unreleased/Fixed-20241213-091454.yaml deleted file mode 100644 index fb8d92584..000000000 --- a/.changes/unreleased/Fixed-20241213-091454.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Fixed -body: Display more mid-line completions -time: 2024-12-13T09:14:54.808683-08:00 diff --git a/.changes/unreleased/Fixed-20241213-091519.yaml b/.changes/unreleased/Fixed-20241213-091519.yaml deleted file mode 100644 index 84a193224..000000000 --- a/.changes/unreleased/Fixed-20241213-091519.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Fixed -body: Restored syntax highlighting -time: 2024-12-13T09:15:19.485189-08:00 diff --git a/.changes/unreleased/Fixed-20241216-220802.yaml b/.changes/unreleased/Fixed-20241216-220802.yaml deleted file mode 100644 index db8c0108f..000000000 --- a/.changes/unreleased/Fixed-20241216-220802.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Fixed -body: Fix tool use bug for models that don't support tools -time: 2024-12-16T22:08:02.399772-08:00 diff --git a/.changes/unreleased/Fixed-20241216-220818.yaml b/.changes/unreleased/Fixed-20241216-220818.yaml deleted file mode 100644 index b8e059181..000000000 --- a/.changes/unreleased/Fixed-20241216-220818.yaml +++ /dev/null @@ -1,4 +0,0 @@ -project: extensions/vscode -kind: Fixed -body: Autodetect mistral API key type -time: 2024-12-16T22:08:18.369444-08:00 diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index 4ad93caf6..88f9906e3 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -5,7 +5,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), and is generated by [Changie](https://github.com/miniscruff/changie). -Pre-release Changes +## 0.8.66 - 2024-12-20 ### Changed * Improved autocomplete in untitled files ### Fixed @@ -13,6 +13,7 @@ Pre-release Changes * Restored syntax highlighting * Fix tool use bug for models that don't support tools * Autodetect mistral API key type +* Fixes Azure OpenAI regressions ## 0.8.62 - 2024-12-10 ### Added From 27f9278d4005ab9278ac68b77bdb287141e8309e Mon Sep 17 00:00:00 2001 From: henry Date: Sat, 21 Dec 2024 15:22:36 -0500 Subject: [PATCH 05/64] prompt engineering changes --- core/util/chatDescriber.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 20eab20b7..a10edbe72 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -8,7 +8,7 @@ import type { IMessenger } from "../protocol/messenger"; export class ChatDescriber { static maxTokens = 12; static prompt: string | undefined = - "Given the following... please reply with a short summary that is 4-8 words in length, you should summarize what the user is asking for OR what the user is trying to accomplish. You should only respond with the summary, no additional text or explanation, you don't need ending punctuation.\n\n"; + "Given the following... please reply with a title for the chat that is 3-4 words in length, all words used should be directly related to the content of the chat, avoid using verbs unless they are directly related to the content of the chat, no additional text or explanation, you don't need ending punctuation.\n\n"; static messenger: IMessenger; static async describe( From f60a39e944122f19337a19759bacebc3639ef69a Mon Sep 17 00:00:00 2001 From: Hieu Pham Date: Sat, 21 Dec 2024 12:24:15 -0800 Subject: [PATCH 06/64] Fix embedding provider not respecting batch size --- core/llm/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/llm/index.ts b/core/llm/index.ts index fbea69104..d789f724e 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -809,12 +809,12 @@ export abstract class BaseLLM implements ILLM { if (this.shouldUseOpenAIAdapter("embed") && this.openaiAdapter) { const result = await this.openaiAdapter.embed({ model: this.model, - input: chunks, + input: batch, }); - return result.data.map((chunk) => chunk.embedding); + return result.data.map((batch) => batch.embedding); } - return await this._embed(chunks); + return await this._embed(batch); }, ); From 4fdf5d5bc358f91f8a6569beb685bca368719603 Mon Sep 17 00:00:00 2001 From: Hieu Pham Date: Sat, 21 Dec 2024 12:58:35 -0800 Subject: [PATCH 07/64] Remove unnecessary change --- core/llm/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/index.ts b/core/llm/index.ts index d789f724e..5c0253e86 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -811,7 +811,7 @@ export abstract class BaseLLM implements ILLM { model: this.model, input: batch, }); - return result.data.map((batch) => batch.embedding); + return result.data.map((chunk) => chunk.embedding); } return await this._embed(batch); From 48ea7ca10a4d918a92e5591e7e357980e3a5b5b3 Mon Sep 17 00:00:00 2001 From: Alexey Palazhchenko Date: Sun, 22 Dec 2024 17:48:52 +0400 Subject: [PATCH 08/64] Fix model names for Ollama --- docs/docs/chat/model-setup.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index a5668786b..478d5740c 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -77,7 +77,7 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your { "title": "Llama 3.1 405B", "provider": "ollama", - "model": "llama3.1-405b" + "model": "llama3.1:405b" } ] ``` @@ -141,7 +141,7 @@ If your local machine can run an 8B parameter model, then we recommend running L { "title": "Llama 3.1 8B", "provider": "ollama", - "model": "llama3.1-8b" + "model": "llama3.1:8b" } ] ``` From 267961f5b67f8f4529917fc43ebc1df88db92b51 Mon Sep 17 00:00:00 2001 From: Test Date: Sun, 22 Dec 2024 14:05:28 -0600 Subject: [PATCH 09/64] fix: build issues with jetbrains --- binary/build.js | 23 +++++++++++++---------- binary/package.json | 3 +-- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/binary/build.js b/binary/build.js index 5d7b6061f..53f7c8e0c 100644 --- a/binary/build.js +++ b/binary/build.js @@ -37,16 +37,17 @@ const assetBackups = [ "node_modules/win-ca/lib/crypt32-x64.node.bak", ]; -let esbuildOnly = false; -for (let i = 2; i < process.argv.length; i++) { - if (process.argv[i] === "--esbuild-only") { - esbuildOnly = true; - } - if (process.argv[i - 1] === "--target") { - targets = [process.argv[i]]; - } -} +const args = process.argv.slice(2); +const includeSourcemaps = args.includes("--with-sourcemaps"); +// Note: Currently this flag is not functioning due to issues with sqlite bindings +// `Error: Could not locate the bindings file. Tried ...` +const esbuildOnly = args.includes("--esbuild-only"); + +const targetIndex = args.indexOf("--target"); +if (targetIndex !== -1) { + targets = [args[targetIndex + 1]]; +} const targetToLanceDb = { "darwin-arm64": "@lancedb/vectordb-darwin-arm64", "darwin-x64": "@lancedb/vectordb-darwin-x64", @@ -208,7 +209,9 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { ], format: "cjs", platform: "node", - sourcemap: true, + sourcemap: includeSourcemaps, + minify: true, + treeShaking: true, loader: { // eslint-disable-next-line @typescript-eslint/naming-convention ".node": "file", diff --git a/binary/package.json b/binary/package.json index 62a28b741..671612630 100644 --- a/binary/package.json +++ b/binary/package.json @@ -23,8 +23,7 @@ "scripts": { "test": "jest", "build": "node build.js", - "build:dev": "tsc", - "esbuild": "node build.js --esbuild-only" + "build:dev": "node build.js --with-sourcemaps" }, "license": "Apache-2.0", "devDependencies": { From fe9e6ed61c4fcc0c9949df0949a81a7c8cb31874 Mon Sep 17 00:00:00 2001 From: Test Date: Sun, 22 Dec 2024 19:51:07 -0600 Subject: [PATCH 10/64] Update build.js --- binary/build.js | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/binary/build.js b/binary/build.js index 53f7c8e0c..e91a3b6b3 100644 --- a/binary/build.js +++ b/binary/build.js @@ -37,17 +37,16 @@ const assetBackups = [ "node_modules/win-ca/lib/crypt32-x64.node.bak", ]; -const args = process.argv.slice(2); -const includeSourcemaps = args.includes("--with-sourcemaps"); - -// Note: Currently this flag is not functioning due to issues with sqlite bindings -// `Error: Could not locate the bindings file. Tried ...` -const esbuildOnly = args.includes("--esbuild-only"); - -const targetIndex = args.indexOf("--target"); -if (targetIndex !== -1) { - targets = [args[targetIndex + 1]]; +let esbuildOnly = false; +for (let i = 2; i < process.argv.length; i++) { + if (process.argv[i] === "--esbuild-only") { + esbuildOnly = true; + } + if (process.argv[i - 1] === "--target") { + targets = [process.argv[i]]; + } } + const targetToLanceDb = { "darwin-arm64": "@lancedb/vectordb-darwin-arm64", "darwin-x64": "@lancedb/vectordb-darwin-x64", @@ -209,7 +208,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { ], format: "cjs", platform: "node", - sourcemap: includeSourcemaps, + sourcemap: true, minify: true, treeShaking: true, loader: { From a045074e0bbc0620a9013d94dcfc2789ed889a5e Mon Sep 17 00:00:00 2001 From: Test Date: Sun, 22 Dec 2024 19:53:20 -0600 Subject: [PATCH 11/64] Update package.json --- binary/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/binary/package.json b/binary/package.json index 671612630..426127922 100644 --- a/binary/package.json +++ b/binary/package.json @@ -23,7 +23,7 @@ "scripts": { "test": "jest", "build": "node build.js", - "build:dev": "node build.js --with-sourcemaps" + "build:darwin-x64": "node build.js --os darwin-x64" }, "license": "Apache-2.0", "devDependencies": { From b0d382277dc07768056a5ebffc948e92fe151850 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 22 Dec 2024 22:18:29 -0500 Subject: [PATCH 12/64] new tests for edge cases --- core/edit/lazy/deterministic.test.ts | 8 ++ core/edit/lazy/deterministic.ts | 110 ++++++++++++++++-- core/edit/lazy/findInAst.ts | 6 +- .../calculator-class-neglected.js.diff | 103 ++++++++++++++++ .../calculator-only-method.js.diff | 99 ++++++++++++++++ 5 files changed, 315 insertions(+), 11 deletions(-) create mode 100644 core/edit/lazy/test-examples/calculator-class-neglected.js.diff create mode 100644 core/edit/lazy/test-examples/calculator-only-method.js.diff diff --git a/core/edit/lazy/deterministic.test.ts b/core/edit/lazy/deterministic.test.ts index 997c24c3a..7590e5025 100644 --- a/core/edit/lazy/deterministic.test.ts +++ b/core/edit/lazy/deterministic.test.ts @@ -158,4 +158,12 @@ describe("deterministicApplyLazyEdit(", () => { test("should acknowledge jsx_expression lazy comments", async () => { await expectDiff("migration-page.tsx"); }); + + test.skip("should handle case where surrounding class is neglected, with lazy block surrounding", async () => { + await expectDiff("calculator-class-neglected.js"); + }); + + test("should handle case where surrounding class is neglected, without lazy block surrounding", async () => { + await expectDiff("calculator-only-method.js"); + }); }); diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index 564656d23..99d5c9a01 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -102,6 +102,24 @@ function shouldRejectDiff(diff: DiffLine[]): boolean { return false; } +function nodeSurroundedInLazyBlocks( + parser: Parser, + + file: string, + filename: string, +): { newTree: Parser.Tree; newFile: string } | undefined { + const ext = path.extname(filename).slice(1); + const language = LANGUAGES[ext]; + if (language) { + const newFile = `${language.singleLineComment} ... existing code ...\n\n${file}\n\n${language.singleLineComment} ... existing code...`; + const newTree = parser.parse(newFile); + + return { newTree, newFile }; + } + + return undefined; +} + // TODO: If we don't have high confidence, return undefined to fall back to slower methods export async function deterministicApplyLazyEdit( oldFile: string, @@ -115,6 +133,7 @@ export async function deterministicApplyLazyEdit( const oldTree = parser.parse(oldFile); let newTree = parser.parse(newLazyFile); + let reconstructedNewFile: string | undefined = undefined; // If there is no lazy block anywhere, we add our own to the outsides // so that large chunks of the file don't get removed @@ -125,24 +144,51 @@ export async function deterministicApplyLazyEdit( ); if (firstSimilarNode?.parent?.equals(oldTree.rootNode)) { // If so, we tack lazy blocks to start and end, and run the usual algorithm - const ext = path.extname(filename).slice(1); - const language = LANGUAGES[ext]; - if (language) { - newLazyFile = `${language.singleLineComment} ... existing code ...\n\n${newLazyFile}\n\n${language.singleLineComment} ... existing code...`; - newTree = parser.parse(newLazyFile); + const result = nodeSurroundedInLazyBlocks(parser, newLazyFile, filename); + if (result) { + newLazyFile = result.newFile; + newTree = result.newTree; } } else { // If not, we need to recursively search for the nodes that are being rewritten, // and we apply a slightly different algorithm - return undefined; // TODO + const newCodeNumLines = newTree.rootNode.text.split("\n").length; + const matchingNode = findInAst( + oldTree.rootNode, + (node) => programNodeIsSimilar(newTree.rootNode, node), + // This isn't perfect—we want the length of the matching code in the old tree + // and the new version could have more lines, or fewer. But should work a lot. + (node) => node.text.split("\n").length >= newCodeNumLines, + ); + if (matchingNode) { + // Now that we've successfully matched the node from the old tree, + // we create the full new lazy file + const startIndex = matchingNode.startIndex; + const endIndex = matchingNode.endIndex; + const oldText = oldTree.rootNode.text; + reconstructedNewFile = + oldText.slice(0, startIndex) + + newTree.rootNode.text + + oldText.slice(endIndex); + } else { + console.warn("No matching node found for lazy block"); + return []; + } } } - const replacements: AstReplacements = []; - findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements); + if (!reconstructedNewFile) { + const replacements: AstReplacements = []; + findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements); - const newFullFile = reconstructNewFile(oldFile, newLazyFile, replacements); - const diff = myersDiff(oldFile, newFullFile); + reconstructedNewFile = reconstructNewFile( + oldFile, + newLazyFile, + replacements, + ); + } + + const diff = myersDiff(oldFile, reconstructedNewFile); // If the diff is too messy and seems likely borked, we fall back to LLM strategy if (shouldRejectDiff(diff)) { @@ -179,6 +225,50 @@ function stringsWithinLevDistThreshold( return dist / Math.min(a.length, b.length) <= threshold; } +function programNodeIsSimilar( + programNode: Parser.SyntaxNode, + otherNode: Parser.SyntaxNode, +): boolean { + // Check purely based on whether they are similar strings + const newLines = programNode.text.split("\n"); + const oldLines = otherNode.text.split("\n"); + + // Check that there is a line that matches the start of the old range + const oldFirstLine = oldLines[0].trim(); + let matchForOldFirstLine = -1; + for (let i = 0; i < newLines.length; i++) { + if (newLines[i].trim() === oldFirstLine) { + matchForOldFirstLine = i; + break; + } + } + + if (matchForOldFirstLine < 0) { + return false; + } + + // Check that the last lines match each other + const oldLastLine = oldLines[oldLines.length - 1].trim(); + const newLastLine = newLines[newLines.length - 1].trim(); + if (oldLastLine !== newLastLine) { + return false; + } + + // Check that the number of matching lines is at least half of the shorter length + let matchingLines = 0; + for (let i = 0; i < Math.min(newLines.length, oldLines.length); i++) { + if (oldLines[i].trim() === newLines[matchForOldFirstLine + i].trim()) { + matchingLines += 1; + } + } + + if (matchingLines >= Math.max(newLines.length, oldLines.length) / 2) { + return true; + } + + return false; +} + /** * Determine whether two nodes are similar * @param a diff --git a/core/edit/lazy/findInAst.ts b/core/edit/lazy/findInAst.ts index 9f47355b8..93809ea20 100644 --- a/core/edit/lazy/findInAst.ts +++ b/core/edit/lazy/findInAst.ts @@ -3,6 +3,7 @@ import Parser from "web-tree-sitter"; export function findInAst( node: Parser.SyntaxNode, criterion: (node: Parser.SyntaxNode) => boolean, + shouldRecurse: (node: Parser.SyntaxNode) => boolean = () => true, ): Parser.SyntaxNode | null { const stack = [node]; while (stack.length > 0) { @@ -10,7 +11,10 @@ export function findInAst( if (criterion(node)) { return node; } - stack.push(...node.children); + + if (shouldRecurse(node)) { + stack.push(...node.children); + } } return null; } diff --git a/core/edit/lazy/test-examples/calculator-class-neglected.js.diff b/core/edit/lazy/test-examples/calculator-class-neglected.js.diff new file mode 100644 index 000000000..eb6dcc285 --- /dev/null +++ b/core/edit/lazy/test-examples/calculator-class-neglected.js.diff @@ -0,0 +1,103 @@ +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +--- + +// ... existing code ... + + /** + * Divides the current result by the given number + * @param {number} number - The number to divide by + * @throws {Error} If attempting to divide by zero + * @returns {Calculator} The calculator instance for chaining + */ + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + +// ... existing code ... + +--- + +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + ++ /** ++ * Divides the current result by the given number ++ * @param {number} number - The number to divide by ++ * @throws {Error} If attempting to divide by zero ++ * @returns {Calculator} The calculator instance for chaining ++ */ + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} \ No newline at end of file diff --git a/core/edit/lazy/test-examples/calculator-only-method.js.diff b/core/edit/lazy/test-examples/calculator-only-method.js.diff new file mode 100644 index 000000000..6f69d0142 --- /dev/null +++ b/core/edit/lazy/test-examples/calculator-only-method.js.diff @@ -0,0 +1,99 @@ +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +--- + + /** + * Divides the current result by the given number + * @param {number} number - The number to divide by + * @throws {Error} If attempting to divide by zero + * @returns {Calculator} The calculator instance for chaining + */ + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + +--- + +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + ++ /** ++ * Divides the current result by the given number ++ * @param {number} number - The number to divide by ++ * @throws {Error} If attempting to divide by zero ++ * @returns {Calculator} The calculator instance for chaining ++ */ + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} \ No newline at end of file From ae8830fa1b59412a27f3f10472defb7358b5c63b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 23 Dec 2024 08:54:19 -0800 Subject: [PATCH 13/64] improv: keyboard shortcut descriptions --- gui/src/pages/More/KeyboardShortcuts.tsx | 25 ++++++++++++------------ 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/gui/src/pages/More/KeyboardShortcuts.tsx b/gui/src/pages/More/KeyboardShortcuts.tsx index 2c8159ff2..26bee125a 100644 --- a/gui/src/pages/More/KeyboardShortcuts.tsx +++ b/gui/src/pages/More/KeyboardShortcuts.tsx @@ -78,18 +78,20 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ { mac: "⌘ L", windows: "⌃ L", - description: "Select Code + New Session", + description: + "Start New Session / Start New Session With Selected Code / Toggle Continue Sidebar", + }, + { + mac: "⌘ ⇧ L", + windows: "⌃ ⇧ L", + description: + "Add Selected Code To Current Session / Toggle Continue Sidebar", }, { mac: "⌘ I", windows: "⌃ I", description: "Edit highlighted code", }, - { - mac: "⌘ ⇧ L", - windows: "⌃ ⇧ L", - description: "Select Code", - }, { mac: "⌘ ⇧ ⏎", windows: "⌃ ⇧ ⏎", @@ -110,11 +112,6 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ windows: "Alt ⌃ N", description: "Reject Top Change in Diff", }, - { - mac: "⌥ ⌘ L", - windows: "Alt ⌃ L", - description: "Toggle Continue Sidebar", - }, { mac: "⌘ ⇧ R", windows: "⌃ ⇧ R", @@ -146,12 +143,14 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [ { mac: "⌘ J", windows: "⌃ J", - description: "Select Code + New Session", + description: + "Start New Session / Start New Session With Selected Code / Toggle Continue Sidebar", }, { mac: "⌘ ⇧ J", windows: "⌃ ⇧ J", - description: "Select Code", + description: + "Add Selected Code To Current Session / Toggle Continue Sidebar", }, { mac: "⌘ I", From 9f77c9626d21befe911707f8b50344ee091f84ae Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 23 Dec 2024 08:56:40 -0800 Subject: [PATCH 14/64] improv: spacing --- gui/src/pages/More/KeyboardShortcuts.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/pages/More/KeyboardShortcuts.tsx b/gui/src/pages/More/KeyboardShortcuts.tsx index 26bee125a..2e8123cec 100644 --- a/gui/src/pages/More/KeyboardShortcuts.tsx +++ b/gui/src/pages/More/KeyboardShortcuts.tsx @@ -63,7 +63,7 @@ interface KeyboardShortcutProps { function KeyboardShortcut(props: KeyboardShortcutProps) { const shortcut = getPlatform() === "mac" ? props.mac : props.windows; return ( -
+
{props.description}
{shortcut.split(" ").map((key, i) => { From f5e7f9ce71d4c34e8ee72b0d78fe89c68d0b7170 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 23 Dec 2024 11:01:35 -0600 Subject: [PATCH 15/64] feat: use meyers diff after initial edit/apply --- .../filtering/streamTransforms/lineStream.ts | 13 +++ core/edit/lazy/streamLazyApply.ts | 7 +- core/edit/streamDiffLines.ts | 14 +-- core/util/ideUtils.ts | 5 +- .../vscode/src/diff/vertical/handler.ts | 95 +++++++++++++++++-- .../vscode/src/extension/VsCodeMessenger.ts | 10 +- .../StepContainerPreToolbar.tsx | 8 +- .../markdown/StyledMarkdownPreview.tsx | 6 +- 8 files changed, 128 insertions(+), 30 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 851dea88a..edad1febc 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -316,6 +316,19 @@ export async function* skipLines(stream: LineStream): LineStream { } } +/** + * Handles cases where original lines have a trailing whitespace, but new lines do not. + * @param {LineStream} stream - The input stream of lines. + * @yields {string} Filtered lines that are stripped of trailing whitespace + */ +export async function* removeTrailingWhitespace( + stream: LineStream, +): LineStream { + for await (const line of stream) { + yield line.trimEnd(); + } +} + /** * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. * diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index a5c85ee4d..982e263e8 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -1,6 +1,7 @@ import { filterLeadingAndTrailingNewLineInsertion, filterLeadingNewline, + removeTrailingWhitespace, stopAtLines, } from "../../autocomplete/filtering/streamTransforms/lineStream.js"; import { streamDiff } from "../../diff/streamDiff.js"; @@ -23,7 +24,10 @@ export async function* streamLazyApply( } const promptMessages = promptFactory(oldCode, filename, newCode); - const lazyCompletion = llm.streamChat(promptMessages, new AbortController().signal); + const lazyCompletion = llm.streamChat( + promptMessages, + new AbortController().signal, + ); // Do find and replace over the lazy edit response async function* replacementFunction( @@ -46,6 +50,7 @@ export async function* streamLazyApply( // lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines); lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]); lazyCompletionLines = filterLeadingNewline(lazyCompletionLines); + lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines); // Fill in unchanged code let lines = streamFillUnchangedCode( diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index d0a6154c1..1d1202b91 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -1,16 +1,17 @@ +import { ChatMessage, DiffLine, ILLM, Prediction } from "../"; import { filterCodeBlockLines, filterEnglishLinesAtEnd, filterEnglishLinesAtStart, filterLeadingAndTrailingNewLineInsertion, + removeTrailingWhitespace, skipLines, stopAtLines, -} from "../autocomplete/filtering/streamTransforms/lineStream.js"; -import { streamDiff } from "../diff/streamDiff.js"; -import { streamLines } from "../diff/util.js"; -import { ChatMessage, DiffLine, ILLM, Prediction } from "../index.js"; -import { gptEditPrompt } from "../llm/templates/edit.js"; -import { Telemetry } from "../util/posthog.js"; +} from "../autocomplete/filtering/streamTransforms/lineStream"; +import { streamDiff } from "../diff/streamDiff"; +import { streamLines } from "../diff/util"; +import { gptEditPrompt } from "../llm/templates/edit"; +import { Telemetry } from "../util/posthog"; function constructPrompt( prefix: string, @@ -110,6 +111,7 @@ export async function* streamDiffLines( lines = filterCodeBlockLines(lines); lines = stopAtLines(lines, () => {}); lines = skipLines(lines); + lines = removeTrailingWhitespace(lines); if (inept) { // lines = fixCodeLlamaFirstLineIndentation(lines); lines = filterEnglishLinesAtEnd(lines); diff --git a/core/util/ideUtils.ts b/core/util/ideUtils.ts index 2dbf20147..93cb5008d 100644 --- a/core/util/ideUtils.ts +++ b/core/util/ideUtils.ts @@ -1,4 +1,5 @@ import { IDE } from ".."; + import { joinPathsToUri, pathToUriPathSegment } from "./uri"; /* @@ -34,17 +35,17 @@ export async function inferResolvedUriFromRelativePath( dirCandidates?: string[], ): Promise { const dirs = dirCandidates ?? (await ide.getWorkspaceDirs()); - console.log(path, dirs); + if (dirs.length === 0) { throw new Error("inferResolvedUriFromRelativePath: no dirs provided"); } + const segments = pathToUriPathSegment(path).split("/"); // Generate all possible suffixes from shortest to longest const suffixes: string[] = []; for (let i = segments.length - 1; i >= 0; i--) { suffixes.push(segments.slice(i).join("/")); } - console.log(suffixes); // For each suffix, try to find a unique matching directory for (const suffix of suffixes) { diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 024aea2d2..a99c9c1c3 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -1,3 +1,5 @@ +import { myersDiff } from "core/diff/myers"; +import * as URI from "uri-js"; import * as vscode from "vscode"; import { @@ -10,7 +12,6 @@ import { import type { VerticalDiffCodeLens } from "./manager"; import type { ApplyState, DiffLine } from "core"; -import * as URI from "uri-js"; export interface VerticalDiffHandlerOptions { input?: string; @@ -249,11 +250,7 @@ export class VerticalDiffHandler implements vscode.Disposable { ? this.redDecorationManager.getRanges() : this.greenDecorationManager.getRanges(); - this.redDecorationManager.clear(); - this.greenDecorationManager.clear(); - this.clearIndexLineDecorations(); - - this.editorToVerticalDiffCodeLens.delete(this.fileUri); + this.clearDecorations(); await this.editor.edit( (editBuilder) => { @@ -360,9 +357,8 @@ export class VerticalDiffHandler implements vscode.Disposable { // Clear deletion buffer await this.insertDeletionBuffer(); - this.clearIndexLineDecorations(); - this.refreshCodeLens(); + this.reapplyWithMeyersDiff(diffLines); this.options.onStatusUpdate( "done", @@ -469,4 +465,87 @@ export class VerticalDiffHandler implements vscode.Disposable { const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.fileUri); return diffBlocks !== undefined && diffBlocks.length > 0; } + + clearDecorations() { + this.redDecorationManager.clear(); + this.greenDecorationManager.clear(); + this.clearIndexLineDecorations(); + this.editorToVerticalDiffCodeLens.delete(this.fileUri); + this.refreshCodeLens(); + } + + /** + * This method is used to apply diff decorations after the intiial stream. + * This is to handle scenarios where we miscalculate the original diff blocks, + * and decide to follow up with a deterministic algorithm like Meyers Diff once + * we have received all of the diff lines. + */ + async reapplyWithMeyersDiff(diffLines: DiffLine[]) { + this.clearDecorations(); + + // First, get our old/new file content based on the diff lines + const oldFileContent = diffLines + .filter((line) => line.type === "same" || line.type === "old") + .map((line) => line.line) + .join("\n"); + + const newFileContent = diffLines + .filter((line) => line.type === "same" || line.type === "new") + .map((line) => line.line) + .join("\n"); + + const diffs = myersDiff(oldFileContent, newFileContent); + + const meyersDiffLines = diffs.map((diff) => diff.line).join("\n"); + console.log({ newFileContent }); + + // Then, we overwrite the potentially miscalcualted diff blocks with our Meyers Diff + const fullRange = new vscode.Range( + this.editor.document.positionAt(0), + this.editor.document.positionAt(this.editor.document.getText().length), + ); + + await this.editor.edit((editBuilder) => { + editBuilder.replace(fullRange, meyersDiffLines); + }); + + let currentBlock = { + start: 0, + numRed: 0, + numGreen: 0, + }; + + const blocks: VerticalDiffCodeLens[] = []; + + // Lastly, we apply decorations + diffs.forEach((diff, index) => { + if (diff.type === "old") { + this.redDecorationManager.addLine(index); + currentBlock.numRed++; + } else if (diff.type === "new") { + this.greenDecorationManager.addLine(index); + currentBlock.numGreen++; + } else if ( + diff.type === "same" && + (currentBlock.numRed > 0 || currentBlock.numGreen > 0) + ) { + blocks.push({ + ...currentBlock, + start: index - currentBlock.numRed - currentBlock.numGreen, + }); + currentBlock = { + start: index + 1, + numRed: 0, + numGreen: 0, + }; + } + }); + + if (currentBlock.numRed > 0 || currentBlock.numGreen > 0) { + blocks.push(currentBlock); + } + + this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks); + this.refreshCodeLens(); + } } diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index d8b240034..d562fdb29 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -9,25 +9,25 @@ import { import { ToWebviewFromCoreProtocol } from "core/protocol/coreWebview"; import { ToIdeFromWebviewOrCoreProtocol } from "core/protocol/ide"; import { ToIdeFromCoreProtocol } from "core/protocol/ideCore"; +import { InProcessMessenger, Message } from "core/protocol/messenger"; import { CORE_TO_WEBVIEW_PASS_THROUGH, WEBVIEW_TO_CORE_PASS_THROUGH, } from "core/protocol/passThrough"; -import { InProcessMessenger, Message } from "core/protocol/messenger"; +import { stripImages } from "core/util/messageContent"; +import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; -import { stripImages } from "core/util/messageContent"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { getControlPlaneSessionInfo, WorkOsAuthProvider, } from "../stubs/WorkOsAuthProvider"; +import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { getUriPathBasename } from "core/util/uri"; -import { showTutorial } from "../util/tutorial"; /** * A shared messenger class between Core and Webview @@ -134,7 +134,7 @@ export class VsCodeMessenger { status: "streaming", fileContent: data.text, }); - console.log("applyToFile", data); + if (data.filepath) { const fileExists = await this.ide.fileExists(data.filepath); if (!fileExists) { diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index d0bd7caa6..c6a0d58f0 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -22,9 +22,9 @@ import { import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; const TopDiv = styled.div` - outline: 1px solid rgba(153, 153, 152); + outline: 0.5px solid rgba(153, 153, 152); outline-offset: -0.5px; - border-radius: ${defaultBorderRadius}; + border-radius: 2.5px; margin-bottom: 8px !important; background-color: ${vscEditorBackground}; min-width: 0; @@ -93,12 +93,12 @@ export default function StepContainerPreToolbar( if (!defaultModel) { return; } - console.log(props.relativeFilepath); + const fileUri = await inferResolvedUriFromRelativePath( props.relativeFilepath, ideMessenger.ide, ); - console.log(fileUri); + ideMessenger.post("applyToFile", { streamId: streamIdRef.current, filepath: fileUri, diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 49eec1d81..a6eb2c569 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,5 +1,5 @@ import { ctxItemToRifWithContents } from "core/commands/util"; -import { memo, useContext, useEffect, useMemo, useRef } from "react"; +import { memo, useEffect, useMemo } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -26,7 +26,6 @@ import { patchNestedMarkdown } from "./utils/patchNestedMarkdown"; import { useAppSelector } from "../../redux/hooks"; import { fixDoubleDollarNewLineLatex } from "./utils/fixDoubleDollarLatex"; import { selectUIConfig } from "../../redux/slices/configSlice"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; import { ToolTip } from "../gui/Tooltip"; import { v4 as uuidv4 } from "uuid"; @@ -43,8 +42,7 @@ const StyledMarkdown = styled.div<{ overflow-x: scroll; overflow-y: hidden; - margin: 10px 0; - padding: 6px 8px; + padding: 16px 8px; } code { From 9d03b370817a704565328d7d15d3a4078118a436 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 23 Dec 2024 09:13:44 -0800 Subject: [PATCH 16/64] improv: order --- gui/src/pages/More/KeyboardShortcuts.tsx | 123 ++++++++++++----------- 1 file changed, 64 insertions(+), 59 deletions(-) diff --git a/gui/src/pages/More/KeyboardShortcuts.tsx b/gui/src/pages/More/KeyboardShortcuts.tsx index 2e8123cec..085c8e515 100644 --- a/gui/src/pages/More/KeyboardShortcuts.tsx +++ b/gui/src/pages/More/KeyboardShortcuts.tsx @@ -75,12 +75,32 @@ function KeyboardShortcut(props: KeyboardShortcutProps) { } const vscodeShortcuts: KeyboardShortcutProps[] = [ + { + mac: "⌘ '", + windows: "⌃ '", + description: "Toggle Selected Model", + }, + { + mac: "⌘ I", + windows: "⌃ I", + description: "Edit highlighted code", + }, { mac: "⌘ L", windows: "⌃ L", description: "Start New Session / Start New Session With Selected Code / Toggle Continue Sidebar", }, + { + mac: "⌘ ⌫", + windows: "⌃ ⌫", + description: "Cancel response", + }, + { + mac: "⌘ ⇧ I", + windows: "⌃ ⇧ I", + description: "Toggle inline edit focus", + }, { mac: "⌘ ⇧ L", windows: "⌃ ⇧ L", @@ -88,14 +108,9 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ "Add Selected Code To Current Session / Toggle Continue Sidebar", }, { - mac: "⌘ I", - windows: "⌃ I", - description: "Edit highlighted code", - }, - { - mac: "⌘ ⇧ ⏎", - windows: "⌃ ⇧ ⏎", - description: "Accept Diff", + mac: "⌘ ⇧ R", + windows: "⌃ ⇧ R", + description: "Debug Terminal", }, { mac: "⌘ ⇧ ⌫", @@ -103,9 +118,9 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ description: "Reject Diff", }, { - mac: "⌥ ⌘ Y", - windows: "Alt ⌃ Y", - description: "Accept Top Change in Diff", + mac: "⌘ ⇧ ⏎", + windows: "⌃ ⇧ ⏎", + description: "Accept Diff", }, { mac: "⌥ ⌘ N", @@ -113,9 +128,38 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ description: "Reject Top Change in Diff", }, { - mac: "⌘ ⇧ R", - windows: "⌃ ⇧ R", - description: "Debug Terminal", + mac: "⌥ ⌘ Y", + windows: "Alt ⌃ Y", + description: "Accept Top Change in Diff", + }, + { + mac: "⌘ K ⌘ A", + windows: "⌃ K ⌃ A", + description: "Toggle Autocomplete Enabled", + }, + { + mac: "⌘ K ⌘ M", + windows: "⌃ K ⌃ M", + description: "Toggle Full Screen", + }, +]; + +const jetbrainsShortcuts: KeyboardShortcutProps[] = [ + { + mac: "⌘ '", + windows: "⌃ '", + description: "Toggle Selected Model", + }, + { + mac: "⌘ I", + windows: "⌃ I", + description: "Edit highlighted code", + }, + { + mac: "⌘ J", + windows: "⌃ J", + description: + "Start New Session / Start New Session With Selected Code / Toggle Continue Sidebar", }, { mac: "⌘ ⌫", @@ -123,28 +167,9 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ description: "Cancel response", }, { - mac: "⌘ K ⌘ M", - windows: "⌃ K ⌃ M", - description: "Toggle Full Screen", - }, - { - mac: "⌘ '", - windows: "⌃ '", - description: "Toggle Selected Model", - }, - { - mac: "⌘ K ⌘ A", - windows: "⌃ K ⌃ A", - description: "Toggle Autocomplete Enabled", - }, -]; - -const jetbrainsShortcuts: KeyboardShortcutProps[] = [ - { - mac: "⌘ J", - windows: "⌃ J", - description: - "Start New Session / Start New Session With Selected Code / Toggle Continue Sidebar", + mac: "⌘ ⇧ I", + windows: "⌃ ⇧ I", + description: "Toggle inline edit focus", }, { mac: "⌘ ⇧ J", @@ -153,25 +178,15 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [ "Add Selected Code To Current Session / Toggle Continue Sidebar", }, { - mac: "⌘ I", - windows: "⌃ I", - description: "Edit highlighted code", - }, - { - mac: "⌘ ⇧ I", - windows: "⌃ ⇧ I", - description: "Toggle inline edit focus", + mac: "⌘ ⇧ ⌫", + windows: "⌃ ⇧ ⌫", + description: "Reject Diff", }, { mac: "⌘ ⇧ ⏎", windows: "⌃ ⇧ ⏎", description: "Accept Diff", }, - { - mac: "⌘ ⇧ ⌫", - windows: "⌃ ⇧ ⌫", - description: "Reject Diff", - }, { mac: "⌥ ⇧ J", windows: "Alt ⇧ J", @@ -182,16 +197,6 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [ windows: "Alt ⌃ J", description: "Toggle Sidebar", }, - { - mac: "⌘ ⌫", - windows: "⌃ ⌫", - description: "Cancel response", - }, - { - mac: "⌘ '", - windows: "⌃ '", - description: "Toggle Selected Model", - }, ]; function KeyboardShortcuts() { From abe2f24a342bf90deee4715800aba2998237a5cf Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 23 Dec 2024 11:19:59 -0600 Subject: [PATCH 17/64] Update handler.ts --- extensions/vscode/src/diff/vertical/handler.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index a99c9c1c3..206962f56 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -497,7 +497,6 @@ export class VerticalDiffHandler implements vscode.Disposable { const diffs = myersDiff(oldFileContent, newFileContent); const meyersDiffLines = diffs.map((diff) => diff.line).join("\n"); - console.log({ newFileContent }); // Then, we overwrite the potentially miscalcualted diff blocks with our Meyers Diff const fullRange = new vscode.Range( From e9c9013ec04e42aeb482ca8a621e1ebbc402a684 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 23 Dec 2024 09:20:18 -0800 Subject: [PATCH 18/64] improv: descriptions --- gui/src/pages/More/KeyboardShortcuts.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gui/src/pages/More/KeyboardShortcuts.tsx b/gui/src/pages/More/KeyboardShortcuts.tsx index 085c8e515..7c8e3a195 100644 --- a/gui/src/pages/More/KeyboardShortcuts.tsx +++ b/gui/src/pages/More/KeyboardShortcuts.tsx @@ -89,7 +89,7 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ mac: "⌘ L", windows: "⌃ L", description: - "Start New Session / Start New Session With Selected Code / Toggle Continue Sidebar", + "New Chat / New Chat With Selected Code / Close Continue Sidebar If Chat Already In Focus", }, { mac: "⌘ ⌫", @@ -105,7 +105,7 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ mac: "⌘ ⇧ L", windows: "⌃ ⇧ L", description: - "Add Selected Code To Current Session / Toggle Continue Sidebar", + "Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar If Chat Already In Focus", }, { mac: "⌘ ⇧ R", @@ -159,7 +159,7 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [ mac: "⌘ J", windows: "⌃ J", description: - "Start New Session / Start New Session With Selected Code / Toggle Continue Sidebar", + "New Chat / New Chat With Selected Code / Close Continue Sidebar If Chat Already In Focus", }, { mac: "⌘ ⌫", @@ -175,7 +175,7 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [ mac: "⌘ ⇧ J", windows: "⌃ ⇧ J", description: - "Add Selected Code To Current Session / Toggle Continue Sidebar", + "Focus Current Chat / Add Selected Code To Current Chat / Close Continue Sidebar If Chat Already In Focus", }, { mac: "⌘ ⇧ ⌫", From 654608f5b8e30903aa30910e24b6d6c40e73962f Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 23 Dec 2024 11:25:25 -0600 Subject: [PATCH 19/64] Update ApplyActions.tsx --- .../markdown/StepContainerPreToolbar/ApplyActions.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index d71d258c5..ae42cdbeb 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -91,7 +91,7 @@ export default function ApplyActions(props: ApplyActionsProps) { ); } - return applyButton("Re-apply"); + return applyButton("Reapply"); } default: return applyButton("Apply"); From 252f8b259828d5aa9f299c34d409210fd6784030 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 23 Dec 2024 11:44:57 -0600 Subject: [PATCH 20/64] Update handler.ts --- extensions/vscode/src/diff/vertical/handler.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 206962f56..ce56a7022 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -504,9 +504,15 @@ export class VerticalDiffHandler implements vscode.Disposable { this.editor.document.positionAt(this.editor.document.getText().length), ); - await this.editor.edit((editBuilder) => { - editBuilder.replace(fullRange, meyersDiffLines); - }); + await this.editor.edit( + (editBuilder) => { + editBuilder.replace(fullRange, meyersDiffLines); + }, + { + undoStopAfter: false, + undoStopBefore: false, + }, + ); let currentBlock = { start: 0, From 0e2587cc71f497141ccd5fc807624eac80f8f183 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 23 Dec 2024 13:50:24 -0600 Subject: [PATCH 21/64] fix: broken JB build --- binary/build.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/binary/build.js b/binary/build.js index e91a3b6b3..7e971e040 100644 --- a/binary/build.js +++ b/binary/build.js @@ -276,6 +276,9 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { `node_modules/${targetToLanceDb[target]}/index.node`, `${targetDir}/index.node`, ); + + // Copy over our dummy package.json + fs.copyFileSync("out/package.json", `${targetDir}/package.json`); } // Our dummy `package.json` is no longer needed so we can remove it. @@ -284,13 +287,12 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { fs.unlinkSync("out/package.json"); const pathsToVerify = []; - for (target of targets) { + for (const target of targets) { const exe = target.startsWith("win") ? ".exe" : ""; const targetDir = `bin/${target}`; pathsToVerify.push( `${targetDir}/continue-binary${exe}`, `${targetDir}/index.node`, // @lancedb - "package.json", // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found `${targetDir}/build/Release/node_sqlite3.node`, ); } From d6bcf4cea4890a243e6619aedd8780f01e5e7fbb Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 23 Dec 2024 14:12:14 -0600 Subject: [PATCH 22/64] Update build.js --- binary/build.js | 26 +++----------------------- 1 file changed, 3 insertions(+), 23 deletions(-) diff --git a/binary/build.js b/binary/build.js index 7e971e040..045fb64f2 100644 --- a/binary/build.js +++ b/binary/build.js @@ -118,22 +118,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { } (async () => { - // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found - // This is only needed for our `pkg` command - fs.writeFileSync( - "out/package.json", - JSON.stringify( - { - name: "binary", - version: "1.0.0", - author: "Continue Dev, Inc", - license: "Apache-2.0", - }, - undefined, - 2, - ), - ); - console.log("[info] Downloading prebuilt lancedb..."); for (const target of targets) { if (targetToLanceDb[target]) { @@ -277,15 +261,11 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { `${targetDir}/index.node`, ); - // Copy over our dummy package.json - fs.copyFileSync("out/package.json", `${targetDir}/package.json`); + // Informs the `continue-binary` of where to look for node_sqlite3.node + // https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found + fs.writeFileSync(`${targetDir}/package.json`, ""); } - // Our dummy `package.json` is no longer needed so we can remove it. - // If it isn't removed, then running locally via `node out/index.js` will fail - // with a `Failed to locate bindings` error - fs.unlinkSync("out/package.json"); - const pathsToVerify = []; for (const target of targets) { const exe = target.startsWith("win") ? ".exe" : ""; From b3ac14332e8bd89237dfa41847701e3378487145 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 23 Dec 2024 11:27:30 -0800 Subject: [PATCH 23/64] fix: cycling through chat messages --- extensions/vscode/e2e/tests/GUI.test.ts | 59 ++++++++++++++++++- gui/src/components/mainInput/TipTapEditor.tsx | 7 +-- gui/src/hooks/useInputHistory.ts | 4 +- 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index c3c2cdf7e..d4c005eae 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -5,6 +5,7 @@ import { Key, WebElement, VSBrowser, + until, } from "vscode-extension-tester"; import { expect } from "chai"; import { GUIActions } from "../actions/GUI.actions"; @@ -192,7 +193,63 @@ describe("GUI Test", () => { }); describe("Chat Paths", () => { - it("Open chat and type → open history → cmd+l → chat opens, empty and in focus", async () => { + it("Open chat and send message → press arrow up and arrow down to cycle through messages → submit another message → press arrow up and arrow down to cycle through messages", async () => { + await GUIActions.sendMessage({ + view, + message: "MESSAGE 1", + inputFieldIndex: 0, + }); + + const input1 = await TestUtils.waitForSuccess(async () => { + return GUISelectors.getMessageInputFieldAtIndex(view, 1); + }); + expect(await input1.getText()).to.equal(""); + + await input1.sendKeys(Key.ARROW_UP); + await driver.wait( + until.elementTextIs(input1, "MESSAGE 1"), + DEFAULT_TIMEOUT.SM, + ); + + await input1.sendKeys(Key.ARROW_DOWN); // First press - bring caret to the end of the message + await input1.sendKeys(Key.ARROW_DOWN); // Second press - trigger message change + await driver.wait(until.elementTextIs(input1, ""), DEFAULT_TIMEOUT.SM); + + await GUIActions.sendMessage({ + view, + message: "MESSAGE 2", + inputFieldIndex: 1, + }); + + const input2 = await TestUtils.waitForSuccess(async () => { + return GUISelectors.getMessageInputFieldAtIndex(view, 2); + }); + expect(await input2.getText()).to.equal(""); + + await input2.sendKeys(Key.ARROW_UP); + await driver.wait( + until.elementTextIs(input2, "MESSAGE 2"), + DEFAULT_TIMEOUT.SM, + ); + + await input2.sendKeys(Key.ARROW_UP); + await driver.wait( + until.elementTextIs(input2, "MESSAGE 1"), + DEFAULT_TIMEOUT.SM, + ); + + await input2.sendKeys(Key.ARROW_DOWN); // First press - bring caret to the end of the message + await input2.sendKeys(Key.ARROW_DOWN); // Second press - trigger message change + await driver.wait( + until.elementTextIs(input2, "MESSAGE 2"), + DEFAULT_TIMEOUT.SM, + ); + + await input2.sendKeys(Key.ARROW_DOWN); + await driver.wait(until.elementTextIs(input2, ""), DEFAULT_TIMEOUT.SM); + }).timeout(DEFAULT_TIMEOUT.XL); + + it("Open chat and type → open history → press new session button → chat opens, empty and in focus", async () => { const originalTextInput = await GUISelectors.getMessageInputFieldAtIndex( view, 0, diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 29c6b108a..24f874eb6 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -637,12 +637,11 @@ function TipTapEditor(props: TipTapEditorProps) { return; } - props.onEnter(json, modifiers, editor); - if (props.isMainInput) { - const content = editor.state.toJSON().doc; - addRef.current(content); + addRef.current(json); } + + props.onEnter(json, modifiers, editor); }, [props.onEnter, editor, props.isMainInput], ); diff --git a/gui/src/hooks/useInputHistory.ts b/gui/src/hooks/useInputHistory.ts index 8a664a9e4..3d63886fe 100644 --- a/gui/src/hooks/useInputHistory.ts +++ b/gui/src/hooks/useInputHistory.ts @@ -52,9 +52,9 @@ export function useInputHistory(historyKey: string) { ) { setCurrentIndex(inputHistory.length); return; - } else { - setCurrentIndex(inputHistory.length + 1); } + + setCurrentIndex(inputHistory.length + 1); setInputHistory((prev) => { return [...prev, inputValue].slice(-MAX_HISTORY_LENGTH); }); From d3f7795e6133fe7452c0626e6a54fb229bacbd7b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 23 Dec 2024 14:22:39 -0800 Subject: [PATCH 24/64] fix: empty last message --- gui/src/redux/thunks/cancelStream.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/gui/src/redux/thunks/cancelStream.ts b/gui/src/redux/thunks/cancelStream.ts index dc23c04a6..c7346557c 100644 --- a/gui/src/redux/thunks/cancelStream.ts +++ b/gui/src/redux/thunks/cancelStream.ts @@ -1,5 +1,9 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; -import { abortStream, setInactive } from "../slices/sessionSlice"; +import { + abortStream, + clearLastEmptyResponse, + setInactive, +} from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; export const cancelStream = createAsyncThunk( @@ -10,6 +14,6 @@ export const cancelStream = createAsyncThunk( // If the assistant message is empty, then remove it and the user message, placing the user input in the main text box // TODO: Waiting until next release - // dispatch(clearLastEmptyResponse()); + dispatch(clearLastEmptyResponse()); }, ); From 26a847cd120926730f6c687bfb782128bf1085f7 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 24 Dec 2024 10:54:40 -0500 Subject: [PATCH 25/64] file stats method --- core/index.d.ts | 12 +++++++++++- core/indexing/CodebaseIndexer.test.ts | 7 +++---- core/indexing/CodebaseIndexer.ts | 6 +++--- core/indexing/refreshIndex.ts | 9 ++++----- core/indexing/types.ts | 4 ---- core/protocol/ide.ts | 3 ++- core/protocol/messenger/messageIde.ts | 7 ++++--- core/protocol/messenger/reverseMessageIde.ts | 4 ++-- core/util/filesystem.ts | 14 ++++++++------ .../constants/MessageTypes.kt | 2 +- .../continue/IdeProtocolClient.kt | 8 ++++---- .../continue/IntelliJIde.kt | 4 ++-- .../continueintellijextension/protocol/ide.kt | 2 +- .../continuedev/continueintellijextension/types.kt | 7 ++++++- extensions/vscode/src/VsCodeIde.ts | 14 ++++++++------ extensions/vscode/src/extension/VsCodeMessenger.ts | 4 ++-- 16 files changed, 61 insertions(+), 46 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index f9e6aa0e7..d916a19f1 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -582,6 +582,16 @@ export interface IdeSettings { enableDebugLogs: boolean; } +export interface FileStats { + size: number; + lastModified: number; +} + +/** Map of file name to stats */ +export type FileStatsMap = { + [path: string]: FileStats; +}; + export interface IDE { getIdeInfo(): Promise; @@ -665,7 +675,7 @@ export interface IDE { listDir(dir: string): Promise<[string, FileType][]>; - getLastModified(files: string[]): Promise<{ [path: string]: number }>; + getFileStats(files: string[]): Promise; getGitHubAuthToken(args: GetGhTokenArgs): Promise; diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index 7db40d75e..211bc3732 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -1,7 +1,7 @@ +import { jest } from "@jest/globals"; import { execSync } from "node:child_process"; import fs from "node:fs"; import path from "path"; -import { jest } from "@jest/globals"; import { ContinueServerClient } from "../continueServer/stubs/client.js"; import { testConfigHandler, testIde } from "../test/fixtures.js"; @@ -14,13 +14,12 @@ import { } from "../test/testDir.js"; import { getIndexSqlitePath } from "../util/paths.js"; +import { pathToFileURL } from "node:url"; import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; import { CodebaseIndex } from "./types.js"; import { walkDir } from "./walkDir.js"; -import { pathToFileURL } from "node:url"; -import { joinPathsToUri } from "../util/uri.js"; jest.useFakeTimers(); @@ -120,7 +119,7 @@ describe("CodebaseIndexer", () => { async function getIndexPlan() { const workspaceFiles = await walkDir(TEST_DIR, testIde); const [tag] = await testIde.getTags(testIndex.artifactId); - const stats = await testIde.getLastModified(workspaceFiles); + const stats = await testIde.getFileStats(workspaceFiles); const [results, lastUpdated, markComplete] = await getComputeDeleteAddRemove( diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 4e8355c9b..e309549eb 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -6,6 +6,7 @@ import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js"; import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; +import { findUriInDirs, getUriPathBasename } from "../util/uri.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; @@ -17,7 +18,6 @@ import { RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; -import { findUriInDirs, getUriPathBasename } from "../util/uri.js"; export class PauseToken { constructor(private _paused: boolean) {} @@ -110,7 +110,7 @@ export class CodebaseIndexer { const branch = await this.ide.getBranch(foundInDir); const repoName = await this.ide.getRepoName(foundInDir); const indexesToBuild = await this.getIndexesToBuild(); - const stats = await this.ide.getLastModified([file]); + const stats = await this.ide.getFileStats([file]); for (const index of indexesToBuild) { const tag = { directory: foundInDir, @@ -389,7 +389,7 @@ export class CodebaseIndexer { branch: string, repoName: string | undefined, ): AsyncGenerator { - const stats = await this.ide.getLastModified(files); + const stats = await this.ide.getFileStats(files); const indexesToBuild = await this.getIndexesToBuild(); let completedIndexCount = 0; let progress = 0; diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index fc71bb046..30fb048cc 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -5,13 +5,12 @@ import plimit from "p-limit"; import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; -import { IndexTag, IndexingProgressUpdate } from "../index.js"; +import { FileStatsMap, IndexTag, IndexingProgressUpdate } from "../index.js"; import { getIndexSqlitePath } from "../util/paths.js"; import { CodebaseIndex, IndexResultType, - LastModifiedMap, MarkCompleteCallback, PathAndCacheKey, RefreshIndexResults, @@ -129,7 +128,7 @@ enum AddRemoveResultType { async function getAddRemoveForTag( tag: IndexTag, - currentFiles: LastModifiedMap, + currentFiles: FileStatsMap, readFile: (path: string) => Promise, ): Promise< [ @@ -157,7 +156,7 @@ async function getAddRemoveForTag( remove.push(pathAndCacheKey); } else { // Exists in old and new, so determine whether it was updated - if (lastUpdated < files[item.path]) { + if (lastUpdated < files[item.path].lastModified) { // Change was made after last update const newHash = calculateHash(await readFile(pathAndCacheKey.path)); if (pathAndCacheKey.cacheKey !== newHash) { @@ -345,7 +344,7 @@ function mapIndexResultTypeToAddRemoveResultType( export async function getComputeDeleteAddRemove( tag: IndexTag, - currentFiles: LastModifiedMap, + currentFiles: FileStatsMap, readFile: (path: string) => Promise, repoName: string | undefined, ): Promise<[RefreshIndexResults, PathAndCacheKey[], MarkCompleteCallback]> { diff --git a/core/indexing/types.ts b/core/indexing/types.ts index 3e3e287b6..bc4183aea 100644 --- a/core/indexing/types.ts +++ b/core/indexing/types.ts @@ -36,8 +36,4 @@ export type RefreshIndexResults = { removeTag: PathAndCacheKey[]; }; -export type LastModifiedMap = { - [path: string]: number; -}; - export type RefreshIndex = (tag: IndexTag) => Promise; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 667ebd7b2..4df3cb95b 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -3,6 +3,7 @@ import { ControlPlaneSessionInfo } from "../control-plane/client"; import type { ContinueRcJson, DiffLine, + FileStatsMap, FileType, IDE, IdeInfo, @@ -84,7 +85,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { ]; getGitRootPath: [{ dir: string }, string | undefined]; listDir: [{ dir: string }, [string, FileType][]]; - getLastModified: [{ files: string[] }, { [path: string]: number }]; + getFileStats: [{ files: string[] }, FileStatsMap]; gotoDefinition: [{ location: Location }, RangeInFile[]]; diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index e2cd50c78..9f46602c1 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -1,8 +1,9 @@ -import { GetGhTokenArgs, ToIdeFromWebviewOrCoreProtocol } from "../ide"; import { FromIdeProtocol } from ".."; +import { GetGhTokenArgs, ToIdeFromWebviewOrCoreProtocol } from "../ide"; import type { ContinueRcJson, + FileStatsMap, FileType, IDE, IdeInfo, @@ -43,8 +44,8 @@ export class MessageIde implements IDE { getGitHubAuthToken(args: GetGhTokenArgs): Promise { return this.request("getGitHubAuthToken", args); } - getLastModified(files: string[]): Promise<{ [path: string]: number }> { - return this.request("getLastModified", { files }); + getFileStats(files: string[]): Promise { + return this.request("getFileStats", { files }); } getGitRootPath(dir: string): Promise { return this.request("getGitRootPath", { dir }); diff --git a/core/protocol/messenger/reverseMessageIde.ts b/core/protocol/messenger/reverseMessageIde.ts index e3f97ea4f..620055a75 100644 --- a/core/protocol/messenger/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -38,8 +38,8 @@ export class ReverseMessageIde { return this.ide.getGitHubAuthToken(data); }); - this.on("getLastModified", (data) => { - return this.ide.getLastModified(data.files); + this.on("getFileStats", (data) => { + return this.ide.getFileStats(data.files); }); this.on("getGitRootPath", (data) => { diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index d0821b6ef..45ac7a7c5 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -1,7 +1,9 @@ import * as fs from "node:fs"; +import { fileURLToPath } from "node:url"; import { ContinueRcJson, + FileStatsMap, FileType, IDE, IdeInfo, @@ -15,7 +17,6 @@ import { ToastType, } from "../index.js"; import { GetGhTokenArgs } from "../protocol/ide.js"; -import { fileURLToPath } from "node:url"; class FileSystemIde implements IDE { constructor(private readonly workspaceDir: string) {} @@ -51,15 +52,16 @@ class FileSystemIde implements IDE { async getGitHubAuthToken(args: GetGhTokenArgs): Promise { return undefined; } - async getLastModified( - fileUris: string[], - ): Promise<{ [path: string]: number }> { - const result: { [path: string]: number } = {}; + async getFileStats(fileUris: string[]): Promise { + const result: FileStatsMap = {}; for (const uri of fileUris) { try { const filepath = fileURLToPath(uri); const stats = fs.statSync(filepath); - result[uri] = stats.mtimeMs; + result[uri] = { + lastModified: stats.mtimeMs, + size: stats.size, + }; } catch (error) { console.error(`Error getting last modified time for ${uri}:`, error); } 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 0374e9346..b309cbbc6 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 @@ -39,7 +39,7 @@ class MessageTypes { "getRepoName", "listDir", "getGitRootPath", - "getLastModified", + "getFileStats", "insertAtCursor", "applyToFile", "getGitHubAuthToken", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 69e06e89e..b4078beea 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -215,13 +215,13 @@ class IdeProtocolClient( respond(null) } - "getLastModified" -> { + "getFileStats" -> { val params = Gson().fromJson( dataElement.toString(), - GetLastModifiedParams::class.java + GetFileStatsParams::class.java ) - val lastModifiedMap = ide.getLastModified(params.files) - respond(lastModifiedMap) + val fileStatsMap = ide.getFileStats(params.files) + respond(fileStatsMap) } "listDir" -> { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 154476f5e..84ff3fc10 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -519,9 +519,9 @@ class IntelliJIDE( return files } - override suspend fun getLastModified(files: List): Map { + override suspend fun getFileStats(files: List): Map { return files.associateWith { file -> - File(URI(file)).lastModified() + FileStats(File(URI(file)).lastModified(), File(URI(file)).length()) } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 432ac4f6e..4aa433f52 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -58,4 +58,4 @@ data class GetGitRootPathParams(val dir: String) data class ListDirParams(val dir: String) -data class GetLastModifiedParams(val files: List) \ No newline at end of file +data class GetFileStatsParams(val files: List) \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index b1e051777..1400e5c54 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -77,6 +77,11 @@ data class Account( val id: String ) +data class FileStats( + val lastModified: Long, + val size: Long +) + data class IdeSettings( val remoteConfigServerUrl: String?, val remoteConfigSyncPeriod: Int, @@ -183,7 +188,7 @@ interface IDE { // will serialize to `first and `second` rather than `0` and `1` like in JavaScript suspend fun listDir(dir: String): List> - suspend fun getLastModified(files: List): Map + suspend fun getFileStats(files: List): Map suspend fun getGitHubAuthToken(args: GetGhTokenArgs): String? diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 17fb84789..faa60cfd4 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -3,20 +3,20 @@ import { exec } from "node:child_process"; import { Range } from "core"; import { EXTENSION_NAME } from "core/control-plane/env"; -import { walkDir } from "core/indexing/walkDir"; import { GetGhTokenArgs } from "core/protocol/ide"; import { editConfigJson, getConfigJsonPath } from "core/util/paths"; import * as vscode from "vscode"; +import * as URI from "uri-js"; import { executeGotoProvider } from "./autocomplete/lsp"; import { Repository } from "./otherExtensions/git"; import { VsCodeIdeUtils } from "./util/ideUtils"; import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; import { VsCodeWebviewProtocol } from "./webviewProtocol"; -import * as URI from "uri-js"; import type { ContinueRcJson, + FileStatsMap, FileType, IDE, IdeInfo, @@ -27,7 +27,6 @@ import type { RangeInFile, Thread, } from "core"; -import { findUriInDirs } from "core/util/uri"; class VsCodeIde implements IDE { ideUtils: VsCodeIdeUtils; @@ -274,12 +273,15 @@ class VsCodeIde implements IDE { ); } - async getLastModified(files: string[]): Promise<{ [path: string]: number }> { - const pathToLastModified: { [path: string]: number } = {}; + async getFileStats(files: string[]): Promise { + const pathToLastModified: FileStatsMap = {}; await Promise.all( files.map(async (file) => { const stat = await vscode.workspace.fs.stat(vscode.Uri.parse(file)); - pathToLastModified[file] = stat.mtime; + pathToLastModified[file] = { + lastModified: stat.mtime, + size: stat.size, + }; }), ); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index d562fdb29..2b88fbca6 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -473,8 +473,8 @@ export class VsCodeMessenger { return await ide.gotoDefinition(msg.data.location); }); - this.onWebviewOrCore("getLastModified", async (msg) => { - return await ide.getLastModified(msg.data.files); + this.onWebviewOrCore("getFileStats", async (msg) => { + return await ide.getFileStats(msg.data.files); }); this.onWebviewOrCore("getGitRootPath", async (msg) => { From 157ac38aa3e5c4f2740a77279bba571817fc8588 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 24 Dec 2024 11:12:00 -0500 Subject: [PATCH 26/64] indexing max file size --- core/indexing/refreshIndex.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 30fb048cc..34c1ac4a2 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -126,6 +126,9 @@ enum AddRemoveResultType { Compute = "compute", } +// Don't attempt to index anything over 5MB +const MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024; + async function getAddRemoveForTag( tag: IndexTag, currentFiles: FileStatsMap, @@ -141,6 +144,12 @@ async function getAddRemoveForTag( const newLastUpdatedTimestamp = Date.now(); const files = { ...currentFiles }; + for (const path in files) { + if (files[path].size > MAX_FILE_SIZE_BYTES) { + delete files[path]; + } + } + const saved = await getSavedItemsForTag(tag); const updateNewVersion: PathAndCacheKey[] = []; From 88e34fb69caae3750621f9f93253a7425535928f Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 24 Dec 2024 08:36:46 -0800 Subject: [PATCH 27/64] fix: tip tap undo and redo --- gui/src/components/mainInput/handleMetaKeyIssues.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/gui/src/components/mainInput/handleMetaKeyIssues.ts b/gui/src/components/mainInput/handleMetaKeyIssues.ts index 867203a14..baf824bd6 100644 --- a/gui/src/components/mainInput/handleMetaKeyIssues.ts +++ b/gui/src/components/mainInput/handleMetaKeyIssues.ts @@ -48,6 +48,11 @@ export const handleVSCMetaKeyIssues = async ( x: () => handleCutOperation(text, editor), c: () => handleCopyOperation(text), v: () => handlePasteOperation(editor), + z: () => { + return e.shiftKey + ? handleRedoOperation(editor) + : handleUndoOperation(editor); + }, }; if (e.key in handlers) { @@ -130,3 +135,11 @@ export const handlePasteOperation = async (editor: Editor) => { document.execCommand("paste"); } }; + +export const handleUndoOperation = async (editor: Editor) => { + editor.commands.undo(); +}; + +export const handleRedoOperation = async (editor: Editor) => { + editor.commands.redo(); +}; From f3de9d85b0603920a240a2ef5c11098772d8b5b1 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 24 Dec 2024 11:38:06 -0500 Subject: [PATCH 28/64] bump package.json version --- 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 8470f84fd..4cb023717 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": "0.9.246", + "version": "0.9.247", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From fb2740d5d4a9a752fbaa87bfa15b277d3b6b38eb Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 24 Dec 2024 08:50:17 -0800 Subject: [PATCH 29/64] test: chat input undo / redo --- .../e2e/tests/KeyboardShortcuts.test.ts | 57 ++++++++++++++++++- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts index cc3f6691d..c73715612 100644 --- a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts +++ b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts @@ -8,13 +8,13 @@ import { WebView, WebElement, until, + Key, } from "vscode-extension-tester"; import { DEFAULT_TIMEOUT } from "../constants"; import { GUISelectors } from "../selectors/GUI.selectors"; import { GUIActions } from "../actions/GUI.actions"; import { expect } from "chai"; import { TestUtils } from "../TestUtils"; -import { Test } from "mocha"; import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; describe("Cmd+L Shortcut Test", () => { @@ -49,6 +49,59 @@ describe("Cmd+L Shortcut Test", () => { await new EditorView().closeAllEditors(); }); + it("Should correctly undo and redo using keyboard shortcuts when writing a chat message", async () => { + await GUIActions.executeFocusContinueInputShortcut(driver); + ({ view } = await GUIActions.switchToReactIframe()); + const chatInput = await TestUtils.waitForSuccess(async () => { + return GUISelectors.getMessageInputFieldAtIndex(view, 0); + }); + + await chatInput.sendKeys("HELLO "); + await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XS); + + await chatInput.sendKeys("WORLD "); + await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XS); + + await chatInput.sendKeys("HELLO "); + await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XS); + + await chatInput.sendKeys("CONTINUE"); + await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XS); + + await chatInput.sendKeys(Key.COMMAND + "z"); + await driver.wait( + until.elementTextIs(chatInput, "HELLO WORLD"), + DEFAULT_TIMEOUT.SM, + ); + + await chatInput.sendKeys(Key.COMMAND + "z"); + await driver.wait(until.elementTextIs(chatInput, ""), DEFAULT_TIMEOUT.SM); + + await chatInput.sendKeys(Key.SHIFT + Key.COMMAND + "z"); + await driver.wait( + until.elementTextIs(chatInput, "HELLO"), + DEFAULT_TIMEOUT.SM, + ); + + await chatInput.sendKeys(Key.SHIFT + Key.COMMAND + "z"); + await driver.wait( + until.elementTextIs(chatInput, "HELLO WORLD"), + DEFAULT_TIMEOUT.SM, + ); + + await chatInput.sendKeys(Key.SHIFT + Key.COMMAND + "z"); + await driver.wait( + until.elementTextIs(chatInput, "HELLO WORLD HELLO"), + DEFAULT_TIMEOUT.SM, + ); + + await chatInput.sendKeys(Key.SHIFT + Key.COMMAND + "z"); + await driver.wait( + until.elementTextIs(chatInput, "HELLO WORLD HELLO CONTINUE"), + DEFAULT_TIMEOUT.SM, + ); + }).timeout(DEFAULT_TIMEOUT.XL); + it("Should not create a code block when Cmd+L is pressed without text highlighted", async () => { const text = "Hello, world!"; @@ -118,7 +171,7 @@ describe("Cmd+L Shortcut Test", () => { await driver.wait(until.elementIsNotVisible(textInput), DEFAULT_TIMEOUT.XS); expect(await textInput.isDisplayed()).to.equal(false); - }).timeout(DEFAULT_TIMEOUT.XL * 1000); + }).timeout(DEFAULT_TIMEOUT.XL); it("Should create a code block when Cmd+L is pressed with text highlighted", async () => { const text = "Hello, world!"; From 9ab29ea76cc597fba2fd6a8adfffce49033ef6e9 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 24 Dec 2024 10:32:43 -0800 Subject: [PATCH 30/64] improv: naming --- extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts index c73715612..908bfb6c4 100644 --- a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts +++ b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts @@ -17,7 +17,7 @@ import { expect } from "chai"; import { TestUtils } from "../TestUtils"; import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; -describe("Cmd+L Shortcut Test", () => { +describe("Keyboard Shortcuts", () => { let driver: WebDriver; let editor: TextEditor; let view: WebView; From e45aa164c64a52936c7dd1c0467548aadf821639 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 24 Dec 2024 10:37:26 -0800 Subject: [PATCH 31/64] fix: keyboard shortcuts test on linux --- .../vscode/e2e/tests/KeyboardShortcuts.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts index 908bfb6c4..0191d1d63 100644 --- a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts +++ b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts @@ -68,34 +68,34 @@ describe("Keyboard Shortcuts", () => { await chatInput.sendKeys("CONTINUE"); await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XS); - await chatInput.sendKeys(Key.COMMAND + "z"); + await chatInput.sendKeys(TestUtils.osControlKey + "z"); await driver.wait( until.elementTextIs(chatInput, "HELLO WORLD"), DEFAULT_TIMEOUT.SM, ); - await chatInput.sendKeys(Key.COMMAND + "z"); + await chatInput.sendKeys(TestUtils.osControlKey + "z"); await driver.wait(until.elementTextIs(chatInput, ""), DEFAULT_TIMEOUT.SM); - await chatInput.sendKeys(Key.SHIFT + Key.COMMAND + "z"); + await chatInput.sendKeys(Key.SHIFT + TestUtils.osControlKey + "z"); await driver.wait( until.elementTextIs(chatInput, "HELLO"), DEFAULT_TIMEOUT.SM, ); - await chatInput.sendKeys(Key.SHIFT + Key.COMMAND + "z"); + await chatInput.sendKeys(Key.SHIFT + TestUtils.osControlKey + "z"); await driver.wait( until.elementTextIs(chatInput, "HELLO WORLD"), DEFAULT_TIMEOUT.SM, ); - await chatInput.sendKeys(Key.SHIFT + Key.COMMAND + "z"); + await chatInput.sendKeys(Key.SHIFT + TestUtils.osControlKey + "z"); await driver.wait( until.elementTextIs(chatInput, "HELLO WORLD HELLO"), DEFAULT_TIMEOUT.SM, ); - await chatInput.sendKeys(Key.SHIFT + Key.COMMAND + "z"); + await chatInput.sendKeys(Key.SHIFT + TestUtils.osControlKey + "z"); await driver.wait( until.elementTextIs(chatInput, "HELLO WORLD HELLO CONTINUE"), DEFAULT_TIMEOUT.SM, From 9edd5e3e241862d8189cf17332f7c3a2933125c4 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 24 Dec 2024 14:03:23 -0500 Subject: [PATCH 32/64] Use ConfigResult everywhere --- binary/test/binary.test.ts | 24 ++++----- core/autocomplete/CompletionProvider.ts | 6 +-- core/config/ConfigHandler.test.ts | 4 +- core/config/ConfigHandler.ts | 32 +++++------- core/config/ProfileLifecycleManager.ts | 37 ++++++------- core/context/mcp/index.ts | 2 +- .../providers/_context-providers.test.ts | 9 ++-- core/core.ts | 52 +++++++++++++------ core/indexing/CodebaseIndexer.ts | 10 ++-- core/indexing/LanceDbIndex.test.ts | 7 ++- core/indexing/docs/DocsCrawler.skip.ts | 3 +- core/indexing/docs/DocsService.skip.ts | 4 +- core/indexing/docs/DocsService.ts | 11 ++-- core/protocol/core.ts | 8 ++- core/protocol/webview.ts | 6 ++- extensions/vscode/src/commands.ts | 7 ++- .../vscode/src/extension/VsCodeExtension.ts | 6 +-- .../vscode/src/extension/VsCodeMessenger.ts | 7 ++- .../codeLens/registerAllCodeLensProviders.ts | 12 +++-- .../src/quickEdit/QuickEditQuickPick.ts | 16 ++++-- .../vscode/src/util/loadAutocompleteModel.ts | 6 ++- gui/src/hooks/useSetup.ts | 19 ++++--- gui/src/redux/slices/configSlice.ts | 16 ++++-- 23 files changed, 189 insertions(+), 115 deletions(-) diff --git a/binary/test/binary.test.ts b/binary/test/binary.test.ts index f84b23a2d..bd8504986 100644 --- a/binary/test/binary.test.ts +++ b/binary/test/binary.test.ts @@ -1,8 +1,8 @@ import { SerializedContinueConfig } from "core"; // import Mock from "core/llm/llms/Mock.js"; import { FromIdeProtocol, ToIdeProtocol } from "core/protocol/index.js"; -import FileSystemIde from "core/util/filesystem"; import { IMessenger } from "core/protocol/messenger"; +import FileSystemIde from "core/util/filesystem"; import fs from "fs"; import { ChildProcessWithoutNullStreams, @@ -186,10 +186,11 @@ describe("Test Suite", () => { }); it("should return valid config object", async () => { - const { config } = await messenger.request( + const { result } = await messenger.request( "config/getSerializedProfileInfo", undefined, ); + const { config } = result; expect(config).toHaveProperty("models"); expect(config).toHaveProperty("embeddingsProvider"); expect(config).toHaveProperty("contextProviders"); @@ -229,18 +230,17 @@ describe("Test Suite", () => { await messenger.request("config/addModel", { model, }); - const { config } = await messenger.request( - "config/getSerializedProfileInfo", - undefined, - ); - expect(config.models.some((m) => m.title === model.title)).toBe(true); + const { + result: { config }, + } = await messenger.request("config/getSerializedProfileInfo", undefined); + + expect(config!.models.some((m) => m.title === model.title)).toBe(true); await messenger.request("config/deleteModel", { title: model.title }); - const { config: configAfterDelete } = await messenger.request( - "config/getSerializedProfileInfo", - undefined, - ); - expect(configAfterDelete.models.some((m) => m.title === model.title)).toBe( + const { + result: { config: configAfterDelete }, + } = await messenger.request("config/getSerializedProfileInfo", undefined); + expect(configAfterDelete!.models.some((m) => m.title === model.title)).toBe( false, ); }); diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 479b9061c..77aadbdf5 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -3,11 +3,9 @@ import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { IDE, ILLM } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; -import { PosthogFeatureFlag, Telemetry } from "../util/posthog.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -// @prettier-ignore import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; @@ -123,10 +121,10 @@ export class CompletionProvider { } private async _getAutocompleteOptions() { - const config = await this.configHandler.loadConfig(); + const { config } = await this.configHandler.loadConfig(); const options = { ...DEFAULT_AUTOCOMPLETE_OPTS, - ...config.tabAutocompleteOptions, + ...config?.tabAutocompleteOptions, }; return options; } diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index e7d90f492..5a25e71fc 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -18,8 +18,8 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { }); test("should load the default config successfully", async () => { - const config = await testConfigHandler.loadConfig(); - expect(config.models.length).toBe(defaultConfig.models.length); + const result = await testConfigHandler.loadConfig(); + expect(result.config!.models.length).toBe(defaultConfig.models.length); }); test.skip("should add a system message from config.ts", async () => { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 0106a96c5..9ef3cc8d2 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -60,13 +60,13 @@ export class ConfigHandler { // Always load local profile immediately in case control plane doesn't load try { - this.loadConfig(); + void this.loadConfig(); } catch (e) { console.error("Failed to load config: ", e); } // Load control plane profiles - this.fetchControlPlaneProfiles(); + void this.fetchControlPlaneProfiles(); } // This will be the local profile @@ -146,12 +146,8 @@ export class ConfigHandler { async setSelectedProfile(profileId: string) { this.selectedProfileId = profileId; - const newConfig = await this.loadConfig(); - this.notifyConfigListeners({ - config: newConfig, - errors: undefined, - configLoadInterrupted: false, - }); + const result = await this.loadConfig(); + this.notifyConfigListeners(result); const selectedProfiles = this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; selectedProfiles[await this.getWorkspaceId()] = profileId; @@ -170,7 +166,7 @@ export class ConfigHandler { // Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed updateIdeSettings(ideSettings: IdeSettings) { this.ideSettingsPromise = Promise.resolve(ideSettings); - this.reloadConfig(); + void this.reloadConfig(); } updateControlPlaneSessionInfo( @@ -236,15 +232,15 @@ export class ConfigHandler { return this.profiles.map((p) => p.profileDescription); } - async loadConfig(): Promise { - return ( - await this.currentProfile.loadConfig(this.additionalContextProviders) - ).config!; // <-- TODO + async loadConfig(): Promise> { + return await this.currentProfile.loadConfig( + this.additionalContextProviders, + ); } async llmFromTitle(title?: string): Promise { - const config = await this.loadConfig(); - const model = config.models.find((m) => m.title === title); + const { config } = await this.loadConfig(); + const model = config?.models.find((m) => m.title === title); if (!model) { if (title === ONBOARDING_LOCAL_MODEL_TITLE) { // Special case, make calls to Ollama before we have it in the config @@ -252,8 +248,8 @@ export class ConfigHandler { model: LOCAL_ONBOARDING_CHAT_MODEL, }); return ollama; - } else if (config.models.length > 0) { - return config.models[0]; + } else if (config?.models?.length) { + return config?.models[0]; } throw new Error("No model found"); @@ -264,6 +260,6 @@ export class ConfigHandler { registerCustomContextProvider(contextProvider: IContextProvider) { this.additionalContextProviders.push(contextProvider); - this.reloadConfig(); + void this.reloadConfig(); } } diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index 7b595c0e6..c5ae16f91 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -13,8 +13,8 @@ export interface ProfileDescription { } export class ProfileLifecycleManager { - private savedConfig: ConfigResult | undefined; - private savedBrowserConfig?: BrowserSerializedContinueConfig; + private savedConfigResult: ConfigResult | undefined; + private savedBrowserConfigResult?: ConfigResult; private pendingConfigPromise?: Promise>; constructor(private readonly profileLoader: IProfileLoader) {} @@ -35,15 +35,15 @@ export class ProfileLifecycleManager { } clearConfig() { - this.savedConfig = undefined; - this.savedBrowserConfig = undefined; + this.savedConfigResult = undefined; + this.savedBrowserConfigResult = undefined; this.pendingConfigPromise = undefined; } // Clear saved config and reload async reloadConfig(): Promise> { - this.savedConfig = undefined; - this.savedBrowserConfig = undefined; + this.savedConfigResult = undefined; + this.savedBrowserConfigResult = undefined; this.pendingConfigPromise = undefined; return this.loadConfig([], true); @@ -55,8 +55,8 @@ export class ProfileLifecycleManager { ): Promise> { // If we already have a config, return it if (!forceReload) { - if (this.savedConfig) { - return this.savedConfig; + if (this.savedConfigResult) { + return this.savedConfigResult; } else if (this.pendingConfigPromise) { return this.pendingConfigPromise; } @@ -72,7 +72,7 @@ export class ProfileLifecycleManager { result.config.contextProviders ?? [] ).concat(additionalContextProviders); - this.savedConfig = result; + this.savedConfigResult = result; resolve(result); } else if (result.errors) { reject( @@ -82,15 +82,17 @@ export class ProfileLifecycleManager { }); // Wait for the config promise to resolve - this.savedConfig = await this.pendingConfigPromise; + this.savedConfigResult = await this.pendingConfigPromise; this.pendingConfigPromise = undefined; - return this.savedConfig; + return this.savedConfigResult; } async getSerializedConfig( additionalContextProviders: IContextProvider[], ): Promise> { - if (!this.savedBrowserConfig) { + if (this.savedBrowserConfigResult) { + return this.savedBrowserConfigResult; + } else { const result = await this.loadConfig(additionalContextProviders); if (!result.config) { return { @@ -98,12 +100,11 @@ export class ProfileLifecycleManager { config: undefined, }; } - this.savedBrowserConfig = finalToBrowserConfig(result.config); + const serializedConfig = finalToBrowserConfig(result.config); + return { + ...result, + config: serializedConfig, + }; } - return { - config: this.savedBrowserConfig, - errors: [], - configLoadInterrupted: false, - }; } } diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index 9a14e49cd..bcf11492f 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -132,7 +132,7 @@ class MCPConnection { if (!error.message.startsWith("StdioClientTransport already started")) { return { fatal: false, - message: `Failed to connect to MCP ${mcpId}: ${error.message}`, + message: `Failed to connect to MCP: ${error.message}`, }; } } diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index 7e0fdbd73..24cac2c44 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -1,15 +1,15 @@ import fetch from "node-fetch"; +import { contextProviderClassFromName } from "."; import { ContextProviderExtras, ContextProviderWithParams, IContextProvider, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; -import { contextProviderClassFromName } from "."; import { ControlPlaneClient } from "../../control-plane/client"; -import FileSystemIde from "../../util/filesystem"; import { TEST_DIR } from "../../test/testDir"; +import FileSystemIde from "../../util/filesystem"; const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [ { name: "diff", params: {} }, @@ -33,7 +33,10 @@ async function getContextProviderExtras( async (text) => {}, new ControlPlaneClient(Promise.resolve(undefined)), ); - const config = await configHandler.loadConfig(); + const { config } = await configHandler.loadConfig(); + if (!config) { + throw new Error("Config not found"); + } return { fullInput, diff --git a/core/core.ts b/core/core.ts index aa9c1eb5b..14389910c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -65,7 +65,7 @@ export class Core { private abortedMessageIds: Set = new Set(); private async config() { - return this.configHandler.loadConfig(); + return (await this.configHandler.loadConfig()).config; } invoke( @@ -120,11 +120,9 @@ export class Core { ); this.configHandler.onConfigUpdate(async (result) => { - const serialized = await ( - await this.configHandler.getSerializedConfig() - ).config!; + const serializedResult = await this.configHandler.getSerializedConfig(); this.messenger.send("configUpdate", { - config: serialized, + result: serializedResult, profileId: this.configHandler.currentProfile.profileId, }); }); @@ -178,12 +176,12 @@ export class Core { }); const getLlm = async () => { - const config = await this.configHandler.loadConfig(); + const { config } = await this.configHandler.loadConfig(); const selected = this.globalContext.get("selectedTabAutocompleteModel"); return ( - config.tabAutocompleteModels?.find( + config?.tabAutocompleteModels?.find( (model) => model.title === selected, - ) ?? config.tabAutocompleteModels?.[0] + ) ?? config?.tabAutocompleteModels?.[0] ); }; this.completionProvider = new CompletionProvider( @@ -261,7 +259,7 @@ export class Core { on("config/newPromptFile", async (msg) => { await createNewPromptFileV2( this.ide, - (await this.config()).experimental?.promptPath, + (await this.config())?.experimental?.promptPath, ); await this.configHandler.reloadConfig(); }); @@ -272,7 +270,7 @@ export class Core { on("config/reload", async (msg) => { void this.configHandler.reloadConfig(); - return (await this.configHandler.getSerializedConfig()).config!; // <-- TODO + return await this.configHandler.getSerializedConfig(); }); on("config/ideSettingsUpdate", (msg) => { @@ -297,6 +295,10 @@ export class Core { on("context/loadSubmenuItems", async (msg) => { const config = await this.config(); + if (!config) { + return []; + } + const items = await config.contextProviders ?.find((provider) => provider.description.title === msg.data.title) ?.loadSubmenuItems({ @@ -312,6 +314,10 @@ export class Core { const { name, query, fullInput, selectedCode, selectedModelTitle } = msg.data; const config = await this.config(); + if (!config) { + return []; + } + const llm = await this.configHandler.llmFromTitle(selectedModelTitle); const provider = config.contextProviders?.find( (provider) => provider.description.title === name, @@ -366,7 +372,7 @@ export class Core { on("config/getSerializedProfileInfo", async (msg) => { return { - config: (await this.configHandler.getSerializedConfig()).config!, // <-- TODO + result: await this.configHandler.getSerializedConfig(), profileId: this.configHandler.currentProfile.profileId, }; }); @@ -376,7 +382,11 @@ export class Core { abortedMessageIds: Set, msg: Message, ) { - const config = await configHandler.loadConfig(); + const { config } = await configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } + // Stop TTS on new StreamChat if (config.experimental?.readResponseTTS) { void TTS.kill(); @@ -480,7 +490,11 @@ export class Core { return completion; }); on("llm/listModels", async (msg) => { - const config = await this.configHandler.loadConfig(); + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return []; + } + const model = config.models.find((model) => model.title === msg.data.title) ?? config.models.find((model) => model.title?.startsWith(msg.data.title)); @@ -533,7 +547,11 @@ export class Core { selectedCode, } = msg.data; - const config = await configHandler.loadConfig(); + const { config } = await configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } + const llm = await configHandler.llmFromTitle(modelTitle); const slashCommand = config.slashCommands?.find( (sc) => sc.name === slashCommandName, @@ -846,7 +864,11 @@ export class Core { }); on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => { - const config = await this.configHandler.loadConfig(); + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } + const tool = config.tools.find( (t) => t.function.name === toolCall.function.name, ); diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index e309549eb..677cc4305 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -75,7 +75,11 @@ export class CodebaseIndexer { } protected async getIndexesToBuild(): Promise { - const config = await this.configHandler.loadConfig(); + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return []; + } + const indexes = [ new ChunkCodebaseIndex( this.ide.readFile.bind(this.ide), @@ -198,8 +202,8 @@ export class CodebaseIndexer { return; } - const config = await this.configHandler.loadConfig(); - if (config.disableIndexing) { + const { config } = await this.configHandler.loadConfig(); + if (config?.disableIndexing) { yield { progress, desc: "Indexing is disabled in config.json", diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts index 6cf36f78d..08c8f9982 100644 --- a/core/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -2,13 +2,13 @@ import { jest } from "@jest/globals"; import lance from "vectordb"; import { testConfigHandler, testIde } from "../test/fixtures"; +import { getLanceDbPath } from "../util/paths"; import { mockPathAndCacheKey, mockTag, testContinueServerClient, updateIndexAndAwaitGenerator, } from "./test/indexing"; -import { getLanceDbPath } from "../util/paths"; import { LanceDbIndex } from "./LanceDbIndex"; import { DatabaseConnection, SqliteDb } from "./refreshIndex"; @@ -26,7 +26,10 @@ describe.skip("ChunkCodebaseIndex", () => { } beforeAll(async () => { - const mockConfig = await testConfigHandler.loadConfig(); + const { config: mockConfig } = await testConfigHandler.loadConfig(); + if (!mockConfig) { + throw new Error("Failed to load config"); + } index = new LanceDbIndex( mockConfig.embeddingsProvider, diff --git a/core/indexing/docs/DocsCrawler.skip.ts b/core/indexing/docs/DocsCrawler.skip.ts index 97226c296..93d1749c9 100644 --- a/core/indexing/docs/DocsCrawler.skip.ts +++ b/core/indexing/docs/DocsCrawler.skip.ts @@ -28,7 +28,8 @@ describe.skip("DocsCrawler", () => { let docsCrawler: DocsCrawler; beforeAll(async () => { - config = await testConfigHandler.loadConfig(); + const result = await testConfigHandler.loadConfig(); + config = result.config!; mockIde = new FileSystemIde(process.cwd()); chromiumInstaller = new ChromiumInstaller(mockIde, config); docsCrawler = new DocsCrawler(mockIde, config); diff --git a/core/indexing/docs/DocsService.skip.ts b/core/indexing/docs/DocsService.skip.ts index 22c307f35..8b4b6a8bf 100644 --- a/core/indexing/docs/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -74,7 +74,7 @@ describe.skip("DocsService Integration Tests", () => { expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); // config.json check - expect(latestConfig.docs).toContainEqual(mockSiteConfig); + expect(latestConfig.config!.docs).toContainEqual(mockSiteConfig); // Lance DB check let retrievedChunks = await docsService.retrieveChunksFromQuery( @@ -92,7 +92,7 @@ describe.skip("DocsService Integration Tests", () => { // config.json check latestConfig = await getReloadedConfig(); - expect(latestConfig.docs).not.toContainEqual( + expect(latestConfig.config!.docs).not.toContainEqual( expect.objectContaining(mockSiteConfig), ); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index f35f83466..ddebd47a8 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -16,9 +16,9 @@ import { addContextProvider } from "../../config/util"; import DocsContextProvider from "../../context/providers/DocsContextProvider"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; +import { IMessenger } from "../../protocol/messenger"; import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; import { GlobalContext } from "../../util/GlobalContext"; -import { IMessenger } from "../../protocol/messenger"; import { editConfigJson, getDocsSqlitePath, @@ -26,6 +26,7 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; +import { ConfigResult } from "../../config/load"; import { Article, chunkArticle, pageToArticle } from "./article"; import DocsCrawler from "./DocsCrawler"; import { runLanceMigrations, runSqliteMigrations } from "./migrations"; @@ -123,8 +124,8 @@ export default class DocsService { // Initialization - load config and attach config listener private async init(configHandler: ConfigHandler) { - const config = await configHandler.loadConfig(); - await this.handleConfigUpdate({ config }); + const result = await configHandler.loadConfig(); + await this.handleConfigUpdate(result); configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); } @@ -247,9 +248,7 @@ export default class DocsService { private async handleConfigUpdate({ config: newConfig, - }: { - config: ContinueConfig | undefined; - }) { + }: ConfigResult) { if (newConfig) { const oldConfig = this.config; this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 9a7d85510..e05ce1bc4 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -20,6 +20,7 @@ import type { SiteIndexingConfig, ToolCall, } from "../"; +import { ConfigResult } from "../config/load"; export type ProtocolGeneratorType = AsyncGenerator<{ done?: boolean; @@ -63,10 +64,13 @@ export type ToCoreFromIdeOrWebviewProtocol = { "config/ideSettingsUpdate": [IdeSettings, void]; "config/getSerializedProfileInfo": [ undefined, - { config: BrowserSerializedContinueConfig; profileId: string }, + { + result: ConfigResult; + profileId: string; + }, ]; "config/deleteModel": [{ title: string }, void]; - "config/reload": [undefined, BrowserSerializedContinueConfig]; + "config/reload": [undefined, ConfigResult]; "config/listProfiles": [undefined, ProfileDescription[]]; "config/openProfile": [{ profileId: string | undefined }, void]; "context/getContextItems": [ diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 65ecde912..11512fa2c 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,3 +1,4 @@ +import { ConfigResult } from "../config/load.js"; import { ConfigValidationError } from "../config/validation.js"; import type { @@ -10,7 +11,10 @@ import type { export type ToWebviewFromIdeOrCoreProtocol = { configUpdate: [ - { config: BrowserSerializedContinueConfig; profileId: string }, + { + result: ConfigResult; + profileId: string; + }, void, ]; configError: [ConfigValidationError[] | undefined, void]; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 690063628..b83d3d380 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -335,7 +335,10 @@ const getCommandsMap: ( onlyOneInsertion?: boolean, range?: vscode.Range, ) { - const config = await configHandler.loadConfig(); + const { config } = await configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } const defaultModelTitle = await sidebar.webviewProtocol.request( "getDefaultModelTitle", @@ -867,7 +870,7 @@ const getCommandsMap: ( const config = vscode.workspace.getConfiguration(EXTENSION_NAME); const quickPick = vscode.window.createQuickPick(); const autocompleteModels = - (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; + (await configHandler.loadConfig()).config?.tabAutocompleteModels ?? []; let selected = new GlobalContext().get("selectedTabAutocompleteModel"); if ( diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index ac3f7fbf7..4ff02a736 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -149,7 +149,7 @@ export class VsCodeExtension { this.configHandler.reloadConfig.bind(this.configHandler), ); - this.configHandler.loadConfig().then((config) => { + this.configHandler.loadConfig().then(({ config }) => { const { verticalDiffCodeLens } = registerAllCodeLensProviders( context, this.verticalDiffManager.fileUriToCodeLens, @@ -168,9 +168,9 @@ export class VsCodeExtension { } else if (newConfig) { setupStatusBar(undefined, undefined, false); - const serialized = await this.configHandler.getSerializedConfig(); + const result = await this.configHandler.getSerializedConfig(); this.sidebar.webviewProtocol?.request("configUpdate", { - config: serialized.config!, // <-- TODO + result, profileId: this.configHandler.currentProfile.profileId, }); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 2b88fbca6..52238cc1e 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -171,7 +171,12 @@ export class VsCodeMessenger { // Get LLM from config const configHandler = await configHandlerPromise; - const config = await configHandler.loadConfig(); + const { config } = await configHandler.loadConfig(); + + if (!config) { + vscode.window.showErrorMessage("Config not loaded"); + return; + } let llm = getModelByRole(config, "applyCodeBlock"); diff --git a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts index ec168de53..9138fba8b 100644 --- a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts +++ b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts @@ -74,7 +74,7 @@ function registerQuickActionsProvider( export function registerAllCodeLensProviders( context: vscode.ExtensionContext, editorToVerticalDiffCodeLens: Map, - config: ContinueConfig, + config: ContinueConfig | undefined, ) { if (verticalPerLineCodeLensProvider) { verticalPerLineCodeLensProvider.dispose(); @@ -110,11 +110,13 @@ export function registerAllCodeLensProviders( new providers.SuggestionsCodeLensProvider(), ); - registerQuickActionsProvider(config, context); + if (config) { + registerQuickActionsProvider(config, context); - subscribeToVSCodeQuickActionsSettings(() => - registerQuickActionsProvider(config, context), - ); + subscribeToVSCodeQuickActionsSettings(() => + registerQuickActionsProvider(config, context), + ); + } context.subscriptions.push(verticalPerLineCodeLensProvider); context.subscriptions.push(suggestionsCodeLensDisposable); diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index aefc7408f..09cf8e2cd 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -242,6 +242,10 @@ export class QuickEdit { path: string | undefined, ) => { const modelTitle = await this.getCurModelTitle(); + if (!modelTitle) { + throw new Error("No model selected"); + } + await this._streamEditWithInputAndContext(prompt, modelTitle); this.openAcceptRejectMenu(prompt, path); }; @@ -258,12 +262,15 @@ export class QuickEdit { /** * Gets the model title the user has chosen, or their default model */ - private async getCurModelTitle() { + private async getCurModelTitle(): Promise { if (this._curModelTitle) { return this._curModelTitle; } - const config = await this.configHandler.loadConfig(); + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return undefined; + } return ( getModelByRole(config, "inlineEdit")?.title ?? @@ -517,7 +524,10 @@ export class QuickEdit { editor: vscode.TextEditor; params: QuickEditShowParams | undefined; }) { - const config = await this.configHandler.loadConfig(); + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } let prompt: string | undefined; switch (selectedLabel) { diff --git a/extensions/vscode/src/util/loadAutocompleteModel.ts b/extensions/vscode/src/util/loadAutocompleteModel.ts index b4aa9289b..fda69f023 100644 --- a/extensions/vscode/src/util/loadAutocompleteModel.ts +++ b/extensions/vscode/src/util/loadAutocompleteModel.ts @@ -34,7 +34,11 @@ export class TabAutocompleteModel { async get() { if (!this._llm) { - const config = await this.configHandler.loadConfig(); + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return undefined; + } + if (config.tabAutocompleteModels?.length) { const selected = this.globalContext.get("selectedTabAutocompleteModel"); if (selected) { diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 5534fbc3b..65d72557c 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -3,8 +3,9 @@ import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { BrowserSerializedContinueConfig } from "core"; +import { ConfigResult } from "core/config/load"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; -import { setConfig, setConfigError } from "../redux/slices/configSlice"; +import { setConfigError, setConfigResult } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { updateDocsSuggestions } from "../redux/slices/miscSlice"; import { @@ -33,20 +34,23 @@ function useSetup() { const handleConfigUpdate = useCallback( async ( initial: boolean, - result: { config: BrowserSerializedContinueConfig; profileId: string }, + result: { + result: ConfigResult; + profileId: string; + }, ) => { - const { config, profileId } = result; + const { result: configResult, profileId } = result; if (initial && hasLoadedConfig.current) { return; } hasLoadedConfig.current = true; - dispatch(setConfig(config)); + dispatch(setConfigResult(configResult)); dispatch(setSelectedProfileId(profileId)); // Perform any actions needed with the config - if (config.ui?.fontSize) { - setLocalStorage("fontSize", config.ui.fontSize); - document.body.style.fontSize = `${config.ui.fontSize}px`; + if (configResult.config?.ui?.fontSize) { + setLocalStorage("fontSize", configResult.config.ui.fontSize); + document.body.style.fontSize = `${configResult.config.ui.fontSize}px`; } }, [dispatch, hasLoadedConfig], @@ -61,6 +65,7 @@ function useSetup() { if (result.status === "error") { return; } + console.log("Config loaded", result.content); await handleConfigUpdate(initial, result.content); }, [ideMessenger, handleConfigUpdate], diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 95c7e3e8a..35e530e47 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -1,5 +1,6 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { BrowserSerializedContinueConfig } from "core"; +import { ConfigResult } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { DEFAULT_MAX_TOKENS } from "core/llm/constants"; @@ -33,10 +34,19 @@ export const configSlice = createSlice({ name: "config", initialState, reducers: { - setConfig: ( + setConfigResult: ( state, - { payload: config }: PayloadAction, + { + payload: result, + }: PayloadAction>, ) => { + const { config, errors } = result; + state.configError = errors; + + if (!config) { + return; + } + const defaultModelTitle = config.models.find((model) => model.title === state.defaultModelTitle) ?.title || @@ -83,7 +93,7 @@ export const configSlice = createSlice({ }, }); -export const { setDefaultModel, setConfig, setConfigError } = +export const { setDefaultModel, setConfigResult, setConfigError } = configSlice.actions; export const { From 57afa403a8cd5c10286f93314dfd90969535cb47 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 24 Dec 2024 11:07:04 -0800 Subject: [PATCH 33/64] improv: contain chat image to a max height --- gui/src/components/mainInput/TipTapEditor.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 24f874eb6..8f7191e18 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -340,6 +340,10 @@ function TipTapEditor(props: TipTapEditorProps) { }); return [plugin]; }, + }).configure({ + HTMLAttributes: { + class: "editor-image bg-black object-contain max-h-[250px] w-full", + }, }), Placeholder.configure({ placeholder: getPlaceholderText( From 38a7c3a9a20ef9a723d226c3acb56ddb83cc85fe Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 24 Dec 2024 14:42:59 -0500 Subject: [PATCH 34/64] fix mcp decoding for tools --- core/context/mcp/index.ts | 3 ++- core/tools/callTool.ts | 5 ++++- extensions/vscode/package-lock.json | 4 ++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index bcf11492f..e214b1e02 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -7,6 +7,7 @@ import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../.."; import { constructMcpSlashCommand } from "../../commands/slash/mcp"; import { ConfigValidationError } from "../../config/validation"; +import { encodeMCPToolUri } from "../../tools/callTool"; import MCPContextProvider from "../providers/MCPContextProvider"; export class MCPManagerSingleton { @@ -172,7 +173,7 @@ class MCPConnection { readonly: false, type: "function", wouldLikeTo: `use the ${tool.name} tool`, - uri: `mcp://${tool.name}`, + uri: encodeMCPToolUri(mcpId, tool.name), })); config.tools = [...config.tools, ...continueTools]; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 3de329a0b..2bca7c2d1 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -44,7 +44,10 @@ export function decodeMCPToolUri(uri: string): [string, string] | null { if (url.protocol !== "mcp:") { return null; } - return [decodeURIComponent(url.hostname), decodeURIComponent(url.pathname)]; + return [ + decodeURIComponent(url.hostname), + decodeURIComponent(url.pathname).slice(1), // to remove leading '/' + ]; } async function callToolFromUri( diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index ca4edfc38..8f5cad8a0 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.246", + "version": "0.9.247", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.246", + "version": "0.9.247", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", From 2b5ed9e59b0b2ff5bdc3e83b7ee2cd1ced21985e Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 24 Dec 2024 14:45:02 -0500 Subject: [PATCH 35/64] bump package.json --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 4cb023717..6a416096c 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": "0.9.247", + "version": "0.9.248", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From 955117019366c6d286526478497d62cca6c11d5f Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 24 Dec 2024 17:17:09 -0500 Subject: [PATCH 36/64] fix tsc err --- core/tools/callTool.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 2bca7c2d1..706fa57d9 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -55,6 +55,7 @@ async function callToolFromUri( args: any, extras: ToolExtras, ): Promise { + // @ts-ignore const canParse = URL.canParse(uri); if (!canParse) { throw new Error(`Invalid URI: ${uri}`); From b94ccc6db557f705ba4f810ed56c55ce21f383dd Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 24 Dec 2024 12:32:19 -0800 Subject: [PATCH 37/64] fix: scroll to the bottom on history change --- extensions/vscode/e2e/tests/GUI.test.ts | 62 ++++++++++++++ gui/src/components/ChatScrollAnchor.tsx | 38 --------- gui/src/pages/gui/Chat.tsx | 105 +++++++++++++----------- 3 files changed, 118 insertions(+), 87 deletions(-) delete mode 100644 gui/src/components/ChatScrollAnchor.tsx diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index d4c005eae..b5e3cabc3 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -193,6 +193,68 @@ describe("GUI Test", () => { }); describe("Chat Paths", () => { + it("Send many messages → chat auto scrolls → go to history → open previous chat → it is scrolled to the bottom", async () => { + for (let i = 0; i <= 20; i++) { + const { userMessage, llmResponse } = + TestUtils.generateTestMessagePair(i); + await GUIActions.sendMessage({ + view, + message: userMessage, + inputFieldIndex: i, + }); + const response = await TestUtils.waitForSuccess(() => + GUISelectors.getThreadMessageByText(view, llmResponse), + ); + + const viewportHeight = await driver.executeScript( + "return window.innerHeight", + ); + + const isInViewport = await driver.executeScript( + ` + const rect = arguments[0].getBoundingClientRect(); + return ( + rect.top >= 0 && + rect.bottom <= ${viewportHeight} + ); + `, + response, + ); + + expect(isInViewport).to.eq(true); + } + + await view.switchBack(); + + await (await GUISelectors.getHistoryNavButton(view)).click(); + await GUIActions.switchToReactIframe(); + TestUtils.waitForSuccess(async () => { + await (await GUISelectors.getNthHistoryTableRow(view, 0)).click(); + }); + + const { llmResponse } = TestUtils.generateTestMessagePair(20); + const response = await TestUtils.waitForSuccess(() => + GUISelectors.getThreadMessageByText(view, llmResponse), + ); + + const viewportHeight = await driver.executeScript( + "return window.innerHeight", + ); + + const isInViewport = await driver.executeScript( + ` + const rect = arguments[0].getBoundingClientRect(); + return ( + rect.top >= 0 && + rect.bottom <= ${viewportHeight} + ); + `, + response, + ); + + expect(isInViewport).to.eq(true); + }).timeout(DEFAULT_TIMEOUT.XL * 1000); + it("Open chat and send message → press arrow up and arrow down to cycle through messages → submit another message → press arrow up and arrow down to cycle through messages", async () => { await GUIActions.sendMessage({ view, diff --git a/gui/src/components/ChatScrollAnchor.tsx b/gui/src/components/ChatScrollAnchor.tsx deleted file mode 100644 index 9b32e7283..000000000 --- a/gui/src/components/ChatScrollAnchor.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { useEffect } from "react"; -import { useInView } from "react-intersection-observer"; -import { vscBackground } from "."; - -interface ChatScrollAnchorProps { - trackVisibility: boolean; - isAtBottom: boolean; - scrollAreaRef: React.RefObject; -} - -export function ChatScrollAnchor({ - trackVisibility, - isAtBottom, - scrollAreaRef, -}: ChatScrollAnchorProps) { - const { ref, inView, entry } = useInView(); - - useEffect(() => { - if (isAtBottom && trackVisibility && !inView) { - if (!scrollAreaRef.current) return; - - const scrollAreaElement = scrollAreaRef.current; - - scrollAreaElement.scrollTop = - scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight; - } - }, [inView, entry, isAtBottom, trackVisibility]); - - return ( -
- ); -} diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index b7748bf22..8e11e39e5 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -19,7 +19,6 @@ import { lightGray, vscBackground, } from "../../components"; -import { ChatScrollAnchor } from "../../components/ChatScrollAnchor"; import CodeToEditCard from "../../components/CodeToEditCard"; import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; import { useFindWidget } from "../../components/find/FindWidget"; @@ -75,6 +74,7 @@ import { loadLastSession, saveCurrentSession, } from "../../redux/thunks/session"; +import { C } from "core/autocomplete/constants/AutocompleteLanguageInfo"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -132,6 +132,58 @@ function fallbackRender({ error, resetErrorBoundary }: any) { ); } +const useAutoScroll = ( + ref: React.RefObject, + history: unknown[], +) => { + const [userHasScrolled, setUserHasScrolled] = useState(false); + + useEffect(() => { + if (history.length) { + setUserHasScrolled(false); + } + }, [history.length]); + + useEffect(() => { + if (!ref.current || history.length === 0) return; + + const handleScroll = () => { + const elem = ref.current; + if (!elem) return; + + const isAtBottom = + Math.abs(elem.scrollHeight - elem.scrollTop - elem.clientHeight) < 1; + + /** + * We stop auto scrolling if a user manually scrolled up. + * We resume auto scrolling if a user manually scrolled to the bottom. + */ + setUserHasScrolled(!isAtBottom); + }; + + const resizeObserver = new ResizeObserver(() => { + const elem = ref.current; + if (!elem || userHasScrolled) return; + elem.scrollTop = elem.scrollHeight; + }); + + ref.current.addEventListener("scroll", handleScroll); + + // Observe the container + resizeObserver.observe(ref.current); + + // Observe all immediate children + Array.from(ref.current.children).forEach((child) => { + resizeObserver.observe(child); + }); + + return () => { + resizeObserver.disconnect(); + ref.current?.removeEventListener("scroll", handleScroll); + }; + }, [ref, history.length, userHasScrolled]); +}; + export function Chat() { const posthog = usePostHog(); const dispatch = useAppDispatch(); @@ -147,7 +199,6 @@ export function Chat() { const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); const mainTextInputRef = useRef(null); const stepsDivRef = useRef(null); - const [isAtBottom, setIsAtBottom] = useState(false); const history = useAppSelector((state) => state.session.history); const showChatScrollbar = useAppSelector( (state) => state.config.config.ui?.showChatScrollbar, @@ -168,34 +219,6 @@ export function Chat() { selectIsSingleRangeEditOrInsertion, ); const lastSessionId = useAppSelector((state) => state.session.lastSessionId); - const snapToBottom = useCallback(() => { - if (!stepsDivRef.current) return; - const elem = stepsDivRef.current; - elem.scrollTop = elem.scrollHeight - elem.clientHeight; - - setIsAtBottom(true); - }, [stepsDivRef, setIsAtBottom]); - - const smoothScrollToBottom = useCallback(async () => { - if (!stepsDivRef.current) return; - const elem = stepsDivRef.current; - elem.scrollTo({ - top: elem.scrollHeight - elem.clientHeight, - behavior: "smooth", - }); - - setIsAtBottom(true); - }, [stepsDivRef, setIsAtBottom]); - - useEffect(() => { - if (isStreaming) snapToBottom(); - }, [isStreaming, snapToBottom]); - - // useEffect(() => { - // setTimeout(() => { - // smoothScrollToBottom(); - // }, 400); - // }, [smoothScrollToBottom, state.sessionId]); useEffect(() => { // Cmd + Backspace to delete current step @@ -215,18 +238,6 @@ export function Chat() { }; }, [isStreaming]); - const handleScroll = () => { - // Temporary fix to account for additional height when code blocks are added - const OFFSET_HERUISTIC = 300; - if (!stepsDivRef.current) return; - - const { scrollTop, scrollHeight, clientHeight } = stepsDivRef.current; - const atBottom = - scrollHeight - clientHeight <= scrollTop + OFFSET_HERUISTIC; - - setIsAtBottom(atBottom); - }; - const { widget, highlights } = useFindWidget(stepsDivRef); const sendInput = useCallback( @@ -340,6 +351,8 @@ export function Chat() { const showScrollbar = showChatScrollbar || window.innerHeight > 5000; + useAutoScroll(stepsDivRef, history); + return ( <> {isInEditMode && ( @@ -356,14 +369,13 @@ export function Chat() { 0 ? "flex-1" : ""}`} - onScroll={handleScroll} > {highlights} {history.map((item, index: number) => (
))} -
From 3f991b41b6d3035889dd6cf402febac7903ab07d Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 24 Dec 2024 14:29:42 -0800 Subject: [PATCH 38/64] improv: clean up code --- gui/src/pages/gui/Chat.tsx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 8e11e39e5..de8453445 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -70,11 +70,7 @@ import ConfigErrorIndicator from "./ConfigError"; import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; import ToolOutput from "./ToolCallDiv/ToolOutput"; -import { - loadLastSession, - saveCurrentSession, -} from "../../redux/thunks/session"; -import { C } from "core/autocomplete/constants/AutocompleteLanguageInfo"; +import { loadLastSession } from "../../redux/thunks/session"; const StopButton = styled.div` background-color: ${vscBackground}; From e270b206808a35d5156f851fe66c1e1d13752812 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E4=BF=8A=E6=9D=B0?= Date: Wed, 25 Dec 2024 17:37:49 +0800 Subject: [PATCH 39/64] Remove the extra "+" sign from the IDEA shortcut --- docs/docs/getting-started/install.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/getting-started/install.md b/docs/docs/getting-started/install.md index 20aa52baa..3729edbfd 100644 --- a/docs/docs/getting-started/install.md +++ b/docs/docs/getting-started/install.md @@ -18,7 +18,7 @@ If you have any problems, see the [troubleshooting guide](troubleshooting.md) or ## JetBrains -1. Open your JetBrains IDE and open **Settings** using Ctrl + +Alt + S +1. Open your JetBrains IDE and open **Settings** using Ctrl + Alt + S 2. Select **Plugins** on the sidebar and search for "Continue" in the marketplace 3. Click `Install`, which will cause the Continue logo to show up on the right toolbar From decd04eddd4965b9f76c7a9a3abd276d8d2e1692 Mon Sep 17 00:00:00 2001 From: liuk Date: Wed, 25 Dec 2024 23:03:53 +0800 Subject: [PATCH 40/64] fix: Skip duplicate checks at document end or blank text Prevent autocomplete from truncating when the cursor is at the end of the document or when the text after the cursor is blank. --- .../autocomplete/AutocompleteService.kt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index 6279e03f7..2dc6ba021 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -120,6 +120,10 @@ class AutocompleteService(private val project: Project) { return ApplicationManager.getApplication().runReadAction { val document = editor.document val caretOffset = editor.caretModel.offset + + // Don't care about it if it's at the end of the document + if (caretOffset == document.textLength) return@runReadAction completion + val N = 10 var textAfterCursor = if (caretOffset + N <= document.textLength) { document.getText(com.intellij.openapi.util.TextRange(caretOffset, caretOffset + N)) @@ -127,6 +131,9 @@ class AutocompleteService(private val project: Project) { document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength)) } + // Avoid truncating the completion text when the text after the cursor is blank + if (textAfterCursor.isBlank()) return@runReadAction completion + // Determine the index of a newline character within the text following the cursor. val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n') // If a newline character is found and the current line is not empty, truncate the text at that point. From f6304057970b7326d462e56b60721657e75a3892 Mon Sep 17 00:00:00 2001 From: Guspan Tanadi <36249910+guspan-tanadi@users.noreply.github.com> Date: Thu, 26 Dec 2024 12:31:16 +0700 Subject: [PATCH 41/64] docs(autocomplete): prompts example links --- docs/docs/customize/deep-dives/autocomplete.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 35789710c..4aa5f768d 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -91,7 +91,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa ### I want better completions, should I use GPT-4? -Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance. +Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templating/AutocompleteTemplate.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance. ### I'm not seeing any completions From 1a1585e8800cb8f33425b6ddb4d83d107da0c7b9 Mon Sep 17 00:00:00 2001 From: Prajna Kandarpa Date: Fri, 27 Dec 2024 13:25:21 +0530 Subject: [PATCH 42/64] minor documentationtip for aws bedrock --- .../model-providers/top-level/bedrock.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/docs/customize/model-providers/top-level/bedrock.md b/docs/docs/customize/model-providers/top-level/bedrock.md index fb88d5ae0..67d919a2f 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.md +++ b/docs/docs/customize/model-providers/top-level/bedrock.md @@ -22,6 +22,22 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. ] } ``` +> If you run into the following error when connecting to the new Claude 3.5 Sonnet 2 models from AWS - `400 Invocation of model ID anthropic.claude-3-5-sonnet-20241022-v2:0 with on-demand throughput isn’t supported. Retry your request with the ID or ARN of an inference profile that contains this model.` + +> You can fix this using the following config.json +```json title="config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "bedrock", + "model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0", + "region": "us-east-1", + "profile": "bedrock" + } + ] +} +``` ## Autocomplete model From 72d4ad039f0275e1a3cfc1946b009db502f7d05a Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 30 Dec 2024 11:52:27 -0600 Subject: [PATCH 43/64] bugfix(JB): handle disposed editor tooltips --- .../listeners/ContinuePluginSelectionListener.kt | 4 ++++ 1 file changed, 4 insertions(+) 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 4676cae33..24d9787f5 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 @@ -28,6 +28,10 @@ class ContinuePluginSelectionListener( private var lastActiveEditor: Editor? = null override fun selectionChanged(e: SelectionEvent) { + if (e.editor.isDisposed || e.editor.project?.isDisposed == true) { + return + } + debouncer.debounce { handleSelection(e) } } From ddf19053b1b4afb37fc18a60ddd7b6abc86e27c8 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 30 Dec 2024 16:47:34 -0600 Subject: [PATCH 44/64] bugfix(GUI): broken Chinese input w/ codeblock --- gui/src/components/mainInput/CodeBlockComponent.tsx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index f8c359e14..0a0e7996b 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -1,4 +1,4 @@ -import { NodeViewWrapper } from "@tiptap/react"; +import { NodeViewWrapper, NodeViewWrapperProps } from "@tiptap/react"; import { ContextItemWithId } from "core"; import { vscBadgeBackground } from ".."; import CodeSnippetPreview from "../markdown/CodeSnippetPreview"; @@ -13,8 +13,15 @@ export const CodeBlockComponent = (props: any) => { // const isFirstContextItem = item.id === contextItems[0]?.id; const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now + // Not setting this as a "p" will cause issues with foreign keyboards + // See https://github.com/continuedev/continue/issues/3199 + const nodeViewWrapperTag: NodeViewWrapperProps["as"] = "p"; + return ( - + Date: Mon, 30 Dec 2024 17:19:56 -0600 Subject: [PATCH 45/64] bugfix(GUI): increase z-index on tippy mentionlist --- gui/src/components/mainInput/TipTapEditor.tsx | 17 +++++++---------- gui/src/components/mainInput/getSuggestion.ts | 4 +++- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index bcd7328a2..0312b3f53 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -175,6 +175,8 @@ interface TipTapEditorProps { historyKey: string; } +export const TIPPY_DIV_ID = "tippy-js-div"; + function TipTapEditor(props: TipTapEditorProps) { const dispatch = useAppDispatch(); @@ -976,22 +978,17 @@ function TipTapEditor(props: TipTapEditorProps) { {showDragOverMsg && modelSupportsImages( - defaultModel.provider, - defaultModel.model, - defaultModel.title, - defaultModel.capabilities, + defaultModel?.provider || "", + defaultModel?.model || "", + defaultModel?.title, + defaultModel?.capabilities, ) && ( <> Hold ⇧ to drop image )} -
+
); } diff --git a/gui/src/components/mainInput/getSuggestion.ts b/gui/src/components/mainInput/getSuggestion.ts index 41e6338c1..5ec1f778a 100644 --- a/gui/src/components/mainInput/getSuggestion.ts +++ b/gui/src/components/mainInput/getSuggestion.ts @@ -5,6 +5,7 @@ import tippy from "tippy.js"; import { IIdeMessenger } from "../../context/IdeMessenger"; import MentionList from "./MentionList"; import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "./types"; +import { TIPPY_DIV_ID } from "./TipTapEditor"; function getSuggestion( items: (props: { query: string }) => Promise, @@ -37,7 +38,8 @@ function getSuggestion( return; } - const container = document.getElementById("tippy-js-div"); + const container = document.getElementById(TIPPY_DIV_ID); + if (!container) { console.log("no container"); return; From 54e41d6de6eb7685425ec79241894a787a4260b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 17:25:22 +0100 Subject: [PATCH 46/64] Update model-setup.md --- docs/docs/autocomplete/model-setup.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docs/autocomplete/model-setup.md b/docs/docs/autocomplete/model-setup.md index 8aae88c75..221c17ddd 100644 --- a/docs/docs/autocomplete/model-setup.md +++ b/docs/docs/autocomplete/model-setup.md @@ -31,14 +31,14 @@ For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers ```json title="config.json"" { "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B", - "model": "qwen2.5-coder:1.5b", + "title": "Qwen2.5-Coder 1.5B Base", + "model": "qwen2.5-coder:1.5b-base", "provider": "ollama" } } ``` -Have more compute? Use `qwen2.5-coder:7b` for potentially higher-quality suggestions. +Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality suggestions. :::note From 11b657a1546d2e03814205a4de0158ccdf65bf15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 17:30:37 +0100 Subject: [PATCH 47/64] Update model-setup.md Fixed typo for LM studio --- docs/docs/autocomplete/model-setup.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/autocomplete/model-setup.md b/docs/docs/autocomplete/model-setup.md index 221c17ddd..fc5233baa 100644 --- a/docs/docs/autocomplete/model-setup.md +++ b/docs/docs/autocomplete/model-setup.md @@ -42,7 +42,7 @@ Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality su :::note -For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/wen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration. +For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration. ::: From 8c6e33ad803ac5009b0ce7d6280ad05ac6dace03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 17:31:32 +0100 Subject: [PATCH 48/64] Update autocomplete.md --- docs/docs/customize/model-types/autocomplete.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/model-types/autocomplete.md b/docs/docs/customize/model-types/autocomplete.md index d85920605..7f5abc8e2 100644 --- a/docs/docs/customize/model-types/autocomplete.md +++ b/docs/docs/customize/model-types/autocomplete.md @@ -13,4 +13,4 @@ In Continue, these models are used to display inline [Autocomplete](../../autoco If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) or [Vertex AI](../model-providers/top-level/vertexai.md#autocomplete-model). -If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). +If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B-base` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). From fb9db1e12883435fad5cc6610312ff3240ef6803 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 17:32:25 +0100 Subject: [PATCH 49/64] Update ollama.md --- docs/docs/customize/model-providers/top-level/ollama.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docs/customize/model-providers/top-level/ollama.md b/docs/docs/customize/model-providers/top-level/ollama.md index ed96ac385..c307a9344 100644 --- a/docs/docs/customize/model-providers/top-level/ollama.md +++ b/docs/docs/customize/model-providers/top-level/ollama.md @@ -23,14 +23,14 @@ We recommend configuring **Llama3.1 8B** as your chat model. ## Autocomplete model -We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. +We recommend configuring **Qwen2.5-Coder 1.5B-base** as your autocomplete model. ```json title="config.json" { "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B", + "title": "Qwen2.5-Coder 1.5B-base", "provider": "ollama", - "model": "qwen2.5-coder:1.5b" + "model": "qwen2.5-coder:1.5b-base" } } ``` From fa18259a34a3b3940fbbe1a019136b94aa8c260f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 21:08:48 +0100 Subject: [PATCH 50/64] Update README.md --- core/autocomplete/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md index 1136b54ab..ab6e9adfb 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -7,7 +7,7 @@ Continue now provides support for tab autocomplete in [VS Code](https://marketpl We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model: ```bash -ollama run qwen2.5-coder:1.5b +ollama run qwen2.5-coder:1.5b-base ``` Once it has been downloaded, you should begin to see completions in VS Code. @@ -101,7 +101,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa "tabAutocompleteModel": { "title": "Tab Autocomplete Model", "provider": "ollama", - "model": "qwen2.5-coder:1.5b", + "model": "qwen2.5-coder:1.5b-base", "apiBase": "https://" }, "tabAutocompleteOptions": { @@ -123,9 +123,9 @@ Follow these steps to ensure that everything is set up correctly: 1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar). 2. Make sure you have downloaded Ollama. -3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded. +3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. -5. Make sure that you aren't also using another Ollama model for chat. This will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. +5. If you are using another Ollama model for chat and your resources are limited, this will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. A resolution for this could be using the same model for chat and autocomplete. 6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). 7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. From 96200c094f89141ac33e10e9daa0a78ff2ef30e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 21:22:10 +0100 Subject: [PATCH 51/64] removed base from title --- docs/docs/autocomplete/model-setup.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/autocomplete/model-setup.md b/docs/docs/autocomplete/model-setup.md index fc5233baa..2312123a0 100644 --- a/docs/docs/autocomplete/model-setup.md +++ b/docs/docs/autocomplete/model-setup.md @@ -31,7 +31,7 @@ For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers ```json title="config.json"" { "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B Base", + "title": "Qwen2.5-Coder 1.5B", "model": "qwen2.5-coder:1.5b-base", "provider": "ollama" } From 2966c9c57d7b4317504f1e8952d2367fc3d221a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 21:24:21 +0100 Subject: [PATCH 52/64] removed base since its a name and not specific model --- docs/docs/customize/model-types/autocomplete.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/model-types/autocomplete.md b/docs/docs/customize/model-types/autocomplete.md index 7f5abc8e2..d85920605 100644 --- a/docs/docs/customize/model-types/autocomplete.md +++ b/docs/docs/customize/model-types/autocomplete.md @@ -13,4 +13,4 @@ In Continue, these models are used to display inline [Autocomplete](../../autoco If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) or [Vertex AI](../model-providers/top-level/vertexai.md#autocomplete-model). -If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B-base` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). +If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). From 5516ba86ff0cbed6b0777380c273805094c9ac20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 21:25:26 +0100 Subject: [PATCH 53/64] removed base from title --- docs/docs/customize/model-providers/top-level/ollama.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/customize/model-providers/top-level/ollama.md b/docs/docs/customize/model-providers/top-level/ollama.md index c307a9344..e1f3e53e8 100644 --- a/docs/docs/customize/model-providers/top-level/ollama.md +++ b/docs/docs/customize/model-providers/top-level/ollama.md @@ -23,12 +23,12 @@ We recommend configuring **Llama3.1 8B** as your chat model. ## Autocomplete model -We recommend configuring **Qwen2.5-Coder 1.5B-base** as your autocomplete model. +We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model. ```json title="config.json" { "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5B-base", + "title": "Qwen2.5-Coder 1.5B", "provider": "ollama", "model": "qwen2.5-coder:1.5b-base" } From abf1d89a3966498d7529ae2ca1747ac6bb1f9b2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20=C3=96berg?= Date: Wed, 1 Jan 2025 22:24:09 +0100 Subject: [PATCH 54/64] added -base to the qwen-modelse --- docs/docs/customize/deep-dives/autocomplete.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 4aa5f768d..221a6d49f 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -23,7 +23,7 @@ If you want to have the best autocomplete experience, we recommend using Codestr If you'd like to run your autocomplete model locally, we recommend using Ollama. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model: ```bash -ollama run qwen2.5-coder:1.5b +ollama run qwen2.5-coder:1.5b-base ``` Once it has been downloaded, you should begin to see completions in VS Code. @@ -37,7 +37,7 @@ All of the configuration options available for chat models are available to use "tabAutocompleteModel": { "title": "Tab Autocomplete Model", "provider": "ollama", - "model": "qwen2.5-coder:1.5b", + "model": "qwen2.5-coder:1.5b-base", "apiBase": "https://" }, ... @@ -76,7 +76,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa "tabAutocompleteModel": { "title": "Tab Autocomplete Model", "provider": "ollama", - "model": "qwen2.5-coder:1.5b", + "model": "qwen2.5-coder:1.5b-base", "apiBase": "https://" }, "tabAutocompleteOptions": { @@ -99,7 +99,7 @@ Follow these steps to ensure that everything is set up correctly: 1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar, and in JetBrains by going to Settings -> Tools -> Continue). 2. Make sure you have downloaded Ollama. -3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded. +3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. 5. Check the output of the logs to find any potential errors: cmd/ctrl + shift + P -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains. 6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl + , then search for this and check the box) From abfffd831abe960b4881472b2c7c3ca94f187a81 Mon Sep 17 00:00:00 2001 From: "Johnny.H" Date: Thu, 2 Jan 2025 15:53:12 +0800 Subject: [PATCH 55/64] fix `renderInlineAs` not working in `HttpContextProvider` --- core/context/providers/HttpContextProvider.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/context/providers/HttpContextProvider.ts b/core/context/providers/HttpContextProvider.ts index 05a50e15d..7b7228eee 100644 --- a/core/context/providers/HttpContextProvider.ts +++ b/core/context/providers/HttpContextProvider.ts @@ -22,6 +22,9 @@ class HttpContextProvider extends BaseContextProvider { this.options.description || "Retrieve a context item from a custom server", type: "normal", + renderInlineAs: + this.options.renderInlineAs || + HttpContextProvider.description.renderInlineAs, }; } From 0001e275e14b26aaabadbeb30ac4fdeb843d6122 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 2 Jan 2025 15:29:12 -0500 Subject: [PATCH 56/64] update reference --- docs/docs/reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 527820556..b61357649 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -88,7 +88,7 @@ Specifies options for tab autocompletion behavior. - `debounceDelay`: Delay (in ms) before triggering autocomplete. - `maxSuffixPercentage`: Maximum percentage of prompt for suffix. - `prefixPercentage`: Percentage of input for prefix. -- `template`: Template string for autocomplete, using Mustache templating. +- `template`: Template string for autocomplete, using Mustache templating. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables. - `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). - `useCache`: If `true`, caches completions. - `onlyMyCode`: If `true`, only includes code within the repository. From 9cc844fb178a77667a4cd49b0d671f9631af67af Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 2 Jan 2025 15:33:08 -0500 Subject: [PATCH 57/64] update config_schema.json --- extensions/vscode/config_schema.json | 108 +++++++++++++-------------- 1 file changed, 54 insertions(+), 54 deletions(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f2c98642f..c9df4e976 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2805,10 +2805,7 @@ "type": "object", "properties": { "model": { - "enum": [ - "cohere.rerank-v3-5:0", - "amazon.rerank-v1:0" - ] + "enum": ["cohere.rerank-v3-5:0", "amazon.rerank-v1:0"] } }, "required": ["model"] @@ -3132,62 +3129,65 @@ "description": "Allow tool use. Currently only supported with Claude 3.5 Sonnet", "default": true }, - "modelContextProtocolServer": { - "type": "object", - "properties": { - "transport": { - "oneOf": [ - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["stdio"] - }, - "command": { - "type": "string" - }, - "args": { - "type": "array", - "items": { + "modelContextProtocolServers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "transport": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["stdio"] + }, + "command": { "type": "string" + }, + "args": { + "type": "array", + "items": { + "type": "string" + } } - } - }, - "required": ["type", "command", "args"] - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["websocket"] }, - "url": { - "type": "string", - "format": "uri" - } + "required": ["type", "command", "args"] }, - "required": ["type", "url"] - }, - { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": ["sse"] + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["websocket"] + }, + "url": { + "type": "string", + "format": "uri" + } }, - "url": { - "type": "string", - "format": "uri" - } + "required": ["type", "url"] }, - "required": ["type", "url"] - } - ] - } - }, - "required": ["transport"] + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["sse"] + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": ["type", "url"] + } + ] + } + }, + "required": ["transport"] + } } } } From 0cf152ede652d975fd774faa40494020c7514196 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 2 Jan 2025 17:41:28 -0600 Subject: [PATCH 58/64] feat: create SVG tooltip --- .../vscode/src/activation/InlineTipManager.ts | 427 ++++++++++++++++++ extensions/vscode/src/activation/activate.ts | 3 +- .../vscode/src/activation/inlineTips.ts | 122 ----- .../components/indexing/ChatIndexingPeeks.tsx | 2 +- package-lock.json | 8 + package.json | 3 + 6 files changed, 441 insertions(+), 124 deletions(-) create mode 100644 extensions/vscode/src/activation/InlineTipManager.ts delete mode 100644 extensions/vscode/src/activation/inlineTips.ts diff --git a/extensions/vscode/src/activation/InlineTipManager.ts b/extensions/vscode/src/activation/InlineTipManager.ts new file mode 100644 index 000000000..b335cc9dd --- /dev/null +++ b/extensions/vscode/src/activation/InlineTipManager.ts @@ -0,0 +1,427 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import { EXTENSION_NAME } from "core/control-plane/env"; +// @ts-ignore +import svgBuilder from "svg-builder"; +import * as vscode from "vscode"; + +import { getTheme } from "../util/getTheme"; +import { getMetaKeyLabel, getMetaKeyName } from "../util/util"; + +const SVG_CONFIG = { + stroke: "#999998", + strokeWidth: 1, + shortcutColor: "#999998", + filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))", + radius: 4, + leftMargin: 40, + debounceDelay: 500, + chatLabel: "Add to Chat", + chatShortcut: `${getMetaKeyLabel()}L`, + editLabel: "Edit", + editShortcut: `${getMetaKeyLabel()}I`, + + get fontSize() { + return Math.ceil( + (vscode.workspace.getConfiguration("editor").get("fontSize") ?? + 14) * 0.7, + ); + }, + get fontFamily() { + return ( + vscode.workspace.getConfiguration("editor").get("fontFamily") || + "helvetica" + ); + }, + get paddingY() { + return Math.ceil(this.fontSize * 0.4); + }, + get paddingX() { + return Math.ceil(this.fontSize * 0.8); + }, + get gap() { + return this.fontSize * 2.5; + }, + get tipWidth() { + return ( + this.editShortcutX + + this.getEstimatedTextWidth(this.editShortcut) + + this.paddingX + ); + }, + get tipHeight() { + return this.fontSize + this.paddingY * 2; + }, + get textY() { + return this.tipHeight / 2 + this.fontSize * 0.35; + }, + get chatLabelX() { + return this.paddingX; + }, + get chatShortcutX() { + return this.chatLabelX + this.getEstimatedTextWidth(this.chatLabel) + 4; + }, + get editLabelX() { + return this.chatShortcutX + this.gap; + }, + get editShortcutX() { + return this.editLabelX + this.getEstimatedTextWidth(this.editLabel) + 4; + }, + getEstimatedTextWidth(text: string): number { + return text.length * this.fontSize * 0.6; + }, +} as const; + +export class InlineTipManager { + private static instance: InlineTipManager; + + private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"]; + private readonly hideCommand = "continue.hideInlineTip"; + private svgTooltip: vscode.Uri | undefined = undefined; + + private debounceTimer: NodeJS.Timeout | undefined; + private lastActiveEditor?: vscode.TextEditor; + private theme = getTheme(); + private svgTooltipDecoration = this.createSvgTooltipDecoration(); + private emptyFileTooltipDecoration = this.createEmptyFileTooltipDecoration(); + + public static getInstance(): InlineTipManager { + if (!InlineTipManager.instance) { + InlineTipManager.instance = new InlineTipManager(); + } + return InlineTipManager.instance; + } + + private constructor() { + this.createSvgTooltip(); + this.setupSvgTipListeners(); + } + + public setupInlineTips(context: vscode.ExtensionContext) { + context.subscriptions.push( + vscode.window.onDidChangeTextEditorSelection((e) => { + this.handleSelectionChange(e); + }), + ); + + this.setupEmptyFileTips(context); + + context.subscriptions.push(this); + } + + public handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) { + const selection = e.selections[0]; + const editor = e.textEditor; + + if (selection.isEmpty || !this.shouldRenderTip(editor.document.uri)) { + editor.setDecorations(this.svgTooltipDecoration, []); + return; + } + + this.debouncedSelectionChange(editor, selection); + } + + public dispose() { + this.svgTooltipDecoration.dispose(); + this.emptyFileTooltipDecoration.dispose(); + + if (this.debounceTimer) { + clearTimeout(this.debounceTimer); + } + } + + private debouncedSelectionChange( + editor: vscode.TextEditor, + selection: vscode.Selection, + ) { + if (this.debounceTimer) { + clearTimeout(this.debounceTimer); + } + + this.debounceTimer = setTimeout(() => { + // Clear decoration from previous editor + if (this.lastActiveEditor && this.lastActiveEditor !== editor) { + this.lastActiveEditor.setDecorations(this.svgTooltipDecoration, []); + } + + this.lastActiveEditor = editor; + + this.updateTooltipPosition(editor, selection); + }, SVG_CONFIG.debounceDelay); + } + + private setupSvgTipListeners() { + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration("workbench.colorTheme")) { + this.theme = getTheme(); + this.createSvgTooltip(); + } + }); + + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration("editor.fontSize")) { + this.createSvgTooltip(); + } + }); + } + + private shouldRenderTip(uri: vscode.Uri): boolean { + const isAllowedUri = + !this.excludedURIPrefixes.some((prefix) => + uri.toString().startsWith(prefix), + ) && uri.scheme !== "comment"; + + const isEnabled = + !!vscode.workspace + .getConfiguration(EXTENSION_NAME) + .get("showInlineTip") === true; + + return isAllowedUri && isEnabled; + } + + private setupEmptyFileTips(context: vscode.ExtensionContext) { + context.subscriptions.push( + vscode.window.onDidChangeActiveTextEditor((editor) => { + if ( + editor?.document.getText() === "" && + this.shouldRenderTip(editor.document.uri) + ) { + editor.setDecorations(this.emptyFileTooltipDecoration, [ + { + range: new vscode.Range( + new vscode.Position(0, Number.MAX_VALUE), + new vscode.Position(0, Number.MAX_VALUE), + ), + }, + ]); + } + }), + ); + + context.subscriptions.push( + vscode.workspace.onDidChangeTextDocument((e) => { + if ( + e.document.getText() === "" && + this.shouldRenderTip(e.document.uri) + ) { + vscode.window.visibleTextEditors.forEach((editor) => { + editor.setDecorations(this.emptyFileTooltipDecoration, [ + { + range: new vscode.Range( + new vscode.Position(0, Number.MAX_VALUE), + new vscode.Position(0, Number.MAX_VALUE), + ), + }, + ]); + }); + } else { + vscode.window.visibleTextEditors.forEach((editor) => { + editor.setDecorations(this.emptyFileTooltipDecoration, []); + }); + } + }), + ); + } + + private createEmptyFileTooltipDecoration() { + return vscode.window.createTextEditorDecorationType({ + after: { + contentText: `Use ${getMetaKeyName()} + I to generate code`, + color: "#888", + margin: "2em 0 0 0", + fontStyle: "italic", + }, + }); + } + + private createSvgTooltipDecoration() { + return vscode.window.createTextEditorDecorationType({ + after: { + contentIconPath: this.svgTooltip, + margin: `-2.5px 0 0 ${SVG_CONFIG.leftMargin}px`, + width: `${SVG_CONFIG.tipWidth}px`, + }, + }); + } + + private createSvgTooltip() { + const baseTextConfig = { + y: SVG_CONFIG.textY, + "font-family": SVG_CONFIG.fontFamily, + "font-size": SVG_CONFIG.fontSize, + }; + + if (!this.theme) { + return; + } + + try { + const svgContent = svgBuilder + .width(SVG_CONFIG.tipWidth) + .height(SVG_CONFIG.tipHeight) + // Main rectangle + .rect({ + x: 0, + y: 0, + width: SVG_CONFIG.tipWidth, + height: SVG_CONFIG.tipHeight, + rx: SVG_CONFIG.radius, + ry: SVG_CONFIG.radius, + fill: this.theme.colors["editor.background"], + stroke: SVG_CONFIG.stroke, + "stroke-width": SVG_CONFIG.strokeWidth, + filter: SVG_CONFIG.filter, + }) + // Chat + .text( + { + ...baseTextConfig, + x: SVG_CONFIG.chatLabelX, + fill: this.theme.colors["editor.foreground"], + }, + SVG_CONFIG.chatLabel, + ) + .text( + { + ...baseTextConfig, + x: SVG_CONFIG.chatShortcutX, + fill: SVG_CONFIG.shortcutColor, + }, + SVG_CONFIG.chatShortcut, + ) + // Edit + .text( + { + ...baseTextConfig, + x: SVG_CONFIG.editLabelX, + fill: this.theme.colors["editor.foreground"], + }, + SVG_CONFIG.editLabel, + ) + .text( + { + ...baseTextConfig, + x: SVG_CONFIG.editShortcutX, + fill: SVG_CONFIG.shortcutColor, + }, + SVG_CONFIG.editShortcut, + ) + .render(); + + const dataUri = `data:image/svg+xml;base64,${Buffer.from(svgContent).toString("base64")}`; + + this.svgTooltip = vscode.Uri.parse(dataUri); + this.svgTooltipDecoration.dispose(); + this.svgTooltipDecoration = this.createSvgTooltipDecoration(); + } catch (error) { + console.error("Error creating SVG for inline tip:", error); + } + } + + private buildHideTooltipHoverMsg() { + const hoverMarkdown = new vscode.MarkdownString( + `[Disable](command:${this.hideCommand})`, + ); + + hoverMarkdown.isTrusted = true; + hoverMarkdown.supportHtml = true; + return hoverMarkdown; + } + + /** + * Calculates tooltip position using these rules: + * 1. For single-line selection: Place after the line's content + * 2. For multi-line selection: Place after the longer line between: + * - The first non-empty selected line + * - The line above the selection + * Returns null if selection is empty or contains only empty lines + */ + private calculateTooltipPosition( + editor: vscode.TextEditor, + selection: vscode.Selection, + ): vscode.Position | null { + const document = editor.document; + + // Get selection info + const startLine = selection.start.line; + const endLine = selection.end.line; + const isFullLineSelection = + selection.start.character === 0 && + (selection.end.line > selection.start.line + ? selection.end.character === 0 + : selection.end.character === + document.lineAt(selection.end.line).text.length); + + // Helper functions + const isLineEmpty = (lineNumber: number): boolean => { + return document.lineAt(lineNumber).text.trim().length === 0; + }; + + const getLineEndChar = (lineNumber: number): number => { + return document.lineAt(lineNumber).text.trimEnd().length; + }; + + // If single empty line selected and not full line selection, return null + if ( + startLine === endLine && + isLineEmpty(startLine) && + !isFullLineSelection + ) { + return null; + } + + // Find topmost non-empty line + let topNonEmptyLine = startLine; + while (topNonEmptyLine <= endLine && isLineEmpty(topNonEmptyLine)) { + topNonEmptyLine++; + } + + // If all lines empty, return null + if (topNonEmptyLine > endLine) { + return null; + } + + const OFFSET = 4; // Characters to offset from end of line + + // Single line or full line selection + if (isFullLineSelection || startLine === endLine) { + return new vscode.Position( + topNonEmptyLine, + getLineEndChar(topNonEmptyLine) + OFFSET, + ); + } + + // Check line above selection + const lineAboveSelection = Math.max(0, startLine - 1); + + // Get end positions + const topNonEmptyEndChar = getLineEndChar(topNonEmptyLine); + const lineAboveEndChar = getLineEndChar(lineAboveSelection); + + const baseEndChar = Math.max(topNonEmptyEndChar, lineAboveEndChar); + + return new vscode.Position(topNonEmptyLine, baseEndChar + OFFSET); + } + + private updateTooltipPosition( + editor: vscode.TextEditor, + selection: vscode.Selection, + ) { + const position = this.calculateTooltipPosition(editor, selection); + + if (!position) { + editor.setDecorations(this.svgTooltipDecoration, []); + return; + } + + editor.setDecorations(this.svgTooltipDecoration, [ + { + range: new vscode.Range(position, position), + hoverMessage: [this.buildHideTooltipHoverMsg()], + }, + ]); + } +} + +export default function setupInlineTips(context: vscode.ExtensionContext) { + InlineTipManager.getInstance().setupInlineTips(context); +} diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 7aa0ae4a9..d40aee740 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -7,7 +7,8 @@ import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion } from "../util/util"; import { VsCodeContinueApi } from "./api"; -import { setupInlineTips } from "./inlineTips"; +import setupInlineTips from "./InlineTipManager"; +// import { setupInlineTips } from "./inlineTips"; export async function activateExtension(context: vscode.ExtensionContext) { // Add necessary files diff --git a/extensions/vscode/src/activation/inlineTips.ts b/extensions/vscode/src/activation/inlineTips.ts deleted file mode 100644 index 49a8adf29..000000000 --- a/extensions/vscode/src/activation/inlineTips.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { EXTENSION_NAME } from "core/control-plane/env"; -import * as vscode from "vscode"; - -import { getMetaKeyName } from "../util/util"; - -const inlineTipDecoration = vscode.window.createTextEditorDecorationType({ - after: { - contentText: `Add to chat (${getMetaKeyName()}+L) | Edit highlighted code (${getMetaKeyName()}+I).`, - color: "#888", - margin: "0 0 0 6em", - fontWeight: "bold", - }, -}); - -function showInlineTip() { - return vscode.workspace - .getConfiguration(EXTENSION_NAME) - .get("showInlineTip"); -} - -function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) { - const selection = e.selections[0]; - const editor = e.textEditor; - - if (editor.document.uri.toString().startsWith("output:")) { - return; - } - - if (selection.isEmpty || showInlineTip() === false) { - editor.setDecorations(inlineTipDecoration, []); - return; - } - - const line = Math.max(0, selection.start.line - 1); - - const hoverMarkdown = new vscode.MarkdownString( - `Click [here](command:continue.hideInlineTip) to hide these suggestions`, - ); - hoverMarkdown.isTrusted = true; - hoverMarkdown.supportHtml = true; - editor.setDecorations(inlineTipDecoration, [ - { - range: new vscode.Range( - new vscode.Position(line, Number.MAX_VALUE), - new vscode.Position(line, Number.MAX_VALUE), - ), - hoverMessage: [hoverMarkdown], - }, - ]); -} - -const emptyFileTooltipDecoration = vscode.window.createTextEditorDecorationType( - { - after: { - contentText: `Use ${getMetaKeyName()}+I to generate code`, - color: "#888", - margin: "2em 0 0 0", - fontStyle: "italic", - }, - }, -); - -let selectionChangeDebounceTimer: NodeJS.Timeout | undefined; - -export function setupInlineTips(context: vscode.ExtensionContext) { - context.subscriptions.push( - vscode.window.onDidChangeTextEditorSelection((e) => { - if (selectionChangeDebounceTimer) { - clearTimeout(selectionChangeDebounceTimer); - } - selectionChangeDebounceTimer = setTimeout(() => { - handleSelectionChange(e); - }, 200); - }), - ); - - context.subscriptions.push( - vscode.window.onDidChangeActiveTextEditor((editor) => { - if (editor?.document.getText() === "" && showInlineTip() === true) { - if ( - editor.document.uri.toString().startsWith("output:") || - editor.document.uri.scheme === "comment" - ) { - return; - } - - editor.setDecorations(emptyFileTooltipDecoration, [ - { - range: new vscode.Range( - new vscode.Position(0, Number.MAX_VALUE), - new vscode.Position(0, Number.MAX_VALUE), - ), - }, - ]); - } - }), - ); - - context.subscriptions.push( - vscode.workspace.onDidChangeTextDocument((e) => { - if (e.document.uri.toString().startsWith("vscode://inline-chat")) { - return; - } - if (e.document.getText() === "" && showInlineTip() === true) { - vscode.window.visibleTextEditors.forEach((editor) => { - editor.setDecorations(emptyFileTooltipDecoration, [ - { - range: new vscode.Range( - new vscode.Position(0, Number.MAX_VALUE), - new vscode.Position(0, Number.MAX_VALUE), - ), - }, - ]); - }); - } else { - vscode.window.visibleTextEditors.forEach((editor) => { - editor.setDecorations(emptyFileTooltipDecoration, []); - }); - } - }), - ); -} diff --git a/gui/src/components/indexing/ChatIndexingPeeks.tsx b/gui/src/components/indexing/ChatIndexingPeeks.tsx index 1ec1076c0..66936597d 100644 --- a/gui/src/components/indexing/ChatIndexingPeeks.tsx +++ b/gui/src/components/indexing/ChatIndexingPeeks.tsx @@ -62,7 +62,7 @@ function ChatIndexingPeek({ state }: ChatIndexingPeekProps) {
{ dispatch( setIndexingChatPeekHidden({ type: state.type, hidden: true }), diff --git a/package-lock.json b/package-lock.json index c147efa72..da3272555 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,9 @@ "requires": true, "packages": { "": { + "dependencies": { + "svg-builder": "^2.0.0" + }, "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "eslint-plugin-import": "^2.29.1", @@ -2828,6 +2831,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/svg-builder": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/svg-builder/-/svg-builder-2.0.0.tgz", + "integrity": "sha512-v89FptvyrOy1Gf9KPkIo2jxroCLEZLiGBRTSutL3pzqZe2xnCFltkCLnEjV8QOEJ99PzBa9NGPGEDP9l8MWIrw==" + }, "node_modules/text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", diff --git a/package.json b/package.json index c093fccd9..e3091f198 100644 --- a/package.json +++ b/package.json @@ -11,5 +11,8 @@ "eslint-plugin-import": "^2.29.1", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8" + }, + "dependencies": { + "svg-builder": "^2.0.0" } } From 5a13272d375c2630be03dc97e6234389fff2d02a Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 2 Jan 2025 17:56:20 -0600 Subject: [PATCH 59/64] Update InlineTipManager.ts --- extensions/vscode/src/activation/InlineTipManager.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/src/activation/InlineTipManager.ts b/extensions/vscode/src/activation/InlineTipManager.ts index b335cc9dd..954dba19d 100644 --- a/extensions/vscode/src/activation/InlineTipManager.ts +++ b/extensions/vscode/src/activation/InlineTipManager.ts @@ -15,7 +15,7 @@ const SVG_CONFIG = { radius: 4, leftMargin: 40, debounceDelay: 500, - chatLabel: "Add to Chat", + chatLabel: "Chat", chatShortcut: `${getMetaKeyLabel()}L`, editLabel: "Edit", editShortcut: `${getMetaKeyLabel()}I`, From 02968fb1551c0a26af75340641312e1f9f5a1102 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 2 Jan 2025 20:33:23 -0600 Subject: [PATCH 60/64] fix: correct package.json update --- extensions/vscode/package-lock.json | 10 ++++++++-- extensions/vscode/package.json | 1 + extensions/vscode/src/activation/InlineTipManager.ts | 4 ++-- extensions/vscode/src/activation/activate.ts | 1 - package-lock.json | 8 -------- package.json | 3 --- 6 files changed, 11 insertions(+), 16 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 8f5cad8a0..c6db7f103 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.247", + "version": "0.9.248", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.247", + "version": "0.9.248", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -48,6 +48,7 @@ "request": "^2.88.2", "socket.io-client": "^4.7.2", "strip-ansi": "^7.1.0", + "svg-builder": "^2.0.0", "systeminformation": "^5.22.10", "tailwindcss": "^3.3.2", "undici": "^6.2.0", @@ -12122,6 +12123,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/svg-builder": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/svg-builder/-/svg-builder-2.0.0.tgz", + "integrity": "sha512-v89FptvyrOy1Gf9KPkIo2jxroCLEZLiGBRTSutL3pzqZe2xnCFltkCLnEjV8QOEJ99PzBa9NGPGEDP9l8MWIrw==" + }, "node_modules/symbol-tree": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 6a416096c..550ed3538 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -703,6 +703,7 @@ "request": "^2.88.2", "socket.io-client": "^4.7.2", "strip-ansi": "^7.1.0", + "svg-builder": "^2.0.0", "systeminformation": "^5.22.10", "tailwindcss": "^3.3.2", "undici": "^6.2.0", diff --git a/extensions/vscode/src/activation/InlineTipManager.ts b/extensions/vscode/src/activation/InlineTipManager.ts index 954dba19d..0ea078c21 100644 --- a/extensions/vscode/src/activation/InlineTipManager.ts +++ b/extensions/vscode/src/activation/InlineTipManager.ts @@ -23,7 +23,7 @@ const SVG_CONFIG = { get fontSize() { return Math.ceil( (vscode.workspace.getConfiguration("editor").get("fontSize") ?? - 14) * 0.7, + 14) * 0.8, ); }, get fontFamily() { @@ -237,7 +237,7 @@ export class InlineTipManager { return vscode.window.createTextEditorDecorationType({ after: { contentIconPath: this.svgTooltip, - margin: `-2.5px 0 0 ${SVG_CONFIG.leftMargin}px`, + margin: `-5px 0 0 ${SVG_CONFIG.leftMargin}px`, width: `${SVG_CONFIG.tipWidth}px`, }, }); diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index d40aee740..1bd22c7f4 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -8,7 +8,6 @@ import { getExtensionVersion } from "../util/util"; import { VsCodeContinueApi } from "./api"; import setupInlineTips from "./InlineTipManager"; -// import { setupInlineTips } from "./inlineTips"; export async function activateExtension(context: vscode.ExtensionContext) { // Add necessary files diff --git a/package-lock.json b/package-lock.json index da3272555..c147efa72 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,9 +4,6 @@ "requires": true, "packages": { "": { - "dependencies": { - "svg-builder": "^2.0.0" - }, "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "eslint-plugin-import": "^2.29.1", @@ -2831,11 +2828,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/svg-builder": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/svg-builder/-/svg-builder-2.0.0.tgz", - "integrity": "sha512-v89FptvyrOy1Gf9KPkIo2jxroCLEZLiGBRTSutL3pzqZe2xnCFltkCLnEjV8QOEJ99PzBa9NGPGEDP9l8MWIrw==" - }, "node_modules/text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", diff --git a/package.json b/package.json index e3091f198..c093fccd9 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,5 @@ "eslint-plugin-import": "^2.29.1", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8" - }, - "dependencies": { - "svg-builder": "^2.0.0" } } From 92a38ccf5f0639d815684bd786f75ebede9e950c Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 2 Jan 2025 23:24:32 -0600 Subject: [PATCH 61/64] bugfix: handle inline edit w/ myers diff --- .../vscode/src/diff/vertical/handler.ts | 75 ++++++++++--------- .../vscode/src/diff/vertical/manager.ts | 2 +- .../VerticalPerLineCodeLensProvider.ts | 9 --- 3 files changed, 40 insertions(+), 46 deletions(-) diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index a99c9c1c3..80331f805 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -343,6 +343,7 @@ export class VerticalDiffHandler implements vscode.Disposable { async run(diffLineGenerator: AsyncGenerator) { let diffLines = []; + try { // As an indicator of loading this.updateIndexLineDecorations(); @@ -481,9 +482,17 @@ export class VerticalDiffHandler implements vscode.Disposable { * we have received all of the diff lines. */ async reapplyWithMeyersDiff(diffLines: DiffLine[]) { + // First, we reset the original diff by deleting any new lines and clearing decorations + for (const range of this.greenDecorationManager.getRanges()) { + await this.deleteLinesAt( + range.start.line, + range.end.line - range.start.line + 1, + ); + } + this.clearDecorations(); - // First, get our old/new file content based on the diff lines + // Then, get our old/new file content based on the original lines const oldFileContent = diffLines .filter((line) => line.type === "same" || line.type === "old") .map((line) => line.line) @@ -497,55 +506,49 @@ export class VerticalDiffHandler implements vscode.Disposable { const diffs = myersDiff(oldFileContent, newFileContent); const meyersDiffLines = diffs.map((diff) => diff.line).join("\n"); - console.log({ newFileContent }); - - // Then, we overwrite the potentially miscalcualted diff blocks with our Meyers Diff - const fullRange = new vscode.Range( - this.editor.document.positionAt(0), - this.editor.document.positionAt(this.editor.document.getText().length), - ); + // Then, we insert our diff lines await this.editor.edit((editBuilder) => { - editBuilder.replace(fullRange, meyersDiffLines); + editBuilder.replace(this.range, meyersDiffLines), + { + undoStopAfter: false, + undoStopBefore: false, + }; }); - let currentBlock = { - start: 0, - numRed: 0, - numGreen: 0, - }; - - const blocks: VerticalDiffCodeLens[] = []; - // Lastly, we apply decorations + let numRed = 0; + let numGreen = 0; + + const codeLensBlocks: VerticalDiffCodeLens[] = []; + diffs.forEach((diff, index) => { if (diff.type === "old") { - this.redDecorationManager.addLine(index); - currentBlock.numRed++; + this.redDecorationManager.addLine(this.startLine + index); + numRed++; } else if (diff.type === "new") { - this.greenDecorationManager.addLine(index); - currentBlock.numGreen++; - } else if ( - diff.type === "same" && - (currentBlock.numRed > 0 || currentBlock.numGreen > 0) - ) { - blocks.push({ - ...currentBlock, - start: index - currentBlock.numRed - currentBlock.numGreen, + this.greenDecorationManager.addLine(this.startLine + index); + numGreen++; + } else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) { + codeLensBlocks.push({ + numRed, + numGreen, + start: this.startLine + index - numRed - numGreen, }); - currentBlock = { - start: index + 1, - numRed: 0, - numGreen: 0, - }; + numRed = 0; + numGreen = 0; } }); - if (currentBlock.numRed > 0 || currentBlock.numGreen > 0) { - blocks.push(currentBlock); + if (numRed > 0 || numGreen > 0) { + codeLensBlocks.push({ + numGreen, + numRed, + start: this.startLine + diffs.length - 1 - numRed - numGreen, + }); } - this.editorToVerticalDiffCodeLens.set(this.fileUri, blocks); + this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks); this.refreshCodeLens(); } } diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index ee47fd173..1e1b41a17 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -3,13 +3,13 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; import { getMarkdownLanguageTagForFile } from "core/util"; +import * as URI from "uri-js"; import * as vscode from "vscode"; import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; -import * as URI from "uri-js"; export interface VerticalDiffCodeLens { start: number; diff --git a/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts index 52fd07f79..43c9015f1 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts @@ -53,15 +53,6 @@ export class VerticalDiffCodeLensProvider implements vscode.CodeLensProvider { arguments: [uri, i], }), ); - - if (codeLenses.length === 2) { - codeLenses.push( - new vscode.CodeLens(range, { - title: `${getMetaKeyLabel()}I to add instructions`, - command: "", - }), - ); - } } return codeLenses; From cb77d90a896918f64a62a8e5ad7d95ad7ff56b78 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 2 Jan 2025 23:26:33 -0600 Subject: [PATCH 62/64] Update handler.ts --- extensions/vscode/src/diff/vertical/handler.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 80331f805..a3a7f651f 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -544,7 +544,7 @@ export class VerticalDiffHandler implements vscode.Disposable { codeLensBlocks.push({ numGreen, numRed, - start: this.startLine + diffs.length - 1 - numRed - numGreen, + start: this.startLine + diffs.length - numRed - numGreen, }); } From 2200b6eafd2773afbd7172e5fbd601464a5be906 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Jan 2025 10:10:25 +0100 Subject: [PATCH 63/64] uri util fixes --- core/util/ideUtils.ts | 18 ++--- core/util/uri.test.ts | 22 ------ core/util/uri.ts | 71 ++++++++----------- .../StepContainerPreToolbar.tsx | 4 +- 4 files changed, 42 insertions(+), 73 deletions(-) diff --git a/core/util/ideUtils.ts b/core/util/ideUtils.ts index 93cb5008d..b969b2286 100644 --- a/core/util/ideUtils.ts +++ b/core/util/ideUtils.ts @@ -1,6 +1,10 @@ import { IDE } from ".."; -import { joinPathsToUri, pathToUriPathSegment } from "./uri"; +import { + joinEncodedUriPathSegmentToUri, + joinPathsToUri, + pathToUriPathSegment, +} from "./uri"; /* This function takes a relative (to workspace) filepath @@ -51,7 +55,7 @@ export async function inferResolvedUriFromRelativePath( for (const suffix of suffixes) { const uris = dirs.map((dir) => ({ dir, - partialUri: joinPathsToUri(dir, suffix), + partialUri: joinEncodedUriPathSegmentToUri(dir, suffix), })); const promises = uris.map(async ({ partialUri, dir }) => { const exists = await ide.fileExists(partialUri); @@ -67,15 +71,13 @@ export async function inferResolvedUriFromRelativePath( // If exactly one directory matches, use it if (existingUris.length === 1) { - return joinPathsToUri(existingUris[0].dir, segments.join("/")); + return joinEncodedUriPathSegmentToUri( + existingUris[0].dir, + segments.join("/"), + ); } } // If no unique match found, use the first directory return joinPathsToUri(dirs[0], path); } - -interface ResolveResult { - resolvedUri: string; - matchedDir: string; -} diff --git a/core/util/uri.test.ts b/core/util/uri.test.ts index 9e2471054..8a915d73f 100644 --- a/core/util/uri.test.ts +++ b/core/util/uri.test.ts @@ -1,9 +1,7 @@ // Generated by continue -import * as URI from "uri-js"; import { pathToUriPathSegment, findUriInDirs, - relativePathOrUriToUri, getUriPathBasename, getUriFileExtension, getFileExtensionFromBasename, @@ -141,26 +139,6 @@ describe("uri utils", () => { }); }); - describe("relativePathOrUriToUri", () => { - const consoleSpy = jest.spyOn(console, "trace").mockImplementation(); - - afterEach(() => { - consoleSpy.mockClear(); - }); - - it("should return original URI if scheme exists", () => { - const uri = "file:///path/to/file.txt"; - expect(relativePathOrUriToUri(uri, "file:///base")).toBe(uri); - }); - - it("should convert relative path to URI", () => { - expect(relativePathOrUriToUri("path/to/file.txt", "file:///base")).toBe( - "file:///base/path/to/file.txt", - ); - expect(consoleSpy).toHaveBeenCalledWith("Received path with no scheme"); - }); - }); - describe("getLastNUriRelativePathParts", () => { it("should get last N parts of URI relative path", () => { const dirUris = ["file:///workspace/project1"]; diff --git a/core/util/uri.ts b/core/util/uri.ts index 708408ce0..a1bcd7745 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -5,23 +5,21 @@ import * as URI from "uri-js"; \this\is\afile.ts -> this/is/afile.ts is/already/clean -> is/already/clean **/ - export function pathToUriPathSegment(path: string) { let clean = path.replace(/[\\]/g, "/"); // backslashes -> forward slashes clean = clean.replace(/^\//, ""); // remove start slash clean = clean.replace(/\/$/, ""); // remove end slash return clean .split("/") - .map((segment) => encodeURIComponent(segment)) + .map((part) => encodeURIComponent(part)) .join("/"); } export function getCleanUriPath(uri: string) { - const path = URI.parse(uri).path; - if (!path) { - return ""; - } - return pathToUriPathSegment(path); + const path = URI.parse(uri).path ?? ""; + let clean = path.replace(/^\//, ""); // remove start slash + clean = clean.replace(/\/$/, ""); // remove end slash + return clean; } export function findUriInDirs( @@ -36,6 +34,7 @@ export function findUriInDirs( if (!uriComps.scheme) { throw new Error(`Invalid uri: ${uri}`); } + const uriPathParts = getCleanUriPath(uri).split("/"); for (const dir of dirUriCandidates) { const dirComps = URI.parse(dir); @@ -51,14 +50,7 @@ export function findUriInDirs( // file:///folder/file is not within file:///fold // At this point we break the path up and check if each dir path part matches - const dirPathParts = (dirComps.path ?? "") - .replace(/^\//, "") - .split("/") - .map((part) => encodeURIComponent(part)); - const uriPathParts = (uriComps.path ?? "") - .replace(/^\//, "") - .split("/") - .map((part) => encodeURIComponent(part)); + const dirPathParts = getCleanUriPath(dir).split("/"); if (uriPathParts.length < dirPathParts.length) { continue; @@ -70,7 +62,10 @@ export function findUriInDirs( } } if (allDirPartsMatch) { - const relativePath = uriPathParts.slice(dirPathParts.length).join("/"); + const relativePath = uriPathParts + .slice(dirPathParts.length) + .map(decodeURIComponent) + .join("/"); return { uri, relativePathOrBasename: relativePath, @@ -86,28 +81,13 @@ export function findUriInDirs( }; } -/* - To smooth out the transition from path to URI will use this function to warn when path is used - This will NOT work consistently with full OS paths like c:\blah\blah or ~/Users/etc -*/ -export function relativePathOrUriToUri( - relativePathOrUri: string, - defaultDirUri: string, -): string { - const out = URI.parse(relativePathOrUri); - if (out.scheme) { - return relativePathOrUri; - } - console.trace("Received path with no scheme"); - return joinPathsToUri(defaultDirUri, out.path ?? ""); -} - /* Returns just the file or folder name of a URI */ export function getUriPathBasename(uri: string): string { - const cleanPath = getCleanUriPath(uri); - return cleanPath.split("/")?.pop() || ""; + const path = getCleanUriPath(uri); + const basename = path.split("/").pop() || ""; + return decodeURIComponent(basename); } export function getFileExtensionFromBasename(basename: string) { @@ -142,6 +122,15 @@ export function joinPathsToUri(uri: string, ...pathSegments: string[]) { return URI.serialize(components); } +export function joinEncodedUriPathSegmentToUri( + uri: string, + pathSegment: string, +) { + const components = URI.parse(uri); + components.path = `${components.path}/${pathSegment}`; + return URI.serialize(components); +} + export function getShortestUniqueRelativeUriPaths( uris: string[], dirUriCandidates: string[], @@ -153,8 +142,7 @@ export function getShortestUniqueRelativeUriPaths( const segmentCombinationsMap = new Map(); const segmentsInfo = uris.map((uri) => { const { relativePathOrBasename } = findUriInDirs(uri, dirUriCandidates); - const cleanPath = pathToUriPathSegment(relativePathOrBasename); - const segments = cleanPath.split("/"); + const segments = relativePathOrBasename.split("/"); const suffixes: string[] = []; // Generate all possible suffix combinations, starting from the shortest (basename) @@ -168,18 +156,19 @@ export function getShortestUniqueRelativeUriPaths( ); } - return { uri, segments, suffixes, cleanPath }; + return { uri, segments, suffixes, relativePathOrBasename }; }); // Find shortest unique path for each URI - return segmentsInfo.map(({ uri, suffixes, cleanPath }) => { + return segmentsInfo.map(({ uri, suffixes, relativePathOrBasename }) => { // Since suffixes are now ordered from shortest to longest, // the first unique one we find will be the shortest - const uniqueCleanPath = + const uniquePath = suffixes.find((suffix) => segmentCombinationsMap.get(suffix) === 1) ?? - cleanPath; // fallback to full path if no unique suffix found - return { uri, uniquePath: decodeURIComponent(uniqueCleanPath) }; + relativePathOrBasename; // fallback to full path if no unique suffix found + return { uri, uniquePath }; }); } + // Only used when working with system paths and relative paths // Since doesn't account for URI segements before workspace export function getLastNPathParts(filepath: string, n: number): string { diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index c6a0d58f0..398ce5747 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -93,12 +93,12 @@ export default function StepContainerPreToolbar( if (!defaultModel) { return; } - + const fileUri = await inferResolvedUriFromRelativePath( props.relativeFilepath, ideMessenger.ide, ); - + ideMessenger.post("applyToFile", { streamId: streamIdRef.current, filepath: fileUri, From 821c841b43e7b054a207d645df61e93cbc15baa4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 3 Jan 2025 10:47:33 +0100 Subject: [PATCH 64/64] fix multifile edit --- core/util/ideUtils.ts | 6 +++--- extensions/vscode/package-lock.json | 4 ++-- .../StepContainerPreToolbar.tsx | 1 + gui/src/util/getMultifileEditPrompt.ts | 18 ++++++++++++------ 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/core/util/ideUtils.ts b/core/util/ideUtils.ts index b969b2286..9ed4a47fc 100644 --- a/core/util/ideUtils.ts +++ b/core/util/ideUtils.ts @@ -34,7 +34,7 @@ export async function resolveRelativePathInDir( If no meaninful path match just concatenates to first dir's uri */ export async function inferResolvedUriFromRelativePath( - path: string, + relativePath: string, ide: IDE, dirCandidates?: string[], ): Promise { @@ -44,7 +44,7 @@ export async function inferResolvedUriFromRelativePath( throw new Error("inferResolvedUriFromRelativePath: no dirs provided"); } - const segments = pathToUriPathSegment(path).split("/"); + const segments = pathToUriPathSegment(relativePath).split("/"); // Generate all possible suffixes from shortest to longest const suffixes: string[] = []; for (let i = segments.length - 1; i >= 0; i--) { @@ -79,5 +79,5 @@ export async function inferResolvedUriFromRelativePath( } // If no unique match found, use the first directory - return joinPathsToUri(dirs[0], path); + return joinPathsToUri(dirs[0], relativePath); } diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 8f5cad8a0..0a2dd8330 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.247", + "version": "0.9.248", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.247", + "version": "0.9.248", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 398ce5747..1ee03d2f5 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -98,6 +98,7 @@ export default function StepContainerPreToolbar( props.relativeFilepath, ideMessenger.ide, ); + console.log("HERE", props.relativeFilepath, fileUri); ideMessenger.post("applyToFile", { streamId: streamIdRef.current, diff --git a/gui/src/util/getMultifileEditPrompt.ts b/gui/src/util/getMultifileEditPrompt.ts index 8f526f1e2..13ee8ac78 100644 --- a/gui/src/util/getMultifileEditPrompt.ts +++ b/gui/src/util/getMultifileEditPrompt.ts @@ -1,16 +1,22 @@ -import { CodeToEdit } from "core"; +import { CodeToEdit, IDE } from "core"; +import { findUriInDirs } from "core/util/uri"; export default function getMultifileEditPrompt( codeToEdit: CodeToEdit[], + dirs?: string[], ): string { const codeToEditStr = codeToEdit - .map( - (code) => ` -\`\`\` ${code.filepath} + .map((code) => { + const { relativePathOrBasename } = findUriInDirs( + code.filepath, + dirs ?? window.workspacePaths ?? [], + ); + return ` +\`\`\` ${relativePathOrBasename} ${code.contents} \`\`\` - `, - ) + `; + }) .join("\n"); return `