From 6e8f4d86cd3ae1a84bada2a72be2f6e6688dfa00 Mon Sep 17 00:00:00 2001 From: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Date: Sat, 8 Feb 2025 16:28:52 -0500 Subject: [PATCH 001/127] added new gemini models to config_schema.json --- extensions/vscode/config_schema.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index d9dab076b..642335557 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -937,7 +937,10 @@ "gemini-1.5-flash", "gemini-1.5-flash-8b", "gemini-2.0-flash-exp", - "gemini-2.0-flash" + "gemini-2.0-flash", + "gemini-2.0-flash-thinking-exp-01-21", + "gemini-2.0-pro-exp-02-05", + "gemini-2.0-flash-lite-preview-02-05" ] } } From 3c36b4dc378ddd8c5c5c2cc234e9a605d776d928 Mon Sep 17 00:00:00 2001 From: Ingo Eichhorst Date: Sun, 16 Feb 2025 22:31:10 +0100 Subject: [PATCH 002/127] feat: add unified diff instant apply --- core/edit/lazy/applyCodeBlock.ts | 12 + core/edit/lazy/unifiedDiffApply.test.ts | 412 ++++++++++++++++++++++++ core/edit/lazy/unifiedDiffApply.ts | 152 +++++++++ docs/docs/edit/how-to-use-it.md | 7 + 4 files changed, 583 insertions(+) create mode 100644 core/edit/lazy/unifiedDiffApply.test.ts create mode 100644 core/edit/lazy/unifiedDiffApply.ts diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index 924d1c282..8a311a4fe 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -5,6 +5,7 @@ import { getUriFileExtension } from "../../util/uri"; import { deterministicApplyLazyEdit } from "./deterministic"; import { streamLazyApply } from "./streamLazyApply"; +import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply"; function canUseInstantApply(filename: string) { const fileExtension = getUriFileExtension(filename); @@ -32,5 +33,16 @@ export async function applyCodeBlock( } } + // If the code block is a diff + if (isUnifiedDiffFormat(newFile)) { + try { + const diffLines = applyUnifiedDiff(oldFile, newFile); + const diffGenerator = generateLines(diffLines!); + return [true, diffGenerator]; + } catch (e) { + console.error("Failed to apply unified diff", e); + } + } + return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)]; } diff --git a/core/edit/lazy/unifiedDiffApply.test.ts b/core/edit/lazy/unifiedDiffApply.test.ts new file mode 100644 index 000000000..c7a5a8370 --- /dev/null +++ b/core/edit/lazy/unifiedDiffApply.test.ts @@ -0,0 +1,412 @@ +import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply"; + +describe("isUnifiedDiffFormat", () => { + it("should return true for valid unified diff format", () => { + const validDiff = `--- original.txt ++++ modified.txt +@@ -1,3 +1,4 @@ + line1 +-line2 ++newline2 ++newline3 + line3`; + expect(isUnifiedDiffFormat(validDiff)).toBe(true); + }); + + it("should return false for empty diff", () => { + expect(isUnifiedDiffFormat("")).toBe(false); + }); + + it("should return false for diff without hunk header", () => { + const invalidDiff = `--- original.txt ++++ modified.txt ++line1 +-line2 ++line3`; + expect(isUnifiedDiffFormat(invalidDiff)).toBe(false); + }); + + it("should return false for diff without valid content", () => { + const invalidDiff = `--- original.txt ++++ modified.txt +@@ -1,3 +1,4 @@`; + expect(isUnifiedDiffFormat(invalidDiff)).toBe(false); + }); + + it("should return true even without file headers if hunk headers exist", () => { + const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@ + line1 +-line2 ++newline2 ++newline3 + line3`; + expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true); + }); + + it("should return true in case of empty lines", () => { + const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@ + line1 +-line2 ++newline2 + line3`; + expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true); + }); +}); + +describe("applyUnifiedDiff", () => { + it("should correctly apply a add line of unified diff", () => { + const sourceCode = `func main() { + scanner := bufio.NewScanner(os.Stdin) + fmt.Println("Calculator started! Available operations:") + fmt.Println(" + : Addition") + fmt.Println(" - : Subtraction") + fmt.Println(" * : Multiplication") + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") +} +// End of file`; + + const diffText = `--- original.go ++++ updated.go +@@ -30,6 +30,7 @@ + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") ++ fmt.Println(" log: Logarithm (use 'log base number')") + }`; + + const result = applyUnifiedDiff(sourceCode, diffText); + + const expected = [ + { type: "same", line: "func main() {" }, + { type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" }, + { type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" }, + { type: "same", line: " fmt.Println(\" + : Addition\")" }, + { type: "same", line: " fmt.Println(\" - : Subtraction\")" }, + { type: "same", line: " fmt.Println(\" * : Multiplication\")" }, + { type: "same", line: " fmt.Println(\" / : Division\")" }, + { type: "same", line: " fmt.Println(\" ^ : Power\")" }, + { type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" }, + { type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" }, + { type: "same", line: "}" }, + { type: "same", line: "// End of file" } + ]; + + expect(result).toEqual(expected); + }); + + it("should correctly apply multiple insertions and deletions", () => { + const sourceCode = `package main +import "fmt" +func main() { + fmt.Println("Hello") + fmt.Println("World") +}`; + + const diffText = `--- original.go ++++ updated.go +@@ -1,8 +1,11 @@ + package main + +-import "fmt" ++import ( ++ "fmt" ++ "time" ++) + + func main() { +- fmt.Println("Hello") ++ fmt.Printf("The time is: %v\\n", time.Now()) +- fmt.Println("World") ++ fmt.Println("Goodbye!") + }`; + const result = applyUnifiedDiff(sourceCode, diffText); + + const expected = [ + { type: "same", line: "package main" }, + { type: "same", line: "" }, + { type: "old", line: "import \"fmt\"" }, + { type: "new", line: "import (" }, + { type: "new", line: " \"fmt\"" }, + { type: "new", line: " \"time\"" }, + { type: "new", line: ")" }, + { type: "same", line: "" }, + { type: "same", line: "func main() {" }, + { type: "old", line: " fmt.Println(\"Hello\")" }, + { type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" }, + { type: "old", line: " fmt.Println(\"World\")" }, + { type: "new", line: " fmt.Println(\"Goodbye!\")" }, + { type: "same", line: "}" } + ]; + + expect(result).toEqual(expected); + }); + + it("should correctly apply multiple diff blocks", () => { + const sourceCode = `package main +import ( + "bufio" + "fmt" + "math" + "os" + "strconv" + "strings" + "testing" +) +func main() { + scanner := bufio.NewScanner(os.Stdin) + fmt.Println("Calculator started! Available operations:") + fmt.Println(" + : Addition") + fmt.Println(" - : Subtraction") + fmt.Println(" * : Multiplication") + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") + for { + fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ") + scanner.Scan() + input := scanner.Text() + if strings.ToLower(input) == "q" { + fmt.Println("Goodbye!") + break + } + result, err := calculate(input) + if err != nil { + fmt.Printf("Error: %v\n", err) + continue + } + fmt.Printf("Result: %v\n", result) + } +} +func calculate(input string) (float64, error) { + parts := strings.Fields(input) + if len(parts) < 2 { + return 0, fmt.Errorf("invalid input format: please use 'number operator number' or '√ number'") + } + if parts[0] == "√" { + if len(parts) != 2 { + return 0, fmt.Errorf("square root operation requires exactly one number") + } + num, err := strconv.ParseFloat(parts[1], 64) + if err != nil { + return 0, fmt.Errorf("invalid number for square root: %v", err) + } + if num < 0 { + return 0, fmt.Errorf("cannot calculate square root of a negative number") + } + return math.Sqrt(num), nil + } + if len(parts) != 3 { + return 0, fmt.Errorf("invalid input format: please use 'number operator number'") + } + num1, err := strconv.ParseFloat(parts[0], 64) + if err != nil { + return 0, fmt.Errorf("invalid first number: %v", err) + } + operator := parts[1] + num2, err := strconv.ParseFloat(parts[2], 64) + if err != nil { + return 0, fmt.Errorf("invalid second number: %v", err) + } + switch operator { + case "+": + return num1 + num2, nil + case "-": + return num1 - num2, nil + case "*": + return num1 * num2, nil + case "/": + if num2 == 0 { + return 0, fmt.Errorf("division by zero is not allowed") + } + return num1 / num2, nil + case "^": + return math.Pow(num1, num2), nil + default: + return 0, fmt.Errorf("invalid operator: must be +, -, *, /, ^, or √") + } +} +func TestCalculate(t *testing.T) { + tests := []struct { + input string + expected float64 + hasError bool + }{ + {"2 + 3", 5, false}, + {"10 - 5", 5, false}, + {"4 * 3", 12, false}, + {"15 / 3", 5, false}, + {"2 ^ 3", 8, false}, + {"√ 16", 4, false}, + {"2 + a", 0, true}, + {"15 / 0", 0, true}, + {"√ -4", 0, true}, + {"3 $ 4", 0, true}, + {"", 0, true}, + {"1", 0, true}, + {"1 +", 0, true}, + {"+ 1", 0, true}, + {"√ 2 3", 0, true}, + } + for _, test := range tests { + result, err := calculate(test.input) + if test.hasError && err == nil { + t.Errorf("Expected error for input '%s', but got none", test.input) + continue + } + if !test.hasError && err != nil { + t.Errorf("Unexpected error for input '%s': %v", test.input, err) + continue + } + if !test.hasError && result != test.expected { + t.Errorf("For input '%s': expected %f, but got %f", test.input, test.expected, result) + } + } +} +func TestSpecialCases(t *testing.T) { + result, err := calculate("2.5 + 2.5") + if err != nil { + t.Errorf("Unexpected error for floating point addition: %v", err) + } + if result != 5.0 { + t.Errorf("Floating point addition failed: expected 5.0, got %f", result) + } + result, err = calculate("2.5 ^ 2") + if err != nil { + t.Errorf("Unexpected error for power operation: %v", err) + } + expected := 6.25 + if math.Abs(result-expected) > 0.0001 { + t.Errorf("Power operation failed: expected %f, got %f", expected, result) + } + result, err = calculate("√ 2") + if err != nil { + t.Errorf("Unexpected error for square root: %v", err) + } + expected = math.Sqrt(2) + if math.Abs(result-expected) > 0.0001 { + t.Errorf("Square root operation failed: expected %f, got %f", expected, result) + } +} +func TestLargeNumbers(t *testing.T) { + result, err := calculate("1000000000 + 1000000000") + if err != nil { + t.Errorf("Unexpected error for adding large numbers: %v", err) + } + if result != 2000000000 { + t.Errorf("Adding large numbers failed: expected 2000000000, got %f", result) + } + result, err = calculate("1000000 * 1000000") + if err != nil { + t.Errorf("Unexpected error for multiplying large numbers: %v", err) + } + if result != 1000000000000 { + t.Errorf("Multiplying large numbers failed: expected 1000000000000, got %f", result) + } + result, err = calculate("2 ^ 30") + if err != nil { + t.Errorf("Unexpected error for large exponent operation: %v", err) + } + expected := math.Pow(2, 30) + if result != expected { + t.Errorf("Power operation with large exponent failed: expected %f, got %f", expected, result) + } + result, err = calculate("1000000000000 / 1000000") + if err != nil { + t.Errorf("Unexpected error for dividing large numbers: %v", err) + } + if result != 1000000 { + t.Errorf("Dividing large numbers failed: expected 1000000, got %f", result) + } +}`; + + const diffText = `--- original.go ++++ updated.go +@@ -30,6 +30,7 @@ + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") ++ fmt.Println(" log: Logarithm (use 'log base number')") ++ fmt.Println(" Base must be > 0 and != 1, number must be > 0") + for { + fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ") +@@ -73,6 +74,8 @@ + } + return math.Sqrt(num), nil + } ++ ++ // Handle logarithmic operations ++ if parts[0] == "log" { ++ if len(parts) != 3 { ++ return 0, fmt.Errorf("logarithm operation requires exactly two arguments: 'log base number'") ++ } ++ base, err := strconv.ParseFloat(parts[1], 64) ++ if err != nil || base <= 0 || base == 1 { ++ return 0, fmt.Errorf("invalid base for logarithm: must be > 0 and != 1") ++ } ++ num, err := strconv.ParseFloat(parts[2], 64) ++ if err != nil || num <= 0 { ++ return 0, fmt.Errorf("invalid number for logarithm: must be > 0") ++ } ++ return math.Log(num) / math.Log(base), nil ++ } ++ + if len(parts) != 3 { + return 0, fmt.Errorf("invalid input format: please use 'number operator number'") +@@ -155,6 +158,15 @@ + } + } + } ++ ++func TestLogarithmicCases(t *testing.T) { ++ tests := []struct { ++ input string ++ expected float64 ++ hasError bool ++ }{ ++ {"log 2 8", 3, false}, ++ {"log 10 100", 2, false}, ++ {"log 10 -5", 0, true}, ++ {"log 1 100", 0, true}, ++ {"log 0.5 0.25", 2, false}, ++ }`; + const result = applyUnifiedDiff(sourceCode, diffText); + + expect(result[0].line).toEqual("package main"); + // 1st block + expect(result[21].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")"); + expect(result[22].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")"); + // 2nd block + expect(result[60]).toEqual({type: "same", line: "\t}"}); + expect(result[61]).toEqual({type: "new", line: "\t"}); + expect(result[62]).toEqual({type: "new", line: "\t// Handle logarithmic operations"}); + expect(result[77]).toEqual({type: "new", line: ""}); + expect(result[78]).toEqual({type: "same", line: "\tif len(parts) != 3 {"}); + // 3rd block + expect(result[145]).toEqual({type: "same", line: "}"}); + expect(result[146]).toEqual({type: "new", line: ""}); + expect(result[147]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"}); + expect(result[158]).toEqual({type: "new", line: "\t}"}); + expect(result[159]).toEqual({type: "same", line: ""}); + expect(result[160]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"}); + + }); + + it("should throw error when hunk cannot be matched to source", () => { + const sourceCode = `line1 +line2 +line3`; + + const diffText = `--- a.txt ++++ b.txt +@@ -1,3 +1,4 @@ +missing1 +-missing2 ++newline2 +missing3`; + + expect(() => applyUnifiedDiff(sourceCode, diffText)) + .toThrow("Hunk could not be applied cleanly to source code."); + }); +}); diff --git a/core/edit/lazy/unifiedDiffApply.ts b/core/edit/lazy/unifiedDiffApply.ts new file mode 100644 index 000000000..c5768f1d4 --- /dev/null +++ b/core/edit/lazy/unifiedDiffApply.ts @@ -0,0 +1,152 @@ +import { DiffLine } from "../../index"; + +/** + * Checks if a string matches unified diff format by validating: + * 1. Has at least one hunk header (@@ -n,m +n,m @@) + * 2. Contains valid diff content lines (starting with +, -, or space) which are not header lines + */ +export function isUnifiedDiffFormat(diff: string): boolean { + const lines = diff.trim().split("\n"); + + if (lines.length < 3) {return false;} + + let hasHunkHeader = false; + let hasValidContent = false; + + for (const line of lines) { + if (line.startsWith("---") || line.startsWith("+++")) { + // ignore file headers - they are not required or useful + } else if (line.match(/^@@ -\d+,?\d* \+\d+,?\d* @@/)) { + hasHunkHeader = true; + } else if (line.match(/^[+ -]/) || line === "") { + hasValidContent = true; + } + } + + return hasHunkHeader && hasValidContent; +} + +function extractBeforeLines(hunkLines: string[]): string[] { + return hunkLines + .filter((line) => line.startsWith("-") || !line.startsWith("+")) + .map((line) => line.substring(1)); +} + +/** + * Applies a unified diff to source code and returns an array of DiffLine objects. + * Each DiffLine contains a type ("same", "new", or "old") and the line content. + * + * @throws Error if the diff cannot be cleanly applied to the source + */ +export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] { + const sourceLines = sourceCode.split(/\r?\n/); + const hunks = parseUnifiedDiff(unifiedDiffText); + const diffResult: DiffLine[] = []; + let currentPos = 0; // pointer in sourceLines + + for (const hunk of hunks) { + const hunkBeforeLines = extractBeforeLines(hunk.lines); + const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos); + if (hunkStart === -1) { + // All hunks must be found in the source code. If not, throw an error. + throw new Error("Hunk could not be applied cleanly to source code."); + } + + // Emit any unchanged lines that come before this hunk. + for (let i = currentPos; i < hunkStart; i++) { + diffResult.push({ type: "same", line: sourceLines[i] }); + } + let hunkSourcePos = hunkStart; + + for (const dline of hunk.lines) { + const srcLine = sourceLines[hunkSourcePos]; + if (dline.startsWith("+")) { + // Insertion: output new line (strip the '+' marker) + diffResult.push({ type: "new", line: dline.substring(1) }); + } else if (dline.startsWith("-")) { + // Removal: output the removed (old) line and advance the pointer. + diffResult.push({ type: "old", line: srcLine }); + hunkSourcePos++; + } else { + // Context line: use the source line (in case the diff’s context has a minor whitespace error) + // and advance the pointer. + diffResult.push({ type: "same", line: srcLine }); + hunkSourcePos++; + } + } + currentPos = hunkSourcePos; + } + + for (let i = currentPos; i < sourceLines.length; i++) { + diffResult.push({ type: "same", line: sourceLines[i] }); + } + return diffResult; +} + +interface Hunk { + lines: string[]; +} + +/** + * Parses a unified diff string into an array of hunks. + * It skips the file header lines (starting with "---" or "+++") and hunk header lines (starting with "@@"), + * then collects the remaining lines (which may start with '+' or '-' or have no prefix). + */ +function parseUnifiedDiff(diffText: string): Hunk[] { + const lines = diffText.split(/\r?\n/); + const hunks: Hunk[] = []; + let currentHunk: Hunk | null = null; + + for (const line of lines) { + if (line.startsWith("---") || line.startsWith("+++")) { + // Skip file header lines. + continue; + } + if (line.startsWith("@@")) { + if (currentHunk) { + hunks.push(currentHunk); + } + currentHunk = { lines: [] }; + continue; + } + currentHunk?.lines.push(line); + } + if (currentHunk) { + hunks.push(currentHunk); + } + return hunks; +} + +/** + * Searches for an occurrence of the block of lines (the “before” block) in sourceLines, + * starting at startIndex. Comparison is done by checking if the lines are exactly equal, + * or if their trimmed versions are equal. + * + * Returns the index in sourceLines where the block begins, or -1 if no match is found. + */ +function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number { + for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) { + let match = true; + for (let j = 0; j < hunkBeforeLines.length; j++) { + const sl = sourceLines[i + j]; + const hl = hunkBeforeLines[j]; + if (!linesMatch(sl, hl)) { + match = false; + break; + } + } + if (match) { + return i; + } + } + return -1; +} + +/** + * Returns true if the two lines are either exactly equal or equal after trimming whitespace and tabs. + */ +function linesMatch(a: string, b: string): boolean { + const trimmedA = a.replace(/^\s+/, ""); + const trimmedB = b.replace(/^\s+/, ""); + return trimmedA === trimmedB; +} diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index 850c34b60..19f8e0ccd 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -35,3 +35,10 @@ You can navigate through each proposed change, accepting or rejecting them using You can also accept or reject all changes at once using cmd/ctrl + shift + enter (to accept) or cmd/ctrl + shift + delete/backspace (to reject). If you want to request a new suggestion for the same highlighted code section, you can use cmd/ctrl + i to re-prompt the model. + +## Instant Diff Apply + +If you have large files (exeeding the output token of your model) the edit apply will delete all lines that exceed the model window. To mitigate you can instead of applying the changes directly, ask the chat LLM to "generate a unified diff". +The resulting diff (if the LLM has not made a mistake) can be instantly applied, changing only the lines that need to change. + +Explainer Video: https://youtu.be/b7Xxsot4gyw \ No newline at end of file From 2869cf50781317eddf55dde8248a247953f53d99 Mon Sep 17 00:00:00 2001 From: lkyu <67578466+lkyu-ly@users.noreply.github.com> Date: Thu, 20 Feb 2025 01:07:24 +0800 Subject: [PATCH 003/127] Update domain in docusaurus.config.js Change site url from `continue.dev` to `docs.continue.dev` so as to generate a correct sitemap. --- docs/docusaurus.config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index c97113a0a..0ca029806 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -19,7 +19,7 @@ const config = { favicon: "img/favicon.ico", // Set the production url of your site here - url: "https://continue.dev", + url: "https://docs.continue.dev", // Set the // pathname under which your site is served // For GitHub pages deployment, it is often '//' baseUrl: "/", From 17dbfe6bfd38f67b7cb535da00fa626cdaf4f690 Mon Sep 17 00:00:00 2001 From: Aplulu Date: Fri, 21 Feb 2025 02:49:36 +0900 Subject: [PATCH 004/127] fix: Resolve proxy error when adding Azure OpenAI model --- packages/openai-adapters/src/apis/AzureOpenAI.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/openai-adapters/src/apis/AzureOpenAI.ts b/packages/openai-adapters/src/apis/AzureOpenAI.ts index 2b02af69d..fc9fbdda8 100644 --- a/packages/openai-adapters/src/apis/AzureOpenAI.ts +++ b/packages/openai-adapters/src/apis/AzureOpenAI.ts @@ -40,8 +40,10 @@ export class AzureOpenAIApi implements BaseLlmApi { if (PROXY) { const url = new URL(PROXY); proxyOptions = { - host: url.hostname, - port: Number(url.port), + host: (url.protocol ? url.protocol + "//" : "") + url.hostname, + port: Number(url.port || 80), + username: url.username, + password: url.password, }; } From ad73f4eaa58bfde4d710d8a276d08db6ea4891d1 Mon Sep 17 00:00:00 2001 From: ferenci84 Date: Fri, 21 Feb 2025 17:59:56 +0100 Subject: [PATCH 005/127] modify condition to ignore non-file URIs in RecentlyEditedTracker --- extensions/vscode/src/autocomplete/recentlyEdited.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 69b9b4d0f..d32f362dd 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -47,7 +47,7 @@ export class RecentlyEditedTracker { editedRange: Omit, ): Promise { - if (editedRange.uri.scheme === "output") { + if (editedRange.uri.scheme !== "file") { return; } @@ -83,7 +83,6 @@ export class RecentlyEditedTracker { RecentlyEditedTracker.maxRecentlyEditedRanges, ); } - } private insertDocument(uri: vscode.Uri): void { From 15e93dd5d0dc3b5dcd00504833beacbddbfe44f3 Mon Sep 17 00:00:00 2001 From: Ingo Eichhorst Date: Sun, 23 Feb 2025 13:16:50 +0100 Subject: [PATCH 006/127] fix: fixed misallignment in tests caused by linter --- core/edit/lazy/unifiedDiffApply.test.ts | 31 ++++++++++++++----------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/core/edit/lazy/unifiedDiffApply.test.ts b/core/edit/lazy/unifiedDiffApply.test.ts index c7a5a8370..f0eae9b64 100644 --- a/core/edit/lazy/unifiedDiffApply.test.ts +++ b/core/edit/lazy/unifiedDiffApply.test.ts @@ -46,8 +46,10 @@ describe("isUnifiedDiffFormat", () => { it("should return true in case of empty lines", () => { const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@ line1 + -line2 +newline2 + line3`; expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true); }); @@ -98,7 +100,9 @@ describe("applyUnifiedDiff", () => { it("should correctly apply multiple insertions and deletions", () => { const sourceCode = `package main + import "fmt" + func main() { fmt.Println("Hello") fmt.Println("World") @@ -375,22 +379,21 @@ func TestLargeNumbers(t *testing.T) { expect(result[0].line).toEqual("package main"); // 1st block - expect(result[21].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")"); - expect(result[22].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")"); + expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")"); + expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")"); + expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")"); // 2nd block - expect(result[60]).toEqual({type: "same", line: "\t}"}); - expect(result[61]).toEqual({type: "new", line: "\t"}); - expect(result[62]).toEqual({type: "new", line: "\t// Handle logarithmic operations"}); - expect(result[77]).toEqual({type: "new", line: ""}); - expect(result[78]).toEqual({type: "same", line: "\tif len(parts) != 3 {"}); + expect(result[56]).toEqual({type: "same", line: "\t}"}); + expect(result[57]).toEqual({type: "new", line: "\t"}); + expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"}); + expect(result[73]).toEqual({type: "new", line: ""}); + expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"}); // 3rd block - expect(result[145]).toEqual({type: "same", line: "}"}); - expect(result[146]).toEqual({type: "new", line: ""}); - expect(result[147]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"}); - expect(result[158]).toEqual({type: "new", line: "\t}"}); - expect(result[159]).toEqual({type: "same", line: ""}); - expect(result[160]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"}); - + expect(result[140]).toEqual({type: "same", line: "}"}); + expect(result[141]).toEqual({type: "new", line: ""}); + expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"}); + expect(result[153]).toEqual({type: "new", line: "\t}"}); + expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"}); }); it("should throw error when hunk cannot be matched to source", () => { From b02e6ba660b493fcd62742dfb2010c90b88a2656 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 27 Feb 2025 11:47:20 -0800 Subject: [PATCH 007/127] fix markdown patch --- .../markdown/utils/patchNestedMarkdown.ts | 68 ++++--------------- 1 file changed, 13 insertions(+), 55 deletions(-) diff --git a/gui/src/components/markdown/utils/patchNestedMarkdown.ts b/gui/src/components/markdown/utils/patchNestedMarkdown.ts index 29b305b26..b8be69ae7 100644 --- a/gui/src/components/markdown/utils/patchNestedMarkdown.ts +++ b/gui/src/components/markdown/utils/patchNestedMarkdown.ts @@ -8,9 +8,8 @@ // TODO support github-specific markdown as well, edge case */ - export const patchNestedMarkdown = (source: string): string => { - if (!source.match(/```(md|markdown)/)) return source; // For performance + if (!source.match(/```(\w+\.(md|markdown))/)) return source; // For performance // const start = Date.now(); let nestCount = 0; const lines = source.split("\n"); @@ -28,9 +27,18 @@ export const patchNestedMarkdown = (source: string): string => { } } else { // Enter the markdown block, start tracking nesting - if (line.startsWith("```md") || line.startsWith("```markdown")) { - nestCount = 1; - lines[i] = lines[i].replace(/```(md|markdown)/, "~~~"); // Replace backticks with tildes + if (line.startsWith("```")) { + const header = line.replaceAll("`", ""); + const file = header.split(" ")[0]; + + if (file) { + const ext = file.split(".").at(-1); + debugger; + if (ext === "md" || ext === "markdown") { + nestCount = 1; + lines[i] = lines[i].replaceAll("`", "~"); // Replace backticks with tildes + } + } } } } @@ -38,53 +46,3 @@ export const patchNestedMarkdown = (source: string): string => { // console.log(`patched in ${Date.now() - start}ms`); return out; }; - -// This version tries to detect if a codeblock without a language specified is a starter codeblock -// It tries again if didn't come back to root nesting, without checking for that ^ -// I didn't use for performance and also because the root nest check doesn't make sense mid-generation - -// export const patchNestedMarkdown = (source: string): string => { -// const start = Date.now(); - -// let attempts = 0; - -// while (attempts <= 2) { -// let nestCount = 0; -// const lines = source.split("\n"); -// const trimmedLines = lines.map((l) => l.trim()); -// for (let i = 0; i < trimmedLines.length; i++) { -// const line = trimmedLines[i]; -// if (nestCount) { -// if (line.match(/^`+$/)) { -// if (attempts === 0 && i !== lines.length && lines[i + 1] !== "") { -// nestCount++; -// continue; -// } -// if (nestCount === 1) lines[i] = "~~~"; -// nestCount--; -// } else if (line.startsWith("```")) { -// // Going into a nested codeblock -// nestCount++; -// } -// } else { -// // Enter the markdown block, start tracking nesting -// if (line.startsWith("```md") || line.startsWith("```markdown")) { -// nestCount = 1; -// lines[i] = lines[i].replace(/^```(md|markdown)/, "~~~"); // Replace backticks with tildes -// } -// } -// } -// if (nestCount === 0) { -// console.log( -// `patch successful in ${Date.now() - start} ms with ${attempts} attempts`, -// ); -// return lines.join("\n"); -// } -// attempts++; -// } - -// console.log( -// `patch failed in ${Date.now() - start} ms with ${attempts} attempts`, -// ); -// return source; -// }; From e2e8e3990a40fe4ff49d8ce6ac21f1a85e1f5b62 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 27 Feb 2025 11:49:01 -0800 Subject: [PATCH 008/127] cleanup --- gui/src/components/markdown/utils/patchNestedMarkdown.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/gui/src/components/markdown/utils/patchNestedMarkdown.ts b/gui/src/components/markdown/utils/patchNestedMarkdown.ts index b8be69ae7..10d5af1b2 100644 --- a/gui/src/components/markdown/utils/patchNestedMarkdown.ts +++ b/gui/src/components/markdown/utils/patchNestedMarkdown.ts @@ -33,7 +33,6 @@ export const patchNestedMarkdown = (source: string): string => { if (file) { const ext = file.split(".").at(-1); - debugger; if (ext === "md" || ext === "markdown") { nestCount = 1; lines[i] = lines[i].replaceAll("`", "~"); // Replace backticks with tildes From 037545fd77e2439afaf09408c12fd7a25dec35a9 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 1 Mar 2025 10:52:38 -0800 Subject: [PATCH 009/127] stale-issue-helper dry run --- .github/workflows/stale-issue-helper.yaml | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .github/workflows/stale-issue-helper.yaml diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml new file mode 100644 index 000000000..c6d4c415a --- /dev/null +++ b/.github/workflows/stale-issue-helper.yaml @@ -0,0 +1,25 @@ +name: "Label stale issues and PRs" +on: + schedule: + - cron: "*/5 * * * *" + +jobs: + stale: + runs-on: ubuntu-latest + strategy: + matrix: + assignee: [sestinj, Patrick-Erichsen, tomasz-stefaniak, RomneyDa] + steps: + - uses: actions/stale@v9 + with: + stale-issue-message: "This issue hasn't been updated in a while. @${{ matrix.assignee }} can you take a look?" + stale-pr-message: "This PR hasn't been updated in a while. @${{ matrix.assignee }} can you take a look?" + days-before-stale: 180 + days-before-close: -1 + days-before-pr-close: -1 + stale-issue-label: "stale" + stale-pr-label: "stale" + debug-only: true + exempt-issue-labels: "needs-triage,no-stale" + exempt-pr-labels: "no-stale,no-stale" + exempt-assignees: ${{ toJSON(fromJSON('["sestinj", "Patrick-Erichsen", "tomasz-stefaniak", "RomneyDa"]').filter(user => user != matrix.assignee)) }} From 3acbc68df82ebfd03ffbd13fdb317cf3c0e0f6df Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 1 Mar 2025 10:53:22 -0800 Subject: [PATCH 010/127] run on push --- .github/workflows/stale-issue-helper.yaml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index c6d4c415a..11c651cd7 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -1,7 +1,10 @@ name: "Label stale issues and PRs" on: + push: + branches: + - nate/stale-issue-helper schedule: - - cron: "*/5 * * * *" + - cron: "30 1 * * *" jobs: stale: From 17e5eb912f640f9cf19ef3d52ed8cfdd72e49a7b Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 1 Mar 2025 11:12:09 -0800 Subject: [PATCH 011/127] use excluded-assignees --- .github/workflows/stale-issue-helper.yaml | 16 +++++++++++++- scripts/getExcludedAssignees.js | 27 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 scripts/getExcludedAssignees.js diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 11c651cd7..4bfc83dee 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -13,6 +13,20 @@ jobs: matrix: assignee: [sestinj, Patrick-Erichsen, tomasz-stefaniak, RomneyDa] steps: + - uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version-file: .nvmrc + + - name: Compute excluded assignees + id: excluded-assignees + run: | + node ./scripts/getExcludedAssignees.js sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa ${{ matrix.assignee }} + + echo "excluded_assignees=$result" >> $GITHUB_OUTPUT + - uses: actions/stale@v9 with: stale-issue-message: "This issue hasn't been updated in a while. @${{ matrix.assignee }} can you take a look?" @@ -25,4 +39,4 @@ jobs: debug-only: true exempt-issue-labels: "needs-triage,no-stale" exempt-pr-labels: "no-stale,no-stale" - exempt-assignees: ${{ toJSON(fromJSON('["sestinj", "Patrick-Erichsen", "tomasz-stefaniak", "RomneyDa"]').filter(user => user != matrix.assignee)) }} + exempt-assignees: ${{ steps.excluded-assignees.outputs.excluded_assignees }} diff --git a/scripts/getExcludedAssignees.js b/scripts/getExcludedAssignees.js new file mode 100644 index 000000000..e6ac5904c --- /dev/null +++ b/scripts/getExcludedAssignees.js @@ -0,0 +1,27 @@ +#!/usr/bin/env node + +function removeStringFromList(list, stringToRemove) { + return list.filter((item) => item !== stringToRemove); +} + +function main() { + // Get command line arguments + const args = process.argv.slice(2); + + if (args.length < 2) { + console.error( + "Usage: node script.js ", + ); + process.exit(1); + } + + const list = args[0].split(","); + const stringToRemove = args[1]; + + const result = removeStringFromList(list, stringToRemove); + + // Output the result as comma-separated values + console.log(result.join(",")); +} + +main(); From 22c296867638ff5a149c96a2ae7a128516f8f8c5 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 1 Mar 2025 11:17:55 -0800 Subject: [PATCH 012/127] include only assigned --- .github/workflows/stale-issue-helper.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 4bfc83dee..f2780530f 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -40,3 +40,4 @@ jobs: exempt-issue-labels: "needs-triage,no-stale" exempt-pr-labels: "no-stale,no-stale" exempt-assignees: ${{ steps.excluded-assignees.outputs.excluded_assignees }} + include-only-assigned: true From a6160ce3433427ba5258645290b028a3291540e5 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 1 Mar 2025 11:20:05 -0800 Subject: [PATCH 013/127] fx --- .github/workflows/stale-issue-helper.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index f2780530f..2c5a00b19 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -23,8 +23,9 @@ jobs: - name: Compute excluded assignees id: excluded-assignees run: | - node ./scripts/getExcludedAssignees.js sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa ${{ matrix.assignee }} + result=$(node ./scripts/getExcludedAssignees.js sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa ${{ matrix.assignee }}) + echo "Result: $result" echo "excluded_assignees=$result" >> $GITHUB_OUTPUT - uses: actions/stale@v9 From 0b78baf289283ab73359980d29a3648064220538 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 1 Mar 2025 11:26:54 -0800 Subject: [PATCH 014/127] env --- .github/workflows/stale-issue-helper.yaml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 2c5a00b19..6b8747e8a 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -9,9 +9,11 @@ on: jobs: stale: runs-on: ubuntu-latest + env: + TEAM_MEMBERS: "sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa" strategy: matrix: - assignee: [sestinj, Patrick-Erichsen, tomasz-stefaniak, RomneyDa] + assignee: ${{ env.TEAM_MEMBERS }} steps: - uses: actions/checkout@v4 @@ -23,7 +25,7 @@ jobs: - name: Compute excluded assignees id: excluded-assignees run: | - result=$(node ./scripts/getExcludedAssignees.js sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa ${{ matrix.assignee }}) + result=$(node ./scripts/getExcludedAssignees.js ${{ env.TEAM_MEMBERS }} ${{ matrix.assignee }}) echo "Result: $result" echo "excluded_assignees=$result" >> $GITHUB_OUTPUT @@ -39,6 +41,6 @@ jobs: stale-pr-label: "stale" debug-only: true exempt-issue-labels: "needs-triage,no-stale" - exempt-pr-labels: "no-stale,no-stale" + exempt-pr-labels: "no-stale" exempt-assignees: ${{ steps.excluded-assignees.outputs.excluded_assignees }} include-only-assigned: true From db35636b71c05e787efc1af35ece6cfd993dd759 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 1 Mar 2025 11:28:02 -0800 Subject: [PATCH 015/127] fix --- .github/workflows/stale-issue-helper.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 6b8747e8a..891908f7c 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -13,7 +13,7 @@ jobs: TEAM_MEMBERS: "sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa" strategy: matrix: - assignee: ${{ env.TEAM_MEMBERS }} + assignee: [sestinj, Patrick-Erichsen, tomasz-stefaniak, RomneyDa] steps: - uses: actions/checkout@v4 From 2376ed817a15187ea1e8f2f2545881b4d2788aa4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 2 Mar 2025 15:51:37 -0800 Subject: [PATCH 016/127] handle URI query params --- core/core.ts | 20 ++++++---- core/index.d.ts | 3 +- core/protocol/coreWebview.ts | 5 ++- extensions/vscode/package.json | 1 + .../vscode/src/extension/VsCodeExtension.ts | 39 ++++++++++++++++++- .../vscode/src/stubs/WorkOsAuthProvider.ts | 13 +++---- extensions/vscode/src/stubs/uriHandler.ts | 10 +++++ gui/src/components/TabBar/TabBar.tsx | 4 -- 8 files changed, 73 insertions(+), 22 deletions(-) create mode 100644 extensions/vscode/src/stubs/uriHandler.ts diff --git a/core/core.ts b/core/core.ts index 6d78ca855..c5b5a064a 100644 --- a/core/core.ts +++ b/core/core.ts @@ -950,15 +950,21 @@ export class Core { }); // - on("didChangeSelectedProfile", (msg) => { - void this.configHandler.setSelectedProfile(msg.data.id); - void this.configHandler.reloadConfig(); + on("didChangeSelectedProfile", async (msg) => { + await this.configHandler.setSelectedProfile(msg.data.id); + await this.configHandler.reloadConfig(); }); - on("didChangeSelectedOrg", (msg) => { - void this.configHandler.setSelectedOrgId(msg.data.id); - void this.configHandler.reloadConfig(); - void this.configHandler.loadAssistantsForSelectedOrg(); + on("didChangeSelectedOrg", async (msg) => { + await this.configHandler.setSelectedOrgId(msg.data.id); + await this.configHandler.loadAssistantsForSelectedOrg(); + if (msg.data.profileId) { + this.invoke("didChangeSelectedProfile", { + id: msg.data.profileId, + }); + } else { + await this.configHandler.reloadConfig(); + } }); on("didChangeControlPlaneSessionInfo", async (msg) => { diff --git a/core/index.d.ts b/core/index.d.ts index 7cbf0e25b..f34a7fbc9 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -920,8 +920,9 @@ export interface BaseCompletionOptions { } export interface ModelCapability { - uploadImage?: boolean; tools?: boolean; + uploadImage?: boolean; + outputImage?: boolean; } export interface ModelDescription { diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 67b5919a4..5e71e5f11 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -5,7 +5,10 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { didChangeSelectedProfile: [{ id: string | null }, void]; - didChangeSelectedOrg: [{ id: string | null }, void]; + didChangeSelectedOrg: [ + { id: string | null; profileId?: string | null }, + void, + ]; }; export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & { didChangeAvailableProfiles: [ diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 366da7ff5..9ee40b4a0 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -52,6 +52,7 @@ "llama" ], "activationEvents": [ + "onUri", "onStartupFinished", "onView:continueGUIView" ], diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 8953c91a0..814f6be97 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -28,6 +28,7 @@ import { registerAllPromptFilesCompletionProviders } from "../lang-server/prompt import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { QuickEdit } from "../quickEdit/QuickEditQuickPick"; import { setupRemoteConfigSync } from "../stubs/activation"; +import { UriEventHandler } from "../stubs/uriHandler"; import { getControlPlaneSessionInfo, WorkOsAuthProvider, @@ -55,10 +56,11 @@ export class VsCodeExtension { private battery: Battery; private workOsAuthProvider: WorkOsAuthProvider; private fileSearch: FileSearch; + private uriHandler = new UriEventHandler(); constructor(context: vscode.ExtensionContext) { // Register auth provider - this.workOsAuthProvider = new WorkOsAuthProvider(context); + this.workOsAuthProvider = new WorkOsAuthProvider(context, this.uriHandler); this.workOsAuthProvider.refreshSessions(); context.subscriptions.push(this.workOsAuthProvider); @@ -193,6 +195,41 @@ export class VsCodeExtension { ), ); + // Handle uri events + this.uriHandler.event((uri) => { + const queryParams = new URLSearchParams(uri.query); + let profileId = queryParams.get("profile_id"); + let orgId = queryParams.get("org_id"); + + if (orgId) { + if (orgId === "null") { + orgId = null; + } + // In case org id is passed with profile id + // Make sure org is updated before profile is set + if (profileId) { + if (profileId === "null") { + profileId = null; + } + this.core.invoke("didChangeSelectedOrg", { + id: orgId, + profileId, + }); + } else { + this.core.invoke("didChangeSelectedOrg", { + id: orgId, + }); + } + } else if (profileId) { + if (profileId === "null") { + profileId = null; + } + this.core.invoke("didChangeSelectedProfile", { + id: profileId, + }); + } + }); + // Battery this.battery = new Battery(); context.subscriptions.push(this.battery); diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 8f0e00c8c..30151d565 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -15,13 +15,13 @@ import { ExtensionContext, ProgressLocation, Uri, - UriHandler, window, workspace, } from "vscode"; import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; import { SecretStorage } from "./SecretStorage"; +import { UriEventHandler } from "./uriHandler"; const AUTH_NAME = "Continue"; @@ -35,11 +35,6 @@ const controlPlaneEnv = getControlPlaneEnvSync( const SESSIONS_SECRET_KEY = `${controlPlaneEnv.AUTH_TYPE}.sessions`; -class UriEventHandler extends EventEmitter implements UriHandler { - public handleUri(uri: Uri) { - this.fire(uri); - } -} // Function to generate a random string of specified length function generateRandomString(length: number): string { const possibleCharacters = @@ -83,13 +78,15 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { string, { promise: Promise; cancel: EventEmitter } >(); - private _uriHandler = new UriEventHandler(); private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes private secretStorage: SecretStorage; - constructor(private readonly context: ExtensionContext) { + constructor( + private readonly context: ExtensionContext, + private readonly _uriHandler: UriEventHandler, + ) { this._disposable = Disposable.from( authentication.registerAuthenticationProvider( controlPlaneEnv.AUTH_TYPE, diff --git a/extensions/vscode/src/stubs/uriHandler.ts b/extensions/vscode/src/stubs/uriHandler.ts new file mode 100644 index 000000000..cc324f856 --- /dev/null +++ b/extensions/vscode/src/stubs/uriHandler.ts @@ -0,0 +1,10 @@ +import * as vscode from "vscode"; + +export class UriEventHandler + extends vscode.EventEmitter + implements vscode.UriHandler +{ + public handleUri(uri: vscode.Uri) { + this.fire(uri); + } +} diff --git a/gui/src/components/TabBar/TabBar.tsx b/gui/src/components/TabBar/TabBar.tsx index 859f6e90c..3b87a23c6 100644 --- a/gui/src/components/TabBar/TabBar.tsx +++ b/gui/src/components/TabBar/TabBar.tsx @@ -155,10 +155,6 @@ export function TabBar() { ); const tabs = useSelector((state: RootState) => state.tabs.tabs); - useEffect(() => { - console.log("session", currentSession); - }, [currentSession.id]); - // Simple UUID generator for our needs const generateId = useCallback(() => { return Date.now().toString(36) + Math.random().toString(36).substring(2); From b6bfb222f94b2528d33579cdff67be011dda8e55 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 19:53:47 -0800 Subject: [PATCH 017/127] auto close --- .github/workflows/stale-issue-helper.yaml | 31 +++-------------------- scripts/getExcludedAssignees.js | 27 -------------------- 2 files changed, 4 insertions(+), 54 deletions(-) delete mode 100644 scripts/getExcludedAssignees.js diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 891908f7c..e05e45c40 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -9,38 +9,15 @@ on: jobs: stale: runs-on: ubuntu-latest - env: - TEAM_MEMBERS: "sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa" - strategy: - matrix: - assignee: [sestinj, Patrick-Erichsen, tomasz-stefaniak, RomneyDa] steps: - - uses: actions/checkout@v4 - - - name: Set up Node.js - uses: actions/setup-node@v4 - with: - node-version-file: .nvmrc - - - name: Compute excluded assignees - id: excluded-assignees - run: | - result=$(node ./scripts/getExcludedAssignees.js ${{ env.TEAM_MEMBERS }} ${{ matrix.assignee }}) - - echo "Result: $result" - echo "excluded_assignees=$result" >> $GITHUB_OUTPUT - - uses: actions/stale@v9 with: - stale-issue-message: "This issue hasn't been updated in a while. @${{ matrix.assignee }} can you take a look?" - stale-pr-message: "This PR hasn't been updated in a while. @${{ matrix.assignee }} can you take a look?" - days-before-stale: 180 - days-before-close: -1 - days-before-pr-close: -1 + close-issue-message: "This issue was closed because it hasn't been updated for 120 days. If it's still important, please reopen + comment and we will glady take another look." + stale-issue-message: "It looks like this issue hasn't been updated in 90 days. If there's still no activity after 120 days, it will be closed." + days-before-stale: 90 + days-before-close: 120 stale-issue-label: "stale" stale-pr-label: "stale" debug-only: true exempt-issue-labels: "needs-triage,no-stale" exempt-pr-labels: "no-stale" - exempt-assignees: ${{ steps.excluded-assignees.outputs.excluded_assignees }} - include-only-assigned: true diff --git a/scripts/getExcludedAssignees.js b/scripts/getExcludedAssignees.js deleted file mode 100644 index e6ac5904c..000000000 --- a/scripts/getExcludedAssignees.js +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env node - -function removeStringFromList(list, stringToRemove) { - return list.filter((item) => item !== stringToRemove); -} - -function main() { - // Get command line arguments - const args = process.argv.slice(2); - - if (args.length < 2) { - console.error( - "Usage: node script.js ", - ); - process.exit(1); - } - - const list = args[0].split(","); - const stringToRemove = args[1]; - - const result = removeStringFromList(list, stringToRemove); - - // Output the result as comma-separated values - console.log(result.join(",")); -} - -main(); From 2f71a8edf0e8ef9c686ee8db6a41b3cbf7c22051 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 19:55:14 -0800 Subject: [PATCH 018/127] don't close/mark prs stale --- .github/workflows/stale-issue-helper.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index e05e45c40..2e0f0fdcd 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -16,6 +16,8 @@ jobs: stale-issue-message: "It looks like this issue hasn't been updated in 90 days. If there's still no activity after 120 days, it will be closed." days-before-stale: 90 days-before-close: 120 + days-before-pr-stale: -1 + days-before-pr-close: -1 stale-issue-label: "stale" stale-pr-label: "stale" debug-only: true From 567d2f146e6addffd44b849648c39a1b8e0bbd4d Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:00:59 -0800 Subject: [PATCH 019/127] update messages --- .github/workflows/stale-issue-helper.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 2e0f0fdcd..b5f32c704 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -13,7 +13,7 @@ jobs: - uses: actions/stale@v9 with: close-issue-message: "This issue was closed because it hasn't been updated for 120 days. If it's still important, please reopen + comment and we will glady take another look." - stale-issue-message: "It looks like this issue hasn't been updated in 90 days. If there's still no activity after 120 days, it will be closed." + stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after 120 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." days-before-stale: 90 days-before-close: 120 days-before-pr-stale: -1 From d0b7d1a0e0b4f15562f70a2d6443f6dc83040a09 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:09:58 -0800 Subject: [PATCH 020/127] first round: close issues before 90 days --- .github/workflows/stale-issue-helper.yaml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index b5f32c704..70159939e 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -14,12 +14,11 @@ jobs: with: close-issue-message: "This issue was closed because it hasn't been updated for 120 days. If it's still important, please reopen + comment and we will glady take another look." stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after 120 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." - days-before-stale: 90 - days-before-close: 120 + days-before-stale: -1 + days-before-close: 90 days-before-pr-stale: -1 days-before-pr-close: -1 stale-issue-label: "stale" stale-pr-label: "stale" - debug-only: true - exempt-issue-labels: "needs-triage,no-stale" + exempt-issue-labels: "needs-triage,no-stale,high,highest" exempt-pr-labels: "no-stale" From d4e46a946bd8551659aec1cd26c4645fa3e76225 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:18:40 -0800 Subject: [PATCH 021/127] update msg --- .github/workflows/stale-issue-helper.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 70159939e..4e6e39d3d 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -12,7 +12,7 @@ jobs: steps: - uses: actions/stale@v9 with: - close-issue-message: "This issue was closed because it hasn't been updated for 120 days. If it's still important, please reopen + comment and we will glady take another look." + close-issue-message: "This issue was closed because it hasn't been updated for 120 days. If it's still important, please reopen + comment and we'll gladly take another look!" stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after 120 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." days-before-stale: -1 days-before-close: 90 From dd9ac81b44213f27eff617c9e70bded6454a39c9 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:19:51 -0800 Subject: [PATCH 022/127] mark stale --- .github/workflows/stale-issue-helper.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 4e6e39d3d..30e1ad773 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -13,8 +13,8 @@ jobs: - uses: actions/stale@v9 with: close-issue-message: "This issue was closed because it hasn't been updated for 120 days. If it's still important, please reopen + comment and we'll gladly take another look!" - stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after 120 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." - days-before-stale: -1 + # stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after 120 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." + days-before-stale: 90 days-before-close: 90 days-before-pr-stale: -1 days-before-pr-close: -1 From d9d79b259ee4969d409b7497362d7038f8b4fc2d Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:22:52 -0800 Subject: [PATCH 023/127] mark stale --- .github/workflows/stale-issue-helper.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 30e1ad773..9df56ba06 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -12,10 +12,10 @@ jobs: steps: - uses: actions/stale@v9 with: - close-issue-message: "This issue was closed because it hasn't been updated for 120 days. If it's still important, please reopen + comment and we'll gladly take another look!" - # stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after 120 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." + close-issue-message: "This issue was closed because it hasn't been updated for 100 days. If it's still important, please reopen + comment and we'll gladly take another look!" + stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." days-before-stale: 90 - days-before-close: 90 + days-before-close: 100 days-before-pr-stale: -1 days-before-pr-close: -1 stale-issue-label: "stale" From 899c9f5349dd5a5bc97a8177ffbc75715b364ac8 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:24:07 -0800 Subject: [PATCH 024/127] permissions --- .github/workflows/stale-issue-helper.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 9df56ba06..f4f9d46c7 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -8,6 +8,9 @@ on: jobs: stale: + permissions: + issues: write + pull-requests: write runs-on: ubuntu-latest steps: - uses: actions/stale@v9 From 8ac5f1dc213d56cac004459d516cdca7abbfaaae Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:37:54 -0800 Subject: [PATCH 025/127] update name --- .github/workflows/stale-issue-helper.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index f4f9d46c7..6f4ddd0b3 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -1,4 +1,4 @@ -name: "Label stale issues and PRs" +name: "Label and close stale issues" on: push: branches: From dbfebd5a734fbb661d6e7009e3d31030c6de8445 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:40:28 -0800 Subject: [PATCH 026/127] update close --- .github/workflows/stale-issue-helper.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 6f4ddd0b3..ce58d0933 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -15,10 +15,10 @@ jobs: steps: - uses: actions/stale@v9 with: - close-issue-message: "This issue was closed because it hasn't been updated for 100 days. If it's still important, please reopen + comment and we'll gladly take another look!" + close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!" stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." days-before-stale: 90 - days-before-close: 100 + days-before-close: 10 days-before-pr-stale: -1 days-before-pr-close: -1 stale-issue-label: "stale" From 937b74f380d5b49f57c71f5cce19f9bf843443ee Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:44:09 -0800 Subject: [PATCH 027/127] update title --- .github/workflows/stale-issue-helper.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index ce58d0933..38e2a0226 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -1,4 +1,4 @@ -name: "Label and close stale issues" +name: "Label / close stale issues" on: push: branches: From 3fd2685a610cbaf26c624165ee72bbec0551bf7c Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:47:06 -0800 Subject: [PATCH 028/127] increase ops --- .github/workflows/stale-issue-helper.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 38e2a0226..c37a3aa1b 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -21,6 +21,7 @@ jobs: days-before-close: 10 days-before-pr-stale: -1 days-before-pr-close: -1 + operations-per-run: 100 stale-issue-label: "stale" stale-pr-label: "stale" exempt-issue-labels: "needs-triage,no-stale,high,highest" From 75387a18a0cbf710c117f066feaec83d0b36c635 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 20:48:47 -0800 Subject: [PATCH 029/127] increase ops --- .github/workflows/stale-issue-helper.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index c37a3aa1b..8f10ebcb5 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -21,7 +21,7 @@ jobs: days-before-close: 10 days-before-pr-stale: -1 days-before-pr-close: -1 - operations-per-run: 100 + operations-per-run: 2000 stale-issue-label: "stale" stale-pr-label: "stale" exempt-issue-labels: "needs-triage,no-stale,high,highest" From 58b5ad94cca789be64e91dad6f5b958d532d501c Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 2 Mar 2025 21:01:19 -0800 Subject: [PATCH 030/127] remove push trigger --- .github/workflows/stale-issue-helper.yaml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 8f10ebcb5..067f4c60f 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -1,8 +1,5 @@ name: "Label / close stale issues" on: - push: - branches: - - nate/stale-issue-helper schedule: - cron: "30 1 * * *" @@ -21,7 +18,7 @@ jobs: days-before-close: 10 days-before-pr-stale: -1 days-before-pr-close: -1 - operations-per-run: 2000 + operations-per-run: 1000 stale-issue-label: "stale" stale-pr-label: "stale" exempt-issue-labels: "needs-triage,no-stale,high,highest" From e997f40b16c782c8d3d62618f00aa61d5c0898d7 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 2 Mar 2025 22:39:35 -0800 Subject: [PATCH 031/127] clean up --- core/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index f34a7fbc9..7cbf0e25b 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -920,9 +920,8 @@ export interface BaseCompletionOptions { } export interface ModelCapability { - tools?: boolean; uploadImage?: boolean; - outputImage?: boolean; + tools?: boolean; } export interface ModelDescription { From 753b3bc938944882d8523053458f3de2c21d08b4 Mon Sep 17 00:00:00 2001 From: Simon Chauvin <34301767+chauvinSimon@users.noreply.github.com> Date: Mon, 3 Mar 2025 14:29:17 +0100 Subject: [PATCH 032/127] Update codebase.mdx - fix yaml against LanceError To prevent the popup of VSCode Error: `Error getting context items from codebase: Error: lance error: LanceError(IO): k must be positive ...` --- docs/docs/customize/deep-dives/codebase.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/customize/deep-dives/codebase.mdx b/docs/docs/customize/deep-dives/codebase.mdx index 24256672e..409ecd080 100644 --- a/docs/docs/customize/deep-dives/codebase.mdx +++ b/docs/docs/customize/deep-dives/codebase.mdx @@ -49,8 +49,8 @@ There are a few options that let you configure the behavior of the `@codebase` c context: - provider: codebase params: - nRetrieve: 25, - nFinal: 5, + nRetrieve: 25 + nFinal: 5 useReranking: true ``` From 892f89e0e23f9ef1cac2eef40d82c25ba8abc153 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 3 Mar 2025 16:08:15 -0800 Subject: [PATCH 033/127] use URI.resolve --- core/util/uri.ts | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/core/util/uri.ts b/core/util/uri.ts index 13d7956ac..a5a84d3b4 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -116,19 +116,30 @@ export function getLastNUriRelativePathParts( } export function joinPathsToUri(uri: string, ...pathSegments: string[]) { - const components = URI.parse(uri); + let baseUri = uri; + if (baseUri.at(-1) !== "/") { + baseUri += "/"; + } const segments = pathSegments.map((segment) => pathToUriPathSegment(segment)); - components.path = `${components.path}/${segments.join("/")}`; - return URI.serialize(components); + return URI.resolve(baseUri, segments.join("/")); } +// const components = URI.parse(uri); +// return URI.serialize(components); +// components.path = `${components.path}/${segments.join("/")}`; + export function joinEncodedUriPathSegmentToUri( uri: string, pathSegment: string, ) { - const components = URI.parse(uri); - components.path = `${components.path}/${pathSegment}`; - return URI.serialize(components); + let baseUri = uri; + if (baseUri.at(-1) !== "/") { + baseUri += "/"; + } + return URI.resolve(baseUri, pathSegment); + // const components = URI.parse(uri); + // components.path = `${components.path}/${pathSegment}`; + // return URI.serialize(components); } export function getShortestUniqueRelativeUriPaths( From a8d9a312a6efb935edca0de7cd8e77fb6d9a2660 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 3 Mar 2025 16:12:30 -0800 Subject: [PATCH 034/127] cleanup --- core/util/uri.ts | 7 ------- 1 file changed, 7 deletions(-) diff --git a/core/util/uri.ts b/core/util/uri.ts index a5a84d3b4..e180a0a69 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -124,10 +124,6 @@ export function joinPathsToUri(uri: string, ...pathSegments: string[]) { return URI.resolve(baseUri, segments.join("/")); } -// const components = URI.parse(uri); -// return URI.serialize(components); -// components.path = `${components.path}/${segments.join("/")}`; - export function joinEncodedUriPathSegmentToUri( uri: string, pathSegment: string, @@ -137,9 +133,6 @@ export function joinEncodedUriPathSegmentToUri( baseUri += "/"; } return URI.resolve(baseUri, pathSegment); - // const components = URI.parse(uri); - // components.path = `${components.path}/${pathSegment}`; - // return URI.serialize(components); } export function getShortestUniqueRelativeUriPaths( From 93193606654d001ff0d98b1c40677ff8aa6a4d88 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 4 Mar 2025 14:06:07 -0800 Subject: [PATCH 035/127] blocktype param --- docs/docs/customize/deep-dives/development-data.md | 2 +- docs/docs/customize/deep-dives/docs.mdx | 2 +- docs/docs/customize/deep-dives/prompt-files.md | 2 +- docs/docs/customize/deep-dives/rules.md | 2 +- docs/docs/customize/tools.mdx | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/docs/customize/deep-dives/development-data.md b/docs/docs/customize/deep-dives/development-data.md index 976c02833..da9f5136c 100644 --- a/docs/docs/customize/deep-dives/development-data.md +++ b/docs/docs/customize/deep-dives/development-data.md @@ -14,7 +14,7 @@ You can read more about how development data is generated as a byproduct of LLM- You can also configure custom destinations for your data, including remote HTTP endpoints and local file directories. -For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&block=data). +For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&blockType=data). See more details about adding `data` blocks to your configuration files in the [YAML specification](../../yaml-reference.md#data) diff --git a/docs/docs/customize/deep-dives/docs.mdx b/docs/docs/customize/deep-dives/docs.mdx index 7a5be2263..4a2aac376 100644 --- a/docs/docs/customize/deep-dives/docs.mdx +++ b/docs/docs/customize/deep-dives/docs.mdx @@ -64,7 +64,7 @@ Pre-indexed docs are only available in VS Code because the VS Code extension shi ### Hub `docs` Blocks -@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&block=docs). +@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs). ### Through the `@Docs` Context Provider diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index 1ab90e94a..f5c834c17 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -4,7 +4,7 @@ title: Prompt files Prompt files provide a convenient way to standardize common patterns and share a collection of LLM prompts with your team. They make it easy to build and use these prompts. -On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&block=rules). +On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=rules). Prompt files can also be stored within your project's root directory as `.prompt` files. See below. diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index eac9137ce..59f816c15 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -9,7 +9,7 @@ Rules are used to provide instructions to **chat** models. They are inserted int ## Hub `rules` blocks -Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&block=rules) in the Hub. +Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. ## `.continuerules` diff --git a/docs/docs/customize/tools.mdx b/docs/docs/customize/tools.mdx index 45280697e..1aad549f1 100644 --- a/docs/docs/customize/tools.mdx +++ b/docs/docs/customize/tools.mdx @@ -30,7 +30,7 @@ Currently custom tools can be configured using the [Model Context Protocol](http MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can explore available MCP server blocks [here](https://hub.continue.dev/explore/mcp). -To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&block=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md): +To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md): From 9404e00e91aed089cd3a8cd344a138af95f83740 Mon Sep 17 00:00:00 2001 From: Piotr Czekaj Date: Wed, 5 Mar 2025 11:47:53 +0100 Subject: [PATCH 036/127] Fix invalid mime type in Jetbrains IDE connection.url.toString() contains values like: jar:file:/Users/some.username/Library/Application%20Support/JetBrains/IntelliJIdea2024.3/plugins/continue-intellij-extension/lib/instrumented-continue-intellij-extension-1.0.2.jar!/webview/index.html if user has "js" in his home folder name then index.html will be treated as text/javascript and continue dev sidebar will output html source code instead of working app --- .../factories/CustomhandlerFactory.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt index 1c683253d..489ef9006 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt @@ -111,7 +111,10 @@ class OpenedConnection(private val connection: URLConnection?) : ) { try { if (connection != null) { - val url = connection.url.toString() + val fullUrl = connection.url.toString() + // Extract only the resource path after the JAR prefix to prevent incorrect mime type matching + // (e.g., if a user's home folder contains "js" in the path) + val url = fullUrl.substringAfterLast("jar!/", fullUrl) when { url.contains("css") -> cefResponse.mimeType = "text/css" url.contains("js") -> cefResponse.mimeType = "text/javascript" From f5a76456f9e17f8e774cb4d81e78a5cf434780a0 Mon Sep 17 00:00:00 2001 From: Nicholas Weatherburn Date: Wed, 5 Mar 2025 17:23:43 -0500 Subject: [PATCH 037/127] Enable Custom LLMs to use Tools by allowing customStreamChat to return ChatMessages as well as strings --- core/index.d.ts | 2 +- core/llm/llms/CustomLLM.ts | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 7cbf0e25b..b92370395 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -543,7 +543,7 @@ export interface CustomLLMWithOptionals { signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, - ) => AsyncGenerator; + ) => AsyncGenerator; listModels?: ( fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => Promise; diff --git a/core/llm/llms/CustomLLM.ts b/core/llm/llms/CustomLLM.ts index 062f141f6..e04ea0ab7 100644 --- a/core/llm/llms/CustomLLM.ts +++ b/core/llm/llms/CustomLLM.ts @@ -1,4 +1,5 @@ import { ChatMessage, CompletionOptions, CustomLLM } from "../../index.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; class CustomLLMClass extends BaseLLM { @@ -18,7 +19,7 @@ class CustomLLMClass extends BaseLLM { signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, - ) => AsyncGenerator; + ) => AsyncGenerator; constructor(custom: CustomLLM) { super(custom.options || { model: "custom" }); @@ -38,7 +39,11 @@ class CustomLLMClass extends BaseLLM { options, (...args) => this.fetch(...args), )) { - yield { role: "assistant", content }; + if (typeof content === "string") { + yield { role: "assistant", content }; + } else { + yield content; + } } } else { for await (const update of super._streamChat(messages, signal, options)) { @@ -68,7 +73,11 @@ class CustomLLMClass extends BaseLLM { options, (...args) => this.fetch(...args), )) { - yield content; + if (typeof content === "string") { + yield content; + } else { + yield renderChatMessage(content); + } } } else { throw new Error( From f6d08a3d0ad3de8e33c4554538a4a8d3cae4469b Mon Sep 17 00:00:00 2001 From: sammyvoncheese Date: Wed, 5 Mar 2025 19:08:08 -0500 Subject: [PATCH 039/127] Update toolSupport.ts 3 Ollama logic changes. - Added logic to pull off the model name from a model which includes an extended path like "hf.co/DevQuasar/ibm-granite.granite-3.2-8b-instruct-preview-GGUF:F16" - added a "granite-3" check to support Hf format for the model name - changed the string compare to look for the model names in the whole string --- core/llm/toolSupport.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 1e23cbf3e..ebe6599f8 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -57,9 +57,18 @@ export const PROVIDER_TOOL_SUPPORT: Record< }, // https://ollama.com/search?c=tools ollama: (model) => { + let modelName = ""; + // Extract the model name after the last slash to support other registries + if(model.includes("/")) { + let parts = model.split('/'); + modelName = parts[parts.length - 1]; + } else { + modelName = model; + } + if ( ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( - (part) => model.toLowerCase().includes(part), + (part) => modelName.toLowerCase().includes(part), ) ) { return false; @@ -79,10 +88,11 @@ export const PROVIDER_TOOL_SUPPORT: Record< "nemotron", "llama3-groq", "granite3", + "granite-3", "aya-expanse", "firefunction-v2", "mistral", - ].some((part) => model.toLowerCase().startsWith(part)) + ].some((part) => modelName.toLowerCase().includes(part)) ) { return true; } From a72cb1c47cdf351ae74c445559b3a7c5dc97522d Mon Sep 17 00:00:00 2001 From: Ian Dolge Date: Wed, 5 Mar 2025 17:50:44 -0800 Subject: [PATCH 040/127] Filter for files ending with .prompt in global Prompt Files --- core/util/paths.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/util/paths.ts b/core/util/paths.ts index bd5a69e1a..31ed8bb02 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -368,7 +368,7 @@ export function readAllGlobalPromptFiles( if (stats.isDirectory()) { const nestedPromptFiles = readAllGlobalPromptFiles(filepath); promptFiles.push(...nestedPromptFiles); - } else { + } else if (file.endsWith(".prompt")) { const content = fs.readFileSync(filepath, "utf8"); promptFiles.push({ path: filepath, content }); } From dbdf72ea84215e59caa5fe9ea159248a56413118 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 13 Feb 2025 12:10:19 +0100 Subject: [PATCH 041/127] Pull missing ollama models Signed-off-by: Fred Bricon --- core/index.d.ts | 4 ++ core/llm/index.ts | 22 ++++++- core/llm/llms/Ollama.ts | 37 +++++++++++- core/util/ollamaHelper.ts | 60 ++++++++++++++++++- .../src/autocomplete/completionProvider.ts | 21 +++++-- extensions/vscode/src/commands.ts | 44 +++++++++++++- extensions/vscode/src/webviewProtocol.ts | 50 ++++++++++------ gui/src/pages/gui/StreamError.tsx | 12 ++-- 8 files changed, 214 insertions(+), 36 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 7cbf0e25b..c0c7e1453 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -163,6 +163,10 @@ export interface ILLM extends LLMOptions { ): string | ChatMessage[]; } +export interface ModelInstaller { + installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise; +} + export type ContextProviderType = "normal" | "query" | "submenu"; export interface ContextProviderDescription { diff --git a/core/llm/index.ts b/core/llm/index.ts index ccbad6699..3abed5f0b 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -19,6 +19,7 @@ import { LLMFullCompletionOptions, LLMOptions, ModelCapability, + ModelInstaller, PromptLog, PromptTemplate, RequestOptions, @@ -58,6 +59,17 @@ import { toFimBody, } from "./openaiTypeConverters.js"; + +export class LLMError extends Error { + constructor(message: string, public llm: ILLM) { + super(message); + } +} + +export function isModelInstaller(provider: any): provider is ModelInstaller { + return provider && typeof provider.installModel === 'function'; +} + export abstract class BaseLLM implements ILLM { static providerName: string; static defaultOptions: Partial | undefined = undefined; @@ -380,9 +392,11 @@ export abstract class BaseLLM implements ILLM { if (!resp.ok) { let text = await resp.text(); if (resp.status === 404 && !resp.url.includes("/v1")) { - if (text.includes("try pulling it first")) { - const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); + const error = JSON.parse(text)?.error?.replace(/"/g, "'"); + let model = error?.match(/model '(.*)' not found/)?.[1]; + if (model && resp.url.match("127.0.0.1:11434")) { text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; + throw new LLMError(text, this);// No need to add HTTP status details } else if (text.includes("/api/chat")) { text = "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; @@ -442,6 +456,10 @@ export abstract class BaseLLM implements ILLM { throw new Error(message); } } + //if e instance of LLMError, rethrow + if (e instanceof LLMError) { + throw e; + } throw new Error(e.message); } }; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index ee822eb27..675fd8663 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,9 +1,10 @@ import { JSONSchema7, JSONSchema7Object } from "json-schema"; -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { ChatMessage, CompletionOptions, ModelInstaller, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; +import { getRemoteModelInfo } from "../../util/ollamaHelper.js"; type OllamaChatMessage = { role: "tool" | "user" | "assistant" | "system"; @@ -123,7 +124,7 @@ interface OllamaTool { }; } -class Ollama extends BaseLLM { +class Ollama extends BaseLLM implements ModelInstaller{ static providerName = "ollama"; static defaultOptions: Partial = { apiBase: "http://localhost:11434/", @@ -574,6 +575,38 @@ class Ollama extends BaseLLM { } return embedding; } + + public async installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise { + const modelInfo = await getRemoteModelInfo(modelName, signal); + if (!modelInfo) { + throw new Error(`'${modelName}' not found in the Ollama registry!`); + } + const response = await fetch(this.getEndpoint("api/pull"), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ name: modelName }), + signal + }); + + const reader = response.body?.getReader(); + //TODO: generate proper progress based on modelInfo size + while (true) { + const { done, value } = await reader?.read() || { done: true, value: undefined }; + if (done) { + break; + } + + const chunk = new TextDecoder().decode(value); + const lines = chunk.split('\n').filter(Boolean); + for (const line of lines) { + const data = JSON.parse(line); + progressReporter?.(data.status, data.completed, data.total); + } + } + } } export default Ollama; diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts index a00e869dd..2d5266318 100644 --- a/core/util/ollamaHelper.ts +++ b/core/util/ollamaHelper.ts @@ -1,6 +1,13 @@ +import crypto from "crypto"; +import { exec } from "node:child_process"; import path from "node:path"; import { IDE } from ".."; -import { exec } from "node:child_process"; + +export interface ModelInfo { + id: string; + size: number; + digest: string; +} export async function isOllamaInstalled(): Promise { return new Promise((resolve, _reject) => { @@ -39,3 +46,54 @@ export async function startLocalOllama(ide: IDE): Promise { }); } } + +export async function getRemoteModelInfo( + modelId: string, + signal?: AbortSignal, + ): Promise { + const start = Date.now(); + const [modelName, tag = "latest"] = modelId.split(":"); + const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`; + try { + const sig = signal ? signal : AbortSignal.timeout(3000); + const response = await fetch(url, { signal: sig }); + + if (!response.ok) { + throw new Error(`Failed to fetch the model page: ${response.statusText}`); + } + + // First, read the response body as an ArrayBuffer to compute the digest + const buffer = await response.arrayBuffer(); + const digest = getDigest(buffer); + + // Then, decode the ArrayBuffer into a string and parse it as JSON + const text = new TextDecoder().decode(buffer); + const manifest = JSON.parse(text) as { + config: { size: number }; + layers: { size: number }[]; + }; + const modelSize = + manifest.config.size + + manifest.layers.reduce((sum, layer) => sum + layer.size, 0); + + const data: ModelInfo = { + id: modelId, + size: modelSize, + digest, + }; + // Cache the successful result + return data; + } catch (error) { + console.error(`Error fetching or parsing model info: ${error}`); + } finally { + const elapsed = Date.now() - start; + console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`); + } + return undefined; + } + + function getDigest(buffer: ArrayBuffer): string { + const hash = crypto.createHash("sha256"); + hash.update(new Uint8Array(buffer)); + return hash.digest("hex"); + } \ No newline at end of file diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 497de3875..8c0721d53 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -21,8 +21,8 @@ import { stopStatusBarLoading, } from "./statusBar"; -import { startLocalOllama } from "core/util/ollamaHelper"; import type { IDE } from "core"; +import { startLocalOllama } from "core/util/ollamaHelper"; const Diff = require("diff"); @@ -44,15 +44,22 @@ export class ContinueCompletionProvider { private onError(e: any) { let options = ["Documentation"]; - if (e.message.includes("Ollama may not be installed")) { + let message = e.message; + let modelName = undefined; + if (message.includes("Ollama may not be installed")) { options.push("Download Ollama"); - } else if (e.message.includes("Ollama may not be running")) { + } else if (message.includes("Ollama may not be running")) { options = ["Start Ollama"]; // We want "Start" to be the only choice + } else if (message.includes("ollama run") && e.llm) { + //extract model name from error message matching the pattern "ollama run " + modelName = message.match(/`ollama run (.*)`/)?.[1]; + message = `Model "${modelName}" is not found in Ollama. You need to install it.`; + options = [`Install Model`]; } - if (e.message.includes("Please sign in with GitHub")) { + if (message.includes("Please sign in with GitHub")) { showFreeTrialLoginMessage( - e.message, + message, this.configHandler.reloadConfig.bind(this.configHandler), () => { void this.webviewProtocol.request("openOnboardingCard", undefined); @@ -60,7 +67,7 @@ export class ContinueCompletionProvider ); return; } - vscode.window.showErrorMessage(e.message, ...options).then((val) => { + vscode.window.showErrorMessage(message, ...options).then((val) => { if (val === "Documentation") { vscode.env.openExternal( vscode.Uri.parse( @@ -71,6 +78,8 @@ export class ContinueCompletionProvider vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); } else if (val === "Start Ollama") { startLocalOllama(this.ide); + } else if (val === "Install Model" && e.llm) { + vscode.commands.executeCommand("continue.installModel", modelName, e.llm); } }); } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index fa6b44c2a..697768d4c 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import * as os from "node:os"; -import { ContextMenuConfig, RangeInFileWithContents } from "core"; +import { ContextMenuConfig, ILLM, ModelInstaller, RangeInFileWithContents } from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; @@ -14,13 +14,13 @@ import readLastLines from "read-last-lines"; import * as vscode from "vscode"; import { - StatusBarStatus, getAutocompleteStatusBarDescription, getAutocompleteStatusBarTitle, getStatusBarStatus, getStatusBarStatusFromQuickPickItemLabel, quickPickStatusText, setupStatusBar, + StatusBarStatus, } from "./autocomplete/statusBar"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; @@ -32,6 +32,7 @@ import { getMetaKeyLabel } from "./util/util"; import { VsCodeIde } from "./VsCodeIde"; import { LOCAL_DEV_DATA_VERSION } from "core/data/log"; +import { isModelInstaller } from "core/llm"; import { startLocalOllama } from "core/util/ollamaHelper"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; @@ -996,6 +997,19 @@ const getCommandsMap: ( "continue.startLocalOllama": () => { startLocalOllama(ide); }, + "continue.installModel": async (modelName: string, llmProvider: ILLM | undefined) => { + try { + if (!isModelInstaller(llmProvider)) { + const msg = llmProvider ? `LLM provider '${llmProvider.providerName}' does not support installing models` : + 'Missing LLM Provider'; + throw new Error(msg); + } + await installModelWithProgress(modelName, llmProvider); + } catch (e) { + const message = e instanceof Error ? e.message : String(e); + vscode.window.showErrorMessage(`Failed to install '${modelName}': ${message}`); + } + } }; }; @@ -1037,6 +1051,32 @@ const registerCopyBufferSpy = ( context.subscriptions.push(typeDisposable); }; +async function installModelWithProgress(modelName: string, modelInstaller: ModelInstaller) { + return vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Installing model '${modelName}'`, + cancellable: true, + }, async (windowProgress, token) => { + let currentProgress: number = 0; + const progressWrapper = (details: string, worked?: number, total?: number) => { + let increment = 0; + if (worked && total) { + const progressValue = Math.round((worked / total) * 100); + increment = progressValue - currentProgress; + currentProgress = progressValue; + } + windowProgress.report({ message: details, increment }); + } + const abortController = new AbortController(); + token.onCancellationRequested(() => { + console.log(`Pulling ${modelName} model was cancelled`); + abortController.abort(); + }); + await modelInstaller.installModel(modelName, abortController.signal, progressWrapper); + }); +} + export function registerAllCommands( context: vscode.ExtensionContext, ide: VsCodeIde, diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 14854f1c3..3f2c6ea44 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -7,6 +7,7 @@ import * as vscode from "vscode"; import { IMessenger } from "../../../core/protocol/messenger"; +import { ILLM } from "core"; import { showFreeTrialLoginMessage } from "./util/messages"; export class VsCodeWebviewProtocol @@ -87,27 +88,40 @@ export class VsCodeWebviewProtocol } } catch (e: any) { let message = e.message; + let llmProvider: ILLM | undefined; //Intercept Ollama errors for special handling - if (message.includes("Ollama may not")) { - const options = []; - if (message.includes("be installed")) { - options.push("Download Ollama"); - } else if (message.includes("be running")) { - options.push("Start Ollama"); + if (message.includes("Ollama may not") || message.includes("`ollama run")) { + let modelName : string | undefined; + const options = []; + if (message.includes("be installed")) { + options.push("Download Ollama"); + } else if (message.includes("be running")) { + options.push("Start Ollama"); + } else if (message.includes("`ollama run")) { + modelName = e.message.match(/`ollama run (.*)`/)?.[1]; + if (e.llm) { + llmProvider = e.llm; } - if (options.length > 0) { - // Respond without an error, so the UI doesn't show the error component - respond({ done: true, status: "error" }); - // Show native vscode error message instead, with options to download/start Ollama - vscode.window.showErrorMessage(e.message, ...options).then(async (val) => { - if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - vscode.commands.executeCommand("continue.startLocalOllama"); - } - }); - return; + message = `Model "${modelName}" is not found in Ollama. You need to install it.`; + if (modelName) { + options.push("Install Model"); } + } + if (options.length > 0) { + // Respond without an error, so the UI doesn't show the error component + respond({ done: true, status: "error" }); + // Show native vscode error message instead, with options to download/start Ollama + vscode.window.showErrorMessage(message, ...options).then(async (val) => { + if (val === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); + } else if (val === "Start Ollama") { + vscode.commands.executeCommand("continue.startLocalOllama"); + } else if (val === "Install Model") { + vscode.commands.executeCommand("continue.installModel", modelName, llmProvider); + } + }); + return; + } } respond({ done: true, error: e.message, status: "error" }); diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 36d3853b1..635a9ae3e 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -66,11 +66,13 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ) { message = error["message"]; const parts = message?.split(" ") ?? []; - const status = parts[0] === "HTTP" ? parts[1] : parts[0]; - if (status) { - const code = Number(status); - if (!Number.isNaN(statusCode)) { - statusCode = code; + if (parts.length > 1) { + const status = parts[0] === "HTTP" ? parts[1] : parts[0]; + if (status) { + const code = Number(status); + if (!Number.isNaN(code)) { + statusCode = code; + } } } } From ec891338b1d8e5ab80faabf8f0306cc7554c1b85 Mon Sep 17 00:00:00 2001 From: aadarshkt Date: Thu, 6 Mar 2025 17:54:26 +0530 Subject: [PATCH 042/127] typo at various locations --- docs/docs/customize/deep-dives/docs.mdx | 4 ++-- docs/docs/troubleshooting.mdx | 2 +- extensions/vscode/src/diff/vertical/manager.ts | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/docs/customize/deep-dives/docs.mdx b/docs/docs/customize/deep-dives/docs.mdx index 7a5be2263..5f65bb660 100644 --- a/docs/docs/customize/deep-dives/docs.mdx +++ b/docs/docs/customize/deep-dives/docs.mdx @@ -137,7 +137,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo context: - provider: docs params: - nRetrieve: 25 # The number of docs to retreive from the embeddings query + nRetrieve: 25 # The number of docs to retrieve from the embeddings query nFinal: 5 # The number of docs chunks to return IF reranking useReranking: true # use reranking if a reranker is configured (defaults to true) ``` @@ -149,7 +149,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo { "name": "docs", "params": { - "nRetrieve": 25, // The number of docs to retreive from the embeddings query + "nRetrieve": 25, // The number of docs to retrieve from the embeddings query "nFinal": 5, // The number of docs chunks to return IF reranking "useReranking": true // use reranking if a reranker is configured (defaults to true) } diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx index 79ebefecb..3065bdc28 100644 --- a/docs/docs/troubleshooting.mdx +++ b/docs/docs/troubleshooting.mdx @@ -41,7 +41,7 @@ If you're getting a response from the LLM that doesn't seem to make sense, you c 1. Open the "Output" panel (right next to the terminal) 2. In the dropdown, select "Continue - LLM Prompts/Completions" -3. View the exact prompts that were sent to the LLM and the completions recieved +3. View the exact prompts that were sent to the LLM and the completions received ### JetBrains diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index a62406b00..d1cb496ea 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -230,7 +230,7 @@ export class VerticalDiffManager { ); if (!diffHandler) { - console.warn("Issue occured while creating new vertical diff handler"); + console.warn("Issue occurred while creating new vertical diff handler"); return; } @@ -353,7 +353,7 @@ export class VerticalDiffManager { ); if (!diffHandler) { - console.warn("Issue occured while creating new vertical diff handler"); + console.warn("Issue occurred while creating new vertical diff handler"); return undefined; } From 6bc0bfc5f1f77de9228c0ffda6cbb602bc8828e5 Mon Sep 17 00:00:00 2001 From: ferenci84 Date: Thu, 6 Mar 2025 14:05:14 +0100 Subject: [PATCH 043/127] Add citations to the log --- core/llm/index.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/core/llm/index.ts b/core/llm/index.ts index ccbad6699..8b63b5660 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -763,6 +763,7 @@ export abstract class BaseLLM implements ILLM { } let completion = ""; + let citations: null | string[] = null try { if (this.templateMessages) { @@ -790,6 +791,8 @@ export abstract class BaseLLM implements ILLM { completion = renderChatMessage(msg); } else { // Stream true + console.log("Streaming"); + const stream = this.openaiAdapter.chatCompletionStream( { ...body, @@ -802,6 +805,9 @@ export abstract class BaseLLM implements ILLM { if (result) { yield result; } + if (!citations && (chunk as any).citations && Array.isArray((chunk as any).citations)) { + citations = (chunk as any).citations; + } } } } else { @@ -824,6 +830,10 @@ export abstract class BaseLLM implements ILLM { if (logEnabled && this.writeLog) { await this.writeLog(`Completion:\n${completion}\n\n`); + + if (citations) { + await this.writeLog(`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`); + } } return { From d9c3d447b9d20b447489d4d147490e5ad60957a5 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 6 Mar 2025 15:20:25 +0100 Subject: [PATCH 044/127] Refactor Ollama error management Signed-off-by: Fred Bricon --- .../src/autocomplete/completionProvider.ts | 26 ++---- extensions/vscode/src/commands.ts | 80 ++++++++++++------- .../vscode/src/diff/vertical/manager.ts | 9 ++- extensions/vscode/src/util/errorHandling.ts | 49 ++++++++++++ extensions/vscode/src/webviewProtocol.ts | 44 ++-------- 5 files changed, 119 insertions(+), 89 deletions(-) create mode 100644 extensions/vscode/src/util/errorHandling.ts diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 8c0721d53..f74de8409 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -22,7 +22,7 @@ import { } from "./statusBar"; import type { IDE } from "core"; -import { startLocalOllama } from "core/util/ollamaHelper"; +import { handleLLMError } from "../util/errorHandling"; const Diff = require("diff"); @@ -43,20 +43,10 @@ export class ContinueCompletionProvider implements vscode.InlineCompletionItemProvider { private onError(e: any) { - let options = ["Documentation"]; - let message = e.message; - let modelName = undefined; - if (message.includes("Ollama may not be installed")) { - options.push("Download Ollama"); - } else if (message.includes("Ollama may not be running")) { - options = ["Start Ollama"]; // We want "Start" to be the only choice - } else if (message.includes("ollama run") && e.llm) { - //extract model name from error message matching the pattern "ollama run " - modelName = message.match(/`ollama run (.*)`/)?.[1]; - message = `Model "${modelName}" is not found in Ollama. You need to install it.`; - options = [`Install Model`]; + if (handleLLMError(e)) { + return; } - + let message = e.message; if (message.includes("Please sign in with GitHub")) { showFreeTrialLoginMessage( message, @@ -67,19 +57,13 @@ export class ContinueCompletionProvider ); return; } - vscode.window.showErrorMessage(message, ...options).then((val) => { + vscode.window.showErrorMessage(message, "Documentation").then((val) => { if (val === "Documentation") { vscode.env.openExternal( vscode.Uri.parse( "https://docs.continue.dev/features/tab-autocomplete", ), ); - } else if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - startLocalOllama(this.ide); - } else if (val === "Install Model" && e.llm) { - vscode.commands.executeCommand("continue.installModel", modelName, e.llm); } }); } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 697768d4c..e9b973a2a 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,7 +1,12 @@ /* eslint-disable @typescript-eslint/naming-convention */ import * as os from "node:os"; -import { ContextMenuConfig, ILLM, ModelInstaller, RangeInFileWithContents } from "core"; +import { + ContextMenuConfig, + ILLM, + ModelInstaller, + RangeInFileWithContents, +} from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; @@ -997,19 +1002,25 @@ const getCommandsMap: ( "continue.startLocalOllama": () => { startLocalOllama(ide); }, - "continue.installModel": async (modelName: string, llmProvider: ILLM | undefined) => { + "continue.installModel": async ( + modelName: string, + llmProvider: ILLM | undefined, + ) => { try { if (!isModelInstaller(llmProvider)) { - const msg = llmProvider ? `LLM provider '${llmProvider.providerName}' does not support installing models` : - 'Missing LLM Provider'; + const msg = llmProvider + ? `LLM provider '${llmProvider.providerName}' does not support installing models` + : "Missing LLM Provider"; throw new Error(msg); } await installModelWithProgress(modelName, llmProvider); } catch (e) { const message = e instanceof Error ? e.message : String(e); - vscode.window.showErrorMessage(`Failed to install '${modelName}': ${message}`); + vscode.window.showErrorMessage( + `Failed to install '${modelName}': ${message}`, + ); } - } + }, }; }; @@ -1051,30 +1062,43 @@ const registerCopyBufferSpy = ( context.subscriptions.push(typeDisposable); }; -async function installModelWithProgress(modelName: string, modelInstaller: ModelInstaller) { - return vscode.window.withProgress( - { - location: vscode.ProgressLocation.Notification, - title: `Installing model '${modelName}'`, - cancellable: true, - }, async (windowProgress, token) => { - let currentProgress: number = 0; - const progressWrapper = (details: string, worked?: number, total?: number) => { - let increment = 0; - if (worked && total) { - const progressValue = Math.round((worked / total) * 100); - increment = progressValue - currentProgress; - currentProgress = progressValue; - } - windowProgress.report({ message: details, increment }); +async function installModelWithProgress( + modelName: string, + modelInstaller: ModelInstaller, +) { + return vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Installing model '${modelName}'`, + cancellable: true, + }, + async (windowProgress, token) => { + let currentProgress: number = 0; + const progressWrapper = ( + details: string, + worked?: number, + total?: number, + ) => { + let increment = 0; + if (worked && total) { + const progressValue = Math.round((worked / total) * 100); + increment = progressValue - currentProgress; + currentProgress = progressValue; } - const abortController = new AbortController(); - token.onCancellationRequested(() => { - console.log(`Pulling ${modelName} model was cancelled`); - abortController.abort(); - }); - await modelInstaller.installModel(modelName, abortController.signal, progressWrapper); + windowProgress.report({ message: details, increment }); + }; + const abortController = new AbortController(); + token.onCancellationRequested(() => { + console.log(`Pulling ${modelName} model was cancelled`); + abortController.abort(); }); + await modelInstaller.installModel( + modelName, + abortController.signal, + progressWrapper, + ); + }, + ); } export function registerAllCommands( diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index a62406b00..b51462a3c 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -9,6 +9,7 @@ import * as vscode from "vscode"; import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; +import { handleLLMError } from "../../util/errorHandling"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -255,7 +256,9 @@ export class VerticalDiffManager { this.enableDocumentChangeListener(); } catch (e) { this.disableDocumentChangeListener(); - vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + if (!handleLLMError(e)) { + vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + } } finally { vscode.commands.executeCommand( "setContext", @@ -446,7 +449,9 @@ export class VerticalDiffManager { return `${prefix}${streamedLines.join("\n")}${suffix}`; } catch (e) { this.disableDocumentChangeListener(); - vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + if (!handleLLMError(e)) { + vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + } return undefined; } finally { vscode.commands.executeCommand( diff --git a/extensions/vscode/src/util/errorHandling.ts b/extensions/vscode/src/util/errorHandling.ts new file mode 100644 index 000000000..de68f0ce2 --- /dev/null +++ b/extensions/vscode/src/util/errorHandling.ts @@ -0,0 +1,49 @@ +import * as vscode from "vscode"; + +function supportSpecialHandling(error: any): boolean { + let message: string | undefined = error.message; + return message !== undefined && message.toLowerCase().includes("ollama"); +} + +/** + * @param error Handles common LLM errors. Currently only handles Ollama-related errors. + * @returns true if error is handled, false otherwise + */ +export function handleLLMError(error: any): boolean { + if (!supportSpecialHandling(error)) { + return false; + } + let message: string = error.message; + let options: string[] | undefined; + let modelName = undefined; + if (message.includes("Ollama may not be installed")) { + options = ["Download Ollama"]; + } else if (message.includes("Ollama may not be running")) { + options = ["Start Ollama"]; // We want "Start" to be the only choice + } else if (message.includes("ollama run") && error.llm) { + //extract model name from error message matching the pattern "ollama run " + modelName = message.match(/`ollama run (.*)`/)?.[1]; + message = `Model "${modelName}" is not found in Ollama. You need to install it.`; + options = [`Install Model`]; + } + if (options === undefined) { + console.log("Found an unhandled Ollama error: ", message); + return false; + } + + vscode.window.showErrorMessage(message, ...options).then((val) => { + if (val === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); + } else if (val === "Start Ollama") { + vscode.commands.executeCommand("continue.startLocalOllama"); + } else if (val === "Install Model" && error.llm) { + //Eventually, we might be able to support installing models for other LLM providers than Ollama + vscode.commands.executeCommand( + "continue.installModel", + modelName, + error.llm, + ); + } + }); + return true; +} diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 3f2c6ea44..0d58532ae 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -7,7 +7,7 @@ import * as vscode from "vscode"; import { IMessenger } from "../../../core/protocol/messenger"; -import { ILLM } from "core"; +import { handleLLMError } from "./util/errorHandling"; import { showFreeTrialLoginMessage } from "./util/messages"; export class VsCodeWebviewProtocol @@ -87,44 +87,12 @@ export class VsCodeWebviewProtocol respond({ done: true, content: response, status: "success" }); } } catch (e: any) { - let message = e.message; - let llmProvider: ILLM | undefined; - //Intercept Ollama errors for special handling - if (message.includes("Ollama may not") || message.includes("`ollama run")) { - let modelName : string | undefined; - const options = []; - if (message.includes("be installed")) { - options.push("Download Ollama"); - } else if (message.includes("be running")) { - options.push("Start Ollama"); - } else if (message.includes("`ollama run")) { - modelName = e.message.match(/`ollama run (.*)`/)?.[1]; - if (e.llm) { - llmProvider = e.llm; - } - message = `Model "${modelName}" is not found in Ollama. You need to install it.`; - if (modelName) { - options.push("Install Model"); - } - } - if (options.length > 0) { - // Respond without an error, so the UI doesn't show the error component - respond({ done: true, status: "error" }); - // Show native vscode error message instead, with options to download/start Ollama - vscode.window.showErrorMessage(message, ...options).then(async (val) => { - if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - vscode.commands.executeCommand("continue.startLocalOllama"); - } else if (val === "Install Model") { - vscode.commands.executeCommand("continue.installModel", modelName, llmProvider); - } - }); - return; - } + if (handleLLMError(e)) { + // Respond without an error, so the UI doesn't show the error component + respond({ done: true, status: "error" }); } - - respond({ done: true, error: e.message, status: "error" }); + let message = e.message; + respond({ done: true, error: message, status: "error" }); const stringified = JSON.stringify({ msg }, null, 2); console.error( From 954d91cfe8d3d9a684213d6aba9b513dd5ddc2a9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 6 Mar 2025 11:59:46 -0800 Subject: [PATCH 045/127] better autodetect names --- core/config/load.ts | 3 ++- core/config/yaml/models.ts | 3 ++- core/util/text.ts | 6 ++++++ gui/src/components/modelSelection/ModelSelectionListbox.tsx | 3 +-- 4 files changed, 11 insertions(+), 4 deletions(-) create mode 100644 core/util/text.ts diff --git a/core/config/load.ts b/core/config/load.ts index 873577d8c..8005ff555 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -71,6 +71,7 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; +import { capitalizeFirstLetter } from "../util/text"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -272,7 +273,7 @@ async function intermediateToFinalConfig( { ...desc, model: modelName, - title: `${llm.title} - ${modelName}`, + title: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, }, ide.readFile.bind(ide), uniqueId, diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index c6916b010..240a7044e 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -3,6 +3,7 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { IDE, IdeSettings, LLMOptions } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; +import { capitalizeFirstLetter } from "../../util/text"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; const AUTODETECT = "AUTODETECT"; @@ -127,7 +128,7 @@ async function autodetectModels( { ...model, model: modelName, - name: `${llm.title} - ${modelName}`, + name: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, }, uniqueId, ideSettings, diff --git a/core/util/text.ts b/core/util/text.ts new file mode 100644 index 000000000..e4870dfa0 --- /dev/null +++ b/core/util/text.ts @@ -0,0 +1,6 @@ +export const capitalizeFirstLetter = (val: string) => { + if (val.length === 0) { + return ""; + } + return val[0].toUpperCase() + val.slice(1); +}; diff --git a/gui/src/components/modelSelection/ModelSelectionListbox.tsx b/gui/src/components/modelSelection/ModelSelectionListbox.tsx index d48ffceed..596cddb9b 100644 --- a/gui/src/components/modelSelection/ModelSelectionListbox.tsx +++ b/gui/src/components/modelSelection/ModelSelectionListbox.tsx @@ -1,11 +1,10 @@ -import { Transition } from "@headlessui/react"; +import { Listbox, Transition } from "@headlessui/react"; import { CheckIcon, ChevronUpDownIcon, CubeIcon, } from "@heroicons/react/24/outline"; import { Fragment } from "react"; -import { Listbox } from "@headlessui/react"; import styled from "styled-components"; import { defaultBorderRadius, From 55c8871ecb2dae3fe2640dbfda09b298dfac5c0b Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Fri, 7 Mar 2025 06:18:52 -0500 Subject: [PATCH 046/127] Set VSCODE_VERSION when running 'extest get-chromedriver' If we only set the VSCODE_VERSION when running 'extest get-vscode', then we might get a version of chromedriver that is incompatible with the version of vscode we download. --- 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 366da7ff5..ec2e14779 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -594,7 +594,7 @@ "e2e:compile": "tsc -p ./tsconfig.e2e.json", "e2e:build": "npm --prefix ../../gui run build && npm run package", "e2e:create-storage": "mkdir -p ./e2e/storage", - "e2e:get-chromedriver": "extest get-chromedriver --storage ./e2e/storage", + "e2e:get-chromedriver": "CODE_VERSION=\"1.95.0\" extest get-chromedriver --storage ./e2e/storage", "e2e:get-vscode": "CODE_VERSION=\"1.95.0\" extest get-vscode --storage ./e2e/storage", "e2e:sign-vscode": "codesign --entitlements entitlements.plist --deep --force -s - './e2e/storage/Visual Studio Code.app'", "e2e:copy-vsix": "chmod +x ./e2e/get-latest-vsix.sh && bash ./e2e/get-latest-vsix.sh", From e1119119108c1e2c09bf8e8a839ec95de654a7e2 Mon Sep 17 00:00:00 2001 From: Bastin Florian <33825469+BastinFlorian@users.noreply.github.com> Date: Fri, 7 Mar 2025 15:55:36 +0100 Subject: [PATCH 047/127] FIX(AZURE): Fix azure codestral documentation when deploying codestral in Azure AI Foundry Based on this issue: https://github.com/continuedev/continue/issues/3735 Update the documentation to use Codestral deployed in Azure with Azure AI Foundry --- docs/docs/customize/model-providers/top-level/azure.mdx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/docs/customize/model-providers/top-level/azure.mdx b/docs/docs/customize/model-providers/top-level/azure.mdx index cbb955bca..6ccb0508d 100644 --- a/docs/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/docs/customize/model-providers/top-level/azure.mdx @@ -51,7 +51,7 @@ We recommend configuring **GPT-4o** as your chat model. ## Autocomplete model -We recommend configuring **Codestral** as your autocomplete model. +We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral: @@ -60,6 +60,8 @@ We recommend configuring **Codestral** as your autocomplete model. - name: Codestral provider: mistral model: codestral-latest + apiBase: https://..models.ai.azure.com/v1, + apiKey: roles: - autocomplete ``` @@ -70,7 +72,9 @@ We recommend configuring **Codestral** as your autocomplete model. "tabAutocompleteModel": { "title": "Codestral", "provider": "mistral", - "model": "codestral-latest" + "model": "codestral-latest", + "apiBase": "https://..models.ai.azure.com/v1", + "apiKey": "" } } ``` From f7d3d21abbaa9ce3020ddf24e1b3a3853d0d20ec Mon Sep 17 00:00:00 2001 From: Bastin Florian <33825469+BastinFlorian@users.noreply.github.com> Date: Fri, 7 Mar 2025 15:58:22 +0100 Subject: [PATCH 048/127] FIX(AZURE): minor change --- docs/docs/customize/model-providers/top-level/azure.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/model-providers/top-level/azure.mdx b/docs/docs/customize/model-providers/top-level/azure.mdx index 6ccb0508d..2c201d938 100644 --- a/docs/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/docs/customize/model-providers/top-level/azure.mdx @@ -60,7 +60,7 @@ We recommend configuring **Codestral** as your autocomplete model. If you use Az - name: Codestral provider: mistral model: codestral-latest - apiBase: https://..models.ai.azure.com/v1, + apiBase: https://..models.ai.azure.com/v1 apiKey: roles: - autocomplete From 54c172b69a123aec1ef1f5ffbabda00e7510761e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 7 Mar 2025 16:16:57 +0000 Subject: [PATCH 049/127] Bump axios from 1.7.9 to 1.8.2 in /core Bumps [axios](https://github.com/axios/axios) from 1.7.9 to 1.8.2. - [Release notes](https://github.com/axios/axios/releases) - [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) - [Commits](https://github.com/axios/axios/compare/v1.7.9...v1.8.2) --- updated-dependencies: - dependency-name: axios dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- core/package-lock.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/core/package-lock.json b/core/package-lock.json index abe4271f8..a15d33faf 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -6163,9 +6163,10 @@ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==" }, "node_modules/axios": { - "version": "1.7.9", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", - "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz", + "integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==", + "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", From 66e4db7f7c6f6be7a2ae59f50db2301a6dc38bde Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 09:52:31 -0800 Subject: [PATCH 050/127] should ignore p1 --- core/core.ts | 4 ++ core/indexing/shouldIgnore.test.ts | 53 ++++++++++++++++++++ core/indexing/shouldIgnore.ts | 80 ++++++++++++++++++++++++++++++ core/test/testDir.ts | 4 +- 4 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 core/indexing/shouldIgnore.test.ts create mode 100644 core/indexing/shouldIgnore.ts diff --git a/core/core.ts b/core/core.ts index 180ce8642..dd05484d3 100644 --- a/core/core.ts +++ b/core/core.ts @@ -829,6 +829,10 @@ export class Core { // Codebase indexing on("index/forceReIndex", async ({ data }) => { + const { config } = await this.configHandler.loadConfig(); + if (config?.disableIndexing) { + return; // TODO silent in case of commands? + } if (data?.shouldClearIndexes) { const codebaseIndexer = await this.codebaseIndexerPromise; await codebaseIndexer.clearIndexes(); diff --git a/core/indexing/shouldIgnore.test.ts b/core/indexing/shouldIgnore.test.ts new file mode 100644 index 000000000..31981c134 --- /dev/null +++ b/core/indexing/shouldIgnore.test.ts @@ -0,0 +1,53 @@ +// Generated by continue + +// Import modules +import { describe, expect, test } from "@jest/globals"; +import { testIde } from "../test/fixtures"; +import { + TEST_DIR, + addToTestDir, + setUpTestDir, + tearDownTestDir, +} from "../test/testDir"; +import { shouldIgnore } from "./shouldIgnore"; + +// Test for the shouldIgnore function +describe("shouldIgnore", () => { + beforeEach(() => { + setUpTestDir(); + }); + + afterEach(() => { + tearDownTestDir(); + }); + + test("should return true if a file is ignored by .gitignore", async () => { + addToTestDir([ + ["/ignored-file.txt", "content"], + ["/kept-file.txt", "content"], + ["/.gitignore", "ignored-file.txt\nignored-folder/"], + "/ignored-folder/", + ["/ignored-folder/file.txt", "content"], + ]); + const result1 = await shouldIgnore( + TEST_DIR + "/ignored-file.txt", + TEST_DIR, + testIde, + ); + expect(result1).toBe(true); + + const result2 = await shouldIgnore( + TEST_DIR + "/ignored-folder", + TEST_DIR, + testIde, + ); + expect(result2).toBe(true); + + const result3 = await shouldIgnore( + TEST_DIR + "/kept-file.txt", + TEST_DIR, + testIde, + ); + expect(result3).toBe(false); + }); +}); diff --git a/core/indexing/shouldIgnore.ts b/core/indexing/shouldIgnore.ts new file mode 100644 index 000000000..5af63394b --- /dev/null +++ b/core/indexing/shouldIgnore.ts @@ -0,0 +1,80 @@ +import ignore from "ignore"; +import { FileType, IDE } from "../index"; +import { getUriPathBasename } from "../util/uri"; +import { getGlobalContinueIgArray, gitIgArrayFromFile } from "./ignore"; + +interface IgnoreContext { + ignore: ReturnType; + dirname: string; +} + +export async function shouldIgnore( + fileUri: string, + rootDirUri: string, + ide: IDE, + ignoreFiles: string[] = [".gitignore", ".continueignore"], +): Promise { + let currentDir = fileUri; + + while (currentDir !== rootDirUri && currentDir.startsWith(rootDirUri)) { + const dirEntries = await ide.listDir(currentDir); + const dirs = dirEntries + .filter(([_, uriType]) => uriType === FileType.File) + .map(([uri, _]) => uri); + + const ignoreContexts = await getIgnoreContextsInDir( + currentDir, + dirs, + ignoreFiles, + ide, + ); + + const relativePath = fileUri.substring(currentDir.length + 1); + + for (const context of ignoreContexts) { + if (context.ignore.ignores(relativePath)) { + return true; + } + } + + currentDir = getParentDir(currentDir); + } + + return false; +} + +async function getIgnoreContextsInDir( + dirUri: string, + entries: string[], + ignoreFiles: string[], + ide: IDE, +): Promise { + const ignoreEntries = entries.filter((entryUri) => + ignoreFiles.includes(getUriPathBasename(entryUri)), + ); + const patterns = await Promise.all( + ignoreEntries.map(async (entryUri) => { + const fileContent = await ide.readFile(entryUri); + return gitIgArrayFromFile(fileContent); + }), + ); + + const globalPatterns = getGlobalContinueIgArray(); + + return [ + ...patterns.map((patterns) => ({ + ignore: ignore().add(patterns), + dirname: dirUri, + })), + { + ignore: ignore().add(globalPatterns), + dirname: "/", + }, + ]; +} + +function getParentDir(uri: string): string { + const splitUri = uri.split("/"); + splitUri.pop(); + return splitUri.join("/"); +} diff --git a/core/test/testDir.ts b/core/test/testDir.ts index 9b0473b46..0e34f509b 100644 --- a/core/test/testDir.ts +++ b/core/test/testDir.ts @@ -1,7 +1,7 @@ import fs from "fs"; import os from "os"; import path from "path"; -import { localPathToUri, localPathOrUriToPath } from "../util/pathToUri"; +import { localPathOrUriToPath, localPathToUri } from "../util/pathToUri"; // Want this outside of the git repository so we can change branches in tests export const TEST_DIR_PATH = path.join(os.tmpdir(), "testWorkspaceDir"); @@ -26,7 +26,7 @@ export function tearDownTestDir() { "index/index.ts" creates an empty index/index.ts ["index/index.ts", "hello"] creates index/index.ts with contents "hello" */ -export function addToTestDir(pathsOrUris: (string | string[])[]) { +export function addToTestDir(pathsOrUris: (string | [string, string])[]) { // Allow tests to use URIs or local paths const paths = pathsOrUris.map((val) => { if (Array.isArray(val)) { From a2034e801db2469870f0acbe69c3b2512d00aec9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 13:01:37 -0800 Subject: [PATCH 051/127] shouldignore working --- core/core.ts | 34 ++++++-- core/indexing/shouldIgnore.test.ts | 109 ++++++++++++++++++++---- core/indexing/shouldIgnore.ts | 130 +++++++++++++++-------------- 3 files changed, 184 insertions(+), 89 deletions(-) diff --git a/core/core.ts b/core/core.ts index dd05484d3..874810967 100644 --- a/core/core.ts +++ b/core/core.ts @@ -53,6 +53,7 @@ import { type IndexingProgressUpdate, } from "."; +import { shouldIgnore } from "./indexing/shouldIgnore"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -890,30 +891,45 @@ export class Core { uri.endsWith(".gitignore") ) { // Reindex the workspaces - this.invoke("index/forceReIndex", undefined); + this.invoke("index/forceReIndex", { + shouldClearIndexes: true, + }); } else { // Reindex the file - await this.refreshCodebaseIndexFiles([uri]); + const ignore = await shouldIgnore(uri, this.ide); + if (!ignore) { + await this.refreshCodebaseIndexFiles([uri]); + } } } } }); - on("files/created", async ({ data }) => { - if (data?.uris?.length) { + const refreshIfNotIgnored = async (uris: string[]) => { + const toRefresh: string[] = []; + for (const uri of uris) { + const ignore = await shouldIgnore(uri, ide); + if (!ignore) { + toRefresh.push(uri); + } + } + if (toRefresh.length > 0) { this.messenger.send("refreshSubmenuItems", { providers: ["file"], }); - await this.refreshCodebaseIndexFiles(data.uris); + await this.refreshCodebaseIndexFiles(toRefresh); + } + }; + + on("files/created", async ({ data }) => { + if (data?.uris?.length) { + void refreshIfNotIgnored(data.uris); } }); on("files/deleted", async ({ data }) => { if (data?.uris?.length) { - this.messenger.send("refreshSubmenuItems", { - providers: ["file"], - }); - await this.refreshCodebaseIndexFiles(data.uris); + void refreshIfNotIgnored(data.uris); } }); on("files/opened", async ({ data }) => { diff --git a/core/indexing/shouldIgnore.test.ts b/core/indexing/shouldIgnore.test.ts index 31981c134..1d1ac857c 100644 --- a/core/indexing/shouldIgnore.test.ts +++ b/core/indexing/shouldIgnore.test.ts @@ -1,7 +1,5 @@ // Generated by continue -// Import modules -import { describe, expect, test } from "@jest/globals"; import { testIde } from "../test/fixtures"; import { TEST_DIR, @@ -9,6 +7,7 @@ import { setUpTestDir, tearDownTestDir, } from "../test/testDir"; + import { shouldIgnore } from "./shouldIgnore"; // Test for the shouldIgnore function @@ -23,31 +22,105 @@ describe("shouldIgnore", () => { test("should return true if a file is ignored by .gitignore", async () => { addToTestDir([ - ["/ignored-file.txt", "content"], - ["/kept-file.txt", "content"], - ["/.gitignore", "ignored-file.txt\nignored-folder/"], - "/ignored-folder/", - ["/ignored-folder/file.txt", "content"], + ["ignored-file.txt", "content"], + [".gitignore", "ignored-file.txt"], ]); - const result1 = await shouldIgnore( - TEST_DIR + "/ignored-file.txt", + const result = await shouldIgnore(TEST_DIR + "/ignored-file.txt", testIde, [ TEST_DIR, + ]); + expect(result).toBe(true); + }); + test("should return true if a folder is ignored by .continueignore", async () => { + addToTestDir([ + "ignored-folder/", + ["ignored-folder/file.txt", "content"], + [".continueignore", "ignored-folder/"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/ignored-folder/file.txt", testIde, + [TEST_DIR], ); - expect(result1).toBe(true); + expect(result).toBe(true); + }); + test("should return false if a file is not ignored", async () => { + addToTestDir([["kept-file.txt", "contents"]]); + const result = await shouldIgnore(TEST_DIR + "/kept-file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(false); + }); + test("should return true if a file is ignored by .gitignore with spaces in file name", async () => { + addToTestDir([ + ["ignored file.txt", "content"], + [".gitignore", "ignored file.txt"], + ]); + const result = await shouldIgnore(TEST_DIR + "/ignored file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); - const result2 = await shouldIgnore( - TEST_DIR + "/ignored-folder", - TEST_DIR, + test("should return true if a .continueignore override ignores file", async () => { + addToTestDir([ + ["override-file.txt", "content"], + [".gitignore", "override-file.txt"], + [".continueignore", "!override-file.txt"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/override-file.txt", testIde, + [TEST_DIR], ); - expect(result2).toBe(true); + expect(result).toBe(false); + }); - const result3 = await shouldIgnore( - TEST_DIR + "/kept-file.txt", - TEST_DIR, + test("should return true for deeply nested file ignored by ignore files at multiple levels", async () => { + addToTestDir([ + "level1/", + "level1/level2/", + "level1/level2/level3/", + ["level1/level2/level3/ignored-file.txt", "content"], + ["level1/.gitignore", "level2/"], + ["level1/level2/.continueignore", "level3/"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/level1/level2/level3/ignored-file.txt", testIde, + [TEST_DIR], ); - expect(result3).toBe(false); + expect(result).toBe(true); + }); + + test("should return false if a file with spaces is not ignored", async () => { + addToTestDir([["kept file.txt", "contents"]]); + const result = await shouldIgnore(TEST_DIR + "/kept file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(false); + }); + + test("should handle multiple levels of directories with some files ignored", async () => { + addToTestDir([ + "nested/", + "nested/dir1/", + "nested/dir2/", + ["nested/dir1/.gitignore", "ignored.txt"], + ["nested/dir1/ignored.txt", "content"], + ["nested/dir2/kept.txt", "content"], + ]); + const ignoredResult = await shouldIgnore( + TEST_DIR + "/nested/dir1/ignored.txt", + testIde, + [TEST_DIR], + ); + expect(ignoredResult).toBe(true); + + const keptResult = await shouldIgnore( + TEST_DIR + "/nested/dir2/kept.txt", + testIde, + [TEST_DIR], + ); + expect(keptResult).toBe(false); }); }); diff --git a/core/indexing/shouldIgnore.ts b/core/indexing/shouldIgnore.ts index 5af63394b..9170bae3e 100644 --- a/core/indexing/shouldIgnore.ts +++ b/core/indexing/shouldIgnore.ts @@ -1,80 +1,86 @@ import ignore from "ignore"; -import { FileType, IDE } from "../index"; -import { getUriPathBasename } from "../util/uri"; -import { getGlobalContinueIgArray, gitIgArrayFromFile } from "./ignore"; +import type { FileType, IDE } from "../"; +import { findUriInDirs } from "../util/uri"; +import { + DEFAULT_IGNORE, + getGlobalContinueIgArray, + gitIgArrayFromFile, +} from "./ignore"; -interface IgnoreContext { - ignore: ReturnType; - dirname: string; -} +/* + Process: + 1. Check global/default ignores + 2. Walk UP tree from file, checking ignores at each level + TODO there might be issues with symlinks here +*/ export async function shouldIgnore( fileUri: string, - rootDirUri: string, ide: IDE, - ignoreFiles: string[] = [".gitignore", ".continueignore"], + rootDirCandidates?: string[], ): Promise { - let currentDir = fileUri; + const rootDirUris = rootDirCandidates ?? (await ide.getWorkspaceDirs()); + const { + foundInDir: rootDir, + uri, + relativePathOrBasename, + } = findUriInDirs(fileUri, rootDirUris); + if (!rootDir) { + throw new Error("Should ignore: file uri not found in root dirs"); + } - while (currentDir !== rootDirUri && currentDir.startsWith(rootDirUri)) { + // Global/default ignores + const globalPatterns = getGlobalContinueIgArray(); + const rootIgnoreContext = ignore().add(globalPatterns).add(DEFAULT_IGNORE); + if (rootIgnoreContext.ignores(relativePathOrBasename)) { + return true; + } + + let currentDir = uri; + while (currentDir !== rootDir) { + // Go to parent dir of file + const splitUri = currentDir.split("/"); + splitUri.pop(); + currentDir = splitUri.join("/"); + + // Get all files in the dir const dirEntries = await ide.listDir(currentDir); - const dirs = dirEntries - .filter(([_, uriType]) => uriType === FileType.File) - .map(([uri, _]) => uri); + const dirFiles = dirEntries + .filter(([_, entryType]) => entryType === (1 as FileType.File)) + .map(([name, _]) => name); - const ignoreContexts = await getIgnoreContextsInDir( - currentDir, - dirs, - ignoreFiles, - ide, + // Find ignore files and get ignore arrays from their contexts + const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore"); + const continueIgnoreFile = dirFiles.find( + (name) => name === ".continueignore", ); - const relativePath = fileUri.substring(currentDir.length + 1); - - for (const context of ignoreContexts) { - if (context.ignore.ignores(relativePath)) { - return true; + const getGitIgnorePatterns = async () => { + if (gitIgnoreFile) { + const contents = await ide.readFile(`${currentDir}/.gitignore`); + return gitIgArrayFromFile(contents); } - } + return []; + }; + const getContinueIgnorePatterns = async () => { + if (continueIgnoreFile) { + const contents = await ide.readFile(`${currentDir}/.continueignore`); + return gitIgArrayFromFile(contents); + } + return []; + }; - currentDir = getParentDir(currentDir); + const ignoreArrays = await Promise.all([ + getGitIgnorePatterns(), + getContinueIgnorePatterns(), + ]); + const ignoreContext = ignore().add(ignoreArrays[0]).add(ignoreArrays[1]); + + const relativePath = uri.substring(currentDir.length + 1); + if (ignoreContext.ignores(relativePath)) { + return true; + } } return false; } - -async function getIgnoreContextsInDir( - dirUri: string, - entries: string[], - ignoreFiles: string[], - ide: IDE, -): Promise { - const ignoreEntries = entries.filter((entryUri) => - ignoreFiles.includes(getUriPathBasename(entryUri)), - ); - const patterns = await Promise.all( - ignoreEntries.map(async (entryUri) => { - const fileContent = await ide.readFile(entryUri); - return gitIgArrayFromFile(fileContent); - }), - ); - - const globalPatterns = getGlobalContinueIgArray(); - - return [ - ...patterns.map((patterns) => ({ - ignore: ignore().add(patterns), - dirname: dirUri, - })), - { - ignore: ignore().add(globalPatterns), - dirname: "/", - }, - ]; -} - -function getParentDir(uri: string): string { - const splitUri = uri.split("/"); - splitUri.pop(); - return splitUri.join("/"); -} From 98b56b04732ba459f05a0e1e968e453218ca7208 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 7 Mar 2025 13:46:34 -0800 Subject: [PATCH 052/127] bump --- 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 b6c71a29c..1de735944 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.4", + "version": "1.1.5", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From daa418109b320f4f40f3164992e5c45f7f144c09 Mon Sep 17 00:00:00 2001 From: Alexey Elin Date: Fri, 7 Mar 2025 20:35:40 +0300 Subject: [PATCH 053/127] (fix): GitLabMergeRequest context provider doesn't work when the git origin is https --- .../GitLabMergeRequestContextProvider.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/core/context/providers/GitLabMergeRequestContextProvider.ts b/core/context/providers/GitLabMergeRequestContextProvider.ts index 3e8f77a67..b4d3fe2ed 100644 --- a/core/context/providers/GitLabMergeRequestContextProvider.ts +++ b/core/context/providers/GitLabMergeRequestContextProvider.ts @@ -94,7 +94,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { }); } - private async getRemoteBranchName( + private async getRemoteBranchInfo( extras: ContextProviderExtras, ): Promise { const subprocess = await getSubprocess(extras); @@ -121,9 +121,16 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`); - const urlMatches = /:(?.*).git/.exec(remoteUrl); + let urlMatches: RegExpExecArray | null; + if (/https?.*/.test(remoteUrl)) { + const pathname = new URL(remoteUrl).pathname; + urlMatches = /\/(?.*?)(?:(?=\.git)|$)/.exec(pathname) + } else { + // ssh + urlMatches = /:(?.*).git/.exec(remoteUrl) + } - const project = urlMatches?.groups?.project ?? null; + const project = urlMatches?.groups?.projectPath ?? null; return { branch: remoteBranch, @@ -135,7 +142,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const { branch, project } = await this.getRemoteBranchName(extras); + const { branch, project } = await this.getRemoteBranchInfo(extras); const api = await this.getApi(); From fda4cc8096f94548194ac0899ef327ff57f2df45 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 7 Mar 2025 15:33:48 -0800 Subject: [PATCH 054/127] skip ssh on dependabot PRs --- .github/workflows/pr_checks.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 258ec33e2..02b458d21 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -275,7 +275,7 @@ jobs: cd core npm test env: - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork }} + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true && github.actor == 'dependabot[bot]' }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} @@ -436,7 +436,7 @@ jobs: chmod 600 ~/.ssh/id_rsa ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config - if: ${{ github.event.pull_request.head.repo.fork == false }} + if: ${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }} - name: Set up Xvfb run: | @@ -446,7 +446,7 @@ jobs: - name: Run e2e tests run: | cd extensions/vscode - IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} + IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} env: DISPLAY: :99 From 8765df11fcac1092487ffd1fc842c29dc1e4d0fc Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 15:52:19 -0800 Subject: [PATCH 055/127] speed tests --- core/commands/slash/onboard.ts | 8 +- core/core.ts | 2 +- core/indexing/ignore.ts | 4 + core/indexing/shouldIgnore.test.ts | 55 +++++- core/indexing/shouldIgnore.ts | 79 ++++---- core/indexing/walkDir.test.ts | 43 ++++- core/indexing/walkDir.ts | 267 +++++++++++++------------- core/promptFiles/v2/getPromptFiles.ts | 2 +- 8 files changed, 256 insertions(+), 204 deletions(-) diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index d6fedcafb..b53c8d3a9 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -2,8 +2,7 @@ import ignore from "ignore"; import type { FileType, IDE, SlashCommand } from "../.."; import { - defaultIgnoreDir, - defaultIgnoreFile, + DEFAULT_IGNORE, getGlobalContinueIgArray, gitIgArrayFromFile, } from "../../indexing/ignore"; @@ -58,10 +57,7 @@ const OnboardSlashCommand: SlashCommand = { }; async function getEntriesFilteredByIgnore(dir: string, ide: IDE) { - const ig = ignore() - .add(defaultIgnoreDir) - .add(defaultIgnoreFile) - .add(getGlobalContinueIgArray()); + const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray()); const entries = await ide.listDir(dir); const ignoreUri = joinPathsToUri(dir, ".gitignore"); diff --git a/core/core.ts b/core/core.ts index 874810967..33ff03776 100644 --- a/core/core.ts +++ b/core/core.ts @@ -26,7 +26,6 @@ import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import { getAllSuggestedDocs } from "./indexing/docs/suggestions"; -import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import { callTool } from "./tools/callTool"; @@ -53,6 +52,7 @@ import { type IndexingProgressUpdate, } from "."; +import { defaultIgnoreFile } from "./indexing/ignore"; import { shouldIgnore } from "./indexing/shouldIgnore"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 6075bdb26..7f5e8a039 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -114,6 +114,10 @@ export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS); export const DEFAULT_IGNORE = DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n"); +export const defaultIgnoreFileAndDir = ignore() + .add(defaultIgnoreFile) + .add(defaultIgnoreDir); + export function gitIgArrayFromFile(file: string) { return file .split(/\r?\n/) // Split on new line diff --git a/core/indexing/shouldIgnore.test.ts b/core/indexing/shouldIgnore.test.ts index 1d1ac857c..c1935e7d9 100644 --- a/core/indexing/shouldIgnore.test.ts +++ b/core/indexing/shouldIgnore.test.ts @@ -32,7 +32,6 @@ describe("shouldIgnore", () => { }); test("should return true if a folder is ignored by .continueignore", async () => { addToTestDir([ - "ignored-folder/", ["ignored-folder/file.txt", "content"], [".continueignore", "ignored-folder/"], ]); @@ -77,9 +76,6 @@ describe("shouldIgnore", () => { test("should return true for deeply nested file ignored by ignore files at multiple levels", async () => { addToTestDir([ - "level1/", - "level1/level2/", - "level1/level2/level3/", ["level1/level2/level3/ignored-file.txt", "content"], ["level1/.gitignore", "level2/"], ["level1/level2/.continueignore", "level3/"], @@ -102,9 +98,6 @@ describe("shouldIgnore", () => { test("should handle multiple levels of directories with some files ignored", async () => { addToTestDir([ - "nested/", - "nested/dir1/", - "nested/dir2/", ["nested/dir1/.gitignore", "ignored.txt"], ["nested/dir1/ignored.txt", "content"], ["nested/dir2/kept.txt", "content"], @@ -123,4 +116,52 @@ describe("shouldIgnore", () => { ); expect(keptResult).toBe(false); }); + + test("should respect default file and folder ignores top level", async () => { + addToTestDir([ + [".env", "contents"], + ["go.sum", "contents"], + ".idea/", + [".idea/test.xml", "contents"], + ]); + let result = await shouldIgnore(TEST_DIR + "/.env", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/go.sum", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/.idea", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/.idea/test.xml", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); + + test("should respect default file and folder ignores at nested level", async () => { + addToTestDir([ + "nested/.idea/test.xml", + ["nested/.env", "contents"], + ["nested/go.sum", "contents"], + ]); + + let result = await shouldIgnore(TEST_DIR + "/nested/.idea", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/.idea/test.xml", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/.env", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/go.sum", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); }); diff --git a/core/indexing/shouldIgnore.ts b/core/indexing/shouldIgnore.ts index 9170bae3e..dd82a0457 100644 --- a/core/indexing/shouldIgnore.ts +++ b/core/indexing/shouldIgnore.ts @@ -1,11 +1,8 @@ import ignore from "ignore"; import type { FileType, IDE } from "../"; -import { findUriInDirs } from "../util/uri"; -import { - DEFAULT_IGNORE, - getGlobalContinueIgArray, - gitIgArrayFromFile, -} from "./ignore"; +import { findUriInDirs, getUriPathBasename } from "../util/uri"; +import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore"; +import { getIgnoreContext } from "./walkDir"; /* Process: @@ -20,23 +17,19 @@ export async function shouldIgnore( rootDirCandidates?: string[], ): Promise { const rootDirUris = rootDirCandidates ?? (await ide.getWorkspaceDirs()); - const { - foundInDir: rootDir, - uri, - relativePathOrBasename, - } = findUriInDirs(fileUri, rootDirUris); - if (!rootDir) { - throw new Error("Should ignore: file uri not found in root dirs"); - } + const { foundInDir: rootDir, uri } = findUriInDirs(fileUri, rootDirUris); - // Global/default ignores - const globalPatterns = getGlobalContinueIgArray(); - const rootIgnoreContext = ignore().add(globalPatterns).add(DEFAULT_IGNORE); - if (rootIgnoreContext.ignores(relativePathOrBasename)) { + if (!rootDir) { return true; } + const defaultAndGlobalIgnores = ignore() + .add(defaultIgnoreFileAndDir) + .add(getGlobalContinueIgArray()); + let currentDir = uri; + let directParent = true; + let fileType = 1 as FileType.File as FileType; while (currentDir !== rootDir) { // Go to parent dir of file const splitUri = currentDir.split("/"); @@ -45,38 +38,32 @@ export async function shouldIgnore( // Get all files in the dir const dirEntries = await ide.listDir(currentDir); - const dirFiles = dirEntries - .filter(([_, entryType]) => entryType === (1 as FileType.File)) - .map(([name, _]) => name); - // Find ignore files and get ignore arrays from their contexts - const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore"); - const continueIgnoreFile = dirFiles.find( - (name) => name === ".continueignore", + // Check if the file is a symbolic link, ignore if so + if (directParent) { + directParent = false; + const baseName = getUriPathBasename(fileUri); + const entry = dirEntries.find(([name, _]) => name === baseName); + if (entry) { + fileType = entry[1]; + if (fileType === (64 as FileType.SymbolicLink)) { + return true; + } + } + } + + const ignoreContext = await getIgnoreContext( + currentDir, + dirEntries, + ide, + defaultAndGlobalIgnores, ); - const getGitIgnorePatterns = async () => { - if (gitIgnoreFile) { - const contents = await ide.readFile(`${currentDir}/.gitignore`); - return gitIgArrayFromFile(contents); - } - return []; - }; - const getContinueIgnorePatterns = async () => { - if (continueIgnoreFile) { - const contents = await ide.readFile(`${currentDir}/.continueignore`); - return gitIgArrayFromFile(contents); - } - return []; - }; + let relativePath = uri.substring(currentDir.length + 1); + if (fileType === (2 as FileType.Directory)) { + relativePath += "/"; + } - const ignoreArrays = await Promise.all([ - getGitIgnorePatterns(), - getContinueIgnorePatterns(), - ]); - const ignoreContext = ignore().add(ignoreArrays[0]).add(ignoreArrays[1]); - - const relativePath = uri.substring(currentDir.length + 1); if (ignoreContext.ignores(relativePath)) { return true; } diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 8a9d26e7e..8ded86670 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -1,14 +1,14 @@ // Generated by continue -import { testIde } from "../test/fixtures"; -import { - setUpTestDir, - tearDownTestDir, - addToTestDir, - TEST_DIR_PATH, -} from "../test/testDir"; -import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir"; import fs from "fs"; import path from "path"; +import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir"; +import { testIde } from "../test/fixtures"; +import { + addToTestDir, + setUpTestDir, + tearDownTestDir, + TEST_DIR_PATH, +} from "../test/testDir"; describe("walkDir functions", () => { beforeEach(async () => { @@ -19,6 +19,27 @@ describe("walkDir functions", () => { tearDownTestDir(); }); + // describe.only("test speed", () => { + // it("should walk a simple directory structure", async () => { + // addToTestDir([ + // "src/", + // ["src/file1.ts", "content1"], + // ["src/file2.ts", "content2"], + // "src/nested/", + // ["src/nested/file3.ts", "content3"], + // ]); + + // const dir = await testIde.getWorkspaceDirs(); + + // const start = Date.now(); + // for (let i = 0; i < 10000; i++) { + // await walkDir(dir[0], testIde); + // } + // const passed = Date.now() - start; + // console.log(`Test took ${passed} ms`); + // }); + // }); + describe("walkDir", () => { it("should walk a simple directory structure", async () => { addToTestDir([ @@ -313,6 +334,9 @@ describe("walkDir functions", () => { ["node_modules/package/index.js", "content"], ["dist/bundle.js", "content"], ["coverage/lcov.env", "content"], + ["nested/node_modules/package/index.js", "content"], + ["nested/dist/bundle.js", "content"], + ["nested/coverage/lcov.env", "content"], ]); const files = await walkDir( @@ -327,6 +351,9 @@ describe("walkDir functions", () => { expect(files).not.toContain(".git/config"); expect(files).not.toContain("node_modules/package/index.js"); expect(files).not.toContain("coverage/lcov.info"); + expect(files).not.toContain("nested/node_modules/package/index.js"); + expect(files).not.toContain("nested/dist/bundle.js"); + expect(files).not.toContain("nested/coverage/lcov.env"); }); it("should handle directory-specific ignore patterns correctly", async () => { diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 4e97e01d4..757163d96 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -2,27 +2,23 @@ import ignore, { Ignore } from "ignore"; import type { FileType, IDE } from ".."; +import { joinPathsToUri } from "../util/uri"; import { - DEFAULT_IGNORE_DIRS, - DEFAULT_IGNORE_FILETYPES, - defaultIgnoreDir, - defaultIgnoreFile, + defaultIgnoreFileAndDir, getGlobalContinueIgArray, gitIgArrayFromFile, } from "./ignore"; -import { joinPathsToUri } from "../util/uri"; export interface WalkerOptions { - ignoreFiles?: string[]; onlyDirs?: boolean; returnRelativeUrisPaths?: boolean; - additionalIgnoreRules?: string[]; } type Entry = [string, FileType]; // helper struct used for the DFS walk type WalkableEntry = { + name: string; relativeUriPath: string; uri: string; type: FileType; @@ -41,143 +37,110 @@ type IgnoreContext = { }; class DFSWalker { - private readonly ignoreFileNames: Set; - constructor( private readonly uri: string, private readonly ide: IDE, private readonly options: WalkerOptions, - ) { - this.ignoreFileNames = new Set(options.ignoreFiles); - } + ) {} // walk is a depth-first search implementation public async *walk(): AsyncGenerator { - const root = this.newRootWalkContext(); - const stack = [root]; - for (let cur = stack.pop(); cur; cur = stack.pop()) { - const walkableEntries = await this.listDirForWalking(cur.walkableEntry); - const ignoreContexts = await this.getIgnoreToApplyInDir( - cur, - walkableEntries, - ); - for (const w of walkableEntries) { - if (!this.shouldInclude(w, ignoreContexts)) { - continue; - } - if (this.entryIsDirectory(w.entry)) { - stack.push({ - walkableEntry: w, - ignoreContexts: ignoreContexts, - }); - if (this.options.onlyDirs) { - // when onlyDirs is enabled the walker will only return directory names - if (this.options.returnRelativeUrisPaths) { - yield w.relativeUriPath; - } else { - yield w.uri; - } - } - } else { - // Note that shouldInclude handles skipping files if options.onlyDirs is true - if (this.options.returnRelativeUrisPaths) { - yield w.relativeUriPath; - } else { - yield w.uri; - } - } - } - } - } + const defaultAndGlobalIgnores = ignore() + .add(defaultIgnoreFileAndDir) + .add(getGlobalContinueIgArray()); - private newRootWalkContext(): WalkContext { - const globalIgnoreFile = getGlobalContinueIgArray(); - return { + const rootContext: WalkContext = { walkableEntry: { + name: "", relativeUriPath: "", uri: this.uri, type: 2 as FileType.Directory, entry: ["", 2 as FileType.Directory], }, - ignoreContexts: [ + ignoreContexts: [], + }; + const stack = [rootContext]; + + for (let cur = stack.pop(); cur; cur = stack.pop()) { + // Only directories will be added to the stack + const entries = await this.ide.listDir(cur.walkableEntry.uri); + + const newIgnore = await getIgnoreContext( + cur.walkableEntry.uri, + entries, + this.ide, + defaultAndGlobalIgnores, + ); + + const ignoreContexts = [ + ...cur.ignoreContexts, { - ignore: ignore() - .add(defaultIgnoreDir) - .add(defaultIgnoreFile) - .add(globalIgnoreFile), - dirname: "", + ignore: newIgnore, + dirname: cur.walkableEntry.relativeUriPath, }, - ], - }; - } + ]; - private async listDirForWalking( - walkableEntry: WalkableEntry, - ): Promise { - const entries = await this.ide.listDir(walkableEntry.uri); - return entries.map((e) => ({ - relativeUriPath: `${walkableEntry.relativeUriPath}${walkableEntry.relativeUriPath ? "/" : ""}${e[0]}`, - uri: joinPathsToUri(walkableEntry.uri, e[0]), - type: e[1], - entry: e, - })); - } + for (const entry of entries) { + if (this.entryIsSymlink(entry)) { + // If called from the root, a symlink either links to a real file in this repository, + // and therefore will be walked OR it links to something outside of the repository and + // we do not want to index it + continue; + } + const walkableEntry = { + name: entry[0], + relativeUriPath: `${cur.walkableEntry.relativeUriPath}${cur.walkableEntry.relativeUriPath ? "/" : ""}${entry[0]}`, + uri: joinPathsToUri(cur.walkableEntry.uri, entry[0]), + type: entry[1], + entry: entry, + }; - private async getIgnoreToApplyInDir( - curDir: WalkContext, - entriesInDir: WalkableEntry[], - ): Promise { - const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir); - if (ignoreFilesInDir.length === 0) { - return curDir.ignoreContexts; - } - const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat(); - const newIgnoreContext = { - ignore: ignore().add(patterns), - dirname: curDir.walkableEntry.relativeUriPath, - }; - return [...curDir.ignoreContexts, newIgnoreContext]; - } + let relPath = walkableEntry.relativeUriPath; + if (this.entryIsDirectory(entry)) { + relPath = `${relPath}/`; + } else { + if (this.options.onlyDirs) { + continue; + } + } + let shouldInclude = true; + for (const ig of ignoreContexts) { + // remove the directory name and path separator from the match path, unless this an ignore file + // in the root directory + const prefixLength = + ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; + // The ignore library expects a path relative to the ignore file location + const matchPath = relPath.substring(prefixLength); + if (ig.ignore.ignores(matchPath)) { + shouldInclude = false; + } + } + if (!shouldInclude) { + continue; + } - private async loadIgnoreFiles(entries: WalkableEntry[]): Promise { - const ignoreEntries = entries.filter((w) => - this.entryIsIgnoreFile(w.entry), - ); - const promises = ignoreEntries.map(async (w) => { - return await this.ide.readFile(w.uri); - }); - return Promise.all(promises); - } - - private shouldInclude( - walkableEntry: WalkableEntry, - ignoreContexts: IgnoreContext[], - ) { - if (this.entryIsSymlink(walkableEntry.entry)) { - // If called from the root, a symlink either links to a real file in this repository, - // and therefore will be walked OR it links to something outside of the repository and - // we do not want to index it - return false; - } - let relPath = walkableEntry.relativeUriPath; - if (this.entryIsDirectory(walkableEntry.entry)) { - relPath = `${relPath}/`; - } else { - if (this.options.onlyDirs) { - return false; + if (this.entryIsDirectory(entry)) { + stack.push({ + walkableEntry, + ignoreContexts, + }); + if (this.options.onlyDirs) { + // when onlyDirs is enabled the walker will only return directory names + if (this.options.returnRelativeUrisPaths) { + yield walkableEntry.relativeUriPath; + } else { + yield walkableEntry.uri; + } + } + } else { + if (this.options.returnRelativeUrisPaths) { + yield walkableEntry.relativeUriPath; + } else { + yield walkableEntry.uri; + } + } } } - for (const ig of ignoreContexts) { - // remove the directory name and path separator from the match path, unless this an ignore file - // in the root directory - const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; - // The ignore library expects a path relative to the ignore file location - const matchPath = relPath.substring(prefixLength); - if (ig.ignore.ignores(matchPath)) { - return false; - } - } - return true; } private entryIsDirectory(entry: Entry) { @@ -187,21 +150,9 @@ class DFSWalker { private entryIsSymlink(entry: Entry) { return entry[1] === (64 as FileType.SymbolicLink); } - - private entryIsIgnoreFile(e: Entry): boolean { - if ( - e[1] === (2 as FileType.Directory) || - e[1] === (64 as FileType.SymbolicLink) - ) { - return false; - } - return this.ignoreFileNames.has(e[0]); - } } const defaultOptions: WalkerOptions = { - ignoreFiles: [".gitignore", ".continueignore"], - additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES], onlyDirs: false, returnRelativeUrisPaths: false, }; @@ -238,3 +189,49 @@ export async function walkDirs( ); return results.flat(); } + +export async function getIgnoreContext( + currentDir: string, + currentDirEntries: Entry[], + ide: IDE, + defaultAndGlobalIgnores: Ignore, +) { + const dirFiles = currentDirEntries + .filter(([_, entryType]) => entryType === (1 as FileType.File)) + .map(([name, _]) => name); + + // Find ignore files and get ignore arrays from their contexts + // These are done separately so that .continueignore can override .gitignore + const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore"); + const continueIgnoreFile = dirFiles.find( + (name) => name === ".continueignore", + ); + + const getGitIgnorePatterns = async () => { + if (gitIgnoreFile) { + const contents = await ide.readFile(`${currentDir}/.gitignore`); + return gitIgArrayFromFile(contents); + } + return []; + }; + const getContinueIgnorePatterns = async () => { + if (continueIgnoreFile) { + const contents = await ide.readFile(`${currentDir}/.continueignore`); + return gitIgArrayFromFile(contents); + } + return []; + }; + + const ignoreArrays = await Promise.all([ + getGitIgnorePatterns(), + getContinueIgnorePatterns(), + ]); + + // Note precedence here! + const ignoreContext = ignore() + .add(ignoreArrays[0]) // gitignore + .add(defaultAndGlobalIgnores) // default file/folder ignores followed by global .continueignore - this is combined for speed + .add(ignoreArrays[1]); // local .continueignore + + return ignoreContext; +} diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index d991d140a..7859c7cf7 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -16,7 +16,7 @@ export async function getPromptFilesFromDir( return []; } - const uris = await walkDir(dir, ide, { ignoreFiles: [] }); + const uris = await walkDir(dir, ide); const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); const results = promptFilePaths.map(async (uri) => { const content = await ide.readFile(uri); // make a try catch From 06bfaee488163cc217236a8169ab006bb409ea28 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 15:56:59 -0800 Subject: [PATCH 056/127] did change active ignores --- core/core.ts | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/core/core.ts b/core/core.ts index 33ff03776..a3fe41f2b 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,7 +1,4 @@ -import path from "path"; - import { fetchwithRequestOptions } from "@continuedev/fetch"; -import ignore from "ignore"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; @@ -52,7 +49,6 @@ import { type IndexingProgressUpdate, } from "."; -import { defaultIgnoreFile } from "./indexing/ignore"; import { shouldIgnore } from "./indexing/shouldIgnore"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -995,19 +991,15 @@ export class Core { }); on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - const ignoreInstance = ignore().add(defaultIgnoreFile); - let rootDirectory = await this.ide.getWorkspaceDirs(); - const relativeFilePath = path.relative(rootDirectory[0], filepath); try { - if (!ignoreInstance.ignores(relativeFilePath)) { + const ignore = shouldIgnore(filepath, this.ide); + if (!ignore) { recentlyEditedFilesCache.set(filepath, filepath); } } catch (e) { - if (e instanceof RangeError) { - // do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json` - } else { - console.debug("unhandled ignores error", relativeFilePath, e); - } + console.error( + `didChangeActiveTextEditor: failed to udpate recentlyEditedFiles cache for ${filepath}`, + ); } }); From 1edb910bcbfe40b9c58d38479f14d5d437bfd61e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 15:58:34 -0800 Subject: [PATCH 057/127] cleanup --- core/core.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index a3fe41f2b..7a45bcd03 100644 --- a/core/core.ts +++ b/core/core.ts @@ -998,7 +998,7 @@ export class Core { } } catch (e) { console.error( - `didChangeActiveTextEditor: failed to udpate recentlyEditedFiles cache for ${filepath}`, + `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, ); } }); From dbfc346de43ae41a49c516b2375f3e7ea3312803 Mon Sep 17 00:00:00 2001 From: baipaiha Date: Sat, 8 Mar 2025 01:00:07 +0100 Subject: [PATCH 058/127] docs: fix bad yaml-reference links --- docs/docs/customize/deep-dives/configuration.md | 2 +- docs/docs/yaml-migration.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index 11522e86f..5cd0ebf24 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -18,7 +18,7 @@ To open your configuration file, you can click the "gear" icon in the bottom rig When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist. -See the full reference for `config.yaml` [here](../../reference.md). +See the full reference for `config.yaml` [here](../../yaml-reference.md). ## Deprecated configuration methods diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index 0a7773670..4619018f2 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -12,7 +12,7 @@ See also - [Intro to YAML](https://yaml.org/) - [JSON Continue Config Reference](/json-reference) -- [YAML Continue Config Reference](/reference) +- [YAML Continue Config Reference](/yaml-reference) ## Create YAML file @@ -37,9 +37,9 @@ Add all model configurations in `config.json`, including models in `models`, `ta - `inlineEdit` -> e.g. `roles: [chat, edit]` - `applyCodeBlock` -> e.g. `roles: [chat, apply]` -Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/reference#requestoptions) +Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions) -Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/reference#completionoptions) +Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions) From b2568b7296d19262b605c0fa3043970d5624e3ab Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 16:11:52 -0800 Subject: [PATCH 059/127] account for disable indexing --- core/core.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/core/core.ts b/core/core.ts index 7a45bcd03..c4370aac2 100644 --- a/core/core.ts +++ b/core/core.ts @@ -827,7 +827,7 @@ export class Core { // Codebase indexing on("index/forceReIndex", async ({ data }) => { const { config } = await this.configHandler.loadConfig(); - if (config?.disableIndexing) { + if (!config || config.disableIndexing) { return; // TODO silent in case of commands? } if (data?.shouldClearIndexes) { @@ -891,10 +891,13 @@ export class Core { shouldClearIndexes: true, }); } else { - // Reindex the file - const ignore = await shouldIgnore(uri, this.ide); - if (!ignore) { - await this.refreshCodebaseIndexFiles([uri]); + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + // Reindex the file + const ignore = await shouldIgnore(uri, this.ide); + if (!ignore) { + await this.refreshCodebaseIndexFiles([uri]); + } } } } @@ -913,7 +916,10 @@ export class Core { this.messenger.send("refreshSubmenuItems", { providers: ["file"], }); - await this.refreshCodebaseIndexFiles(toRefresh); + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + await this.refreshCodebaseIndexFiles(toRefresh); + } } }; From d42f32b022c63a30b6315cf3607a1f88dc6adc4b Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 7 Mar 2025 17:46:00 -0800 Subject: [PATCH 060/127] increase timeout for o1/o1-preview tests --- core/llm/llm.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index 9912b862e..ff897d5a3 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -205,10 +205,11 @@ describe("LLM", () => { }); testLLM( new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }), - { skip: false, timeout: 20000 }, + { skip: false, timeout: 60000 }, ); testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), { skip: false, + timeout: 60000, }); testLLM( new Gemini({ From fe036fa5096311bae5095cf432abda717f52e093 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 7 Mar 2025 17:40:13 -0800 Subject: [PATCH 061/127] cache the .test-extensions folder to avoid flaky tests due to VS Code Extension Marketplace timeout --- .github/workflows/pr_checks.yaml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 02b458d21..5fe472a10 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -409,6 +409,14 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + # We don't want to cache the Continue extension, so it is deleted at the end of the job + - uses: actions/cache@v4 + id: test-extensions-cache + with: + path: extensions/vscode/e2e/.test-extensions + # package.json used as the key because that's where the download script is defined + key: vscode-test-extensions-${{ hashFiles('extensions/vscode/package.json') }} + - name: Download build artifact uses: actions/download-artifact@v4 with: @@ -450,6 +458,11 @@ jobs: env: DISPLAY: :99 + - name: Delete continue from test extensions + run: | + cd extensions/vscode + rm -rf e2e/.test-extensions/continue* + - name: Upload e2e test screenshots if: failure() uses: actions/upload-artifact@v4 From 0917ddf9a534891c267d659de7f776df59bad65d Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 7 Mar 2025 22:53:42 -0800 Subject: [PATCH 062/127] remove "Autodetect" --- core/config/load.ts | 3 +-- core/config/yaml/models.ts | 3 +-- extensions/vscode/package-lock.json | 4 ++-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index 8005ff555..3636b4bf8 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -71,7 +71,6 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; -import { capitalizeFirstLetter } from "../util/text"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -273,7 +272,7 @@ async function intermediateToFinalConfig( { ...desc, model: modelName, - title: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, + title: modelName, }, ide.readFile.bind(ide), uniqueId, diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 240a7044e..b4392d519 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -3,7 +3,6 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { IDE, IdeSettings, LLMOptions } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; -import { capitalizeFirstLetter } from "../../util/text"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; const AUTODETECT = "AUTODETECT"; @@ -128,7 +127,7 @@ async function autodetectModels( { ...model, model: modelName, - name: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, + name: modelName, }, uniqueId, ideSettings, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index cbcebc34e..ed46978a0 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.3", + "version": "1.1.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.3", + "version": "1.1.4", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", From f86c95ebdbd1851bcbf0e6f22d18a348a8a154ed Mon Sep 17 00:00:00 2001 From: liuk Date: Sat, 8 Mar 2025 23:27:04 +0800 Subject: [PATCH 063/127] fix: Ensure valid line index for highlighter --- .../continueintellijextension/editor/DiffStreamHandler.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index e44c08dd5..55df303a8 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -13,6 +13,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile +import kotlin.math.max import kotlin.math.min @@ -179,7 +180,7 @@ class DiffStreamHandler( // Update the highlighter to show the current line curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) } curLine.highlighter = editor.markupModel.addLineHighlighter( - curLineKey, min(curLine.index, editor.document.lineCount - 1), HighlighterLayer.LAST + curLineKey, min(curLine.index, max(0, editor.document.lineCount - 1)), HighlighterLayer.LAST ) // Remove the unfinished lines highlighter From c0fc96945d26670105d4652e3d751879cd2213e7 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 08:21:49 -0800 Subject: [PATCH 064/127] ignore ssh tests on forks --- .github/workflows/pr_checks.yaml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 5fe472a10..7ed61ec89 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -303,7 +303,13 @@ jobs: cd extensions/vscode npm ci npm run e2e:compile - FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then + # Exclude SSH tests for forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .) + else + # Include all tests for non-forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + fi echo "test_file_matrix<> $GITHUB_OUTPUT echo "$FILES" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT From 7d7fe143ec9b7148cff6b383016b2baf3eb09e29 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 08:59:40 -0800 Subject: [PATCH 065/127] move to dedicated apply deep dive, to be completed --- docs/docs/customize/deep-dives/_apply.md | 16 ++++++++++++++++ docs/docs/edit/how-to-use-it.md | 7 ------- 2 files changed, 16 insertions(+), 7 deletions(-) create mode 100644 docs/docs/customize/deep-dives/_apply.md diff --git a/docs/docs/customize/deep-dives/_apply.md b/docs/docs/customize/deep-dives/_apply.md new file mode 100644 index 000000000..1f87a1993 --- /dev/null +++ b/docs/docs/customize/deep-dives/_apply.md @@ -0,0 +1,16 @@ +--- +description: Learn how to use the Apply feature +keywords: [apply, speculative] +toc_max_heading_level: 5 +--- + + + +# Apply + +## Instant Diff Apply + +If you have large files (exeeding the output token of your model) the edit apply will delete all lines that exceed the model window. To mitigate you can instead of applying the changes directly, ask the chat LLM to "generate a unified diff". +The resulting diff (if the LLM has not made a mistake) can be instantly applied, changing only the lines that need to change. + +Explainer Video: https://youtu.be/b7Xxsot4gyw diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index 19f8e0ccd..850c34b60 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -35,10 +35,3 @@ You can navigate through each proposed change, accepting or rejecting them using You can also accept or reject all changes at once using cmd/ctrl + shift + enter (to accept) or cmd/ctrl + shift + delete/backspace (to reject). If you want to request a new suggestion for the same highlighted code section, you can use cmd/ctrl + i to re-prompt the model. - -## Instant Diff Apply - -If you have large files (exeeding the output token of your model) the edit apply will delete all lines that exceed the model window. To mitigate you can instead of applying the changes directly, ask the chat LLM to "generate a unified diff". -The resulting diff (if the LLM has not made a mistake) can be instantly applied, changing only the lines that need to change. - -Explainer Video: https://youtu.be/b7Xxsot4gyw \ No newline at end of file From 98739c63eccca5b3177935510d5196c20486e2f4 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 09:29:00 -0800 Subject: [PATCH 066/127] fix ignore api key tests --- .github/workflows/pr_checks.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 7ed61ec89..da4d69970 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -275,7 +275,7 @@ jobs: cd core npm test env: - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true && github.actor == 'dependabot[bot]' }} + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} From 1be8ed69ecab06faced15882e425c562cfae3dd1 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 09:42:12 -0800 Subject: [PATCH 067/127] attempt to fix flaky walkdir test --- core/indexing/walkDir.test.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 8ded86670..50d21c778 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -192,12 +192,7 @@ describe("walkDir functions", () => { it("should skip symlinks", async () => { const filePath = path.join(TEST_DIR_PATH, "real.ts"); addToTestDir([["real.ts", "content"]]); - fs.symlink( - filePath, - path.join(TEST_DIR_PATH, "symlink.ts"), - "file", - () => {}, - ); + fs.symlinkSync(filePath, path.join(TEST_DIR_PATH, "symlink.ts"), "file"); const files = await walkDirs(testIde); From 6bc7c5560e6a003b208a363deb38a65e5b4adb73 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 11:54:09 -0800 Subject: [PATCH 068/127] load .continue/assistants profiles --- core/config/ConfigHandler.ts | 48 ++++++++++++++-- core/config/getSystemPromptDotFile.ts | 55 +++++++++++++++++++ .../profile/ControlPlaneProfileLoader.ts | 1 + core/config/profile/LocalProfileLoader.ts | 2 + core/config/profile/PlatformProfileLoader.ts | 1 + core/config/profile/doLoadConfig.ts | 3 +- core/util/paths.ts | 4 ++ extensions/vscode/package-lock.json | 4 +- 8 files changed, 110 insertions(+), 8 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index b9a0f0896..96b5fc6da 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -20,6 +20,7 @@ import { GlobalContext } from "../util/GlobalContext.js"; import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; import { localPathToUri } from "../util/pathToUri.js"; +import { getAllAssistantFiles } from "./getSystemPromptDotFile.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, LOCAL_ONBOARDING_PROVIDER_TITLE, @@ -86,6 +87,25 @@ export class ConfigHandler { }); } + /** + * Users can define as many local assistants as they want in a `.continue/assistants` folder + */ + private async getLocalAssistantProfiles() { + const assistantFiles = await getAllAssistantFiles(this.ide); + const profiles = assistantFiles.map((assistant) => { + return new LocalProfileLoader( + this.ide, + this.ideSettingsPromise, + this.controlPlaneClient, + this.writeLog, + assistant.path, + ); + }); + return profiles.map( + (profile) => new ProfileLifecycleManager(profile, this.ide), + ); + } + /** * Retrieves the titles of additional context providers that are of type "submenu". * @@ -98,13 +118,20 @@ export class ConfigHandler { } private async init() { + try { + await this.loadLocalProfilesOnly(); + } catch (e) { + console.error("Failed to load local assistants: ", e); + } + try { await this.fetchControlPlaneProfiles(); } catch (e) { // If this fails, make sure at least local profile is loaded console.error("Failed to fetch control plane profiles in init: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); } + try { const configResult = await this.loadConfig(); this.notifyConfigListeners(configResult); @@ -189,7 +216,8 @@ export class ConfigHandler { if (selectedOrgId === null) { // Personal - profiles = [...hubProfiles, this.localProfileManager]; + const allLocalProfiles = await this.getAllLocalProfiles(); + profiles = [...hubProfiles, ...allLocalProfiles]; } else { // Organization profiles = hubProfiles; @@ -199,6 +227,16 @@ export class ConfigHandler { await this.updateAvailableProfiles(profiles); } + private async getAllLocalProfiles() { + const localAssistantProfiles = await this.getLocalAssistantProfiles(); + return [this.localProfileManager, ...localAssistantProfiles]; + } + + private async loadLocalProfilesOnly() { + const allLocalProfiles = await this.getAllLocalProfiles(); + await this.updateAvailableProfiles(allLocalProfiles); + } + private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) { this.profiles = profiles; @@ -278,7 +316,7 @@ export class ConfigHandler { } else { try { const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = [this.localProfileManager]; + const profiles = await this.getAllLocalProfiles(); workspaces.forEach((workspace) => { const profileLoader = new ControlPlaneProfileLoader( workspace.id, @@ -296,7 +334,7 @@ export class ConfigHandler { await this.updateAvailableProfiles(profiles); } catch (e: any) { console.error("Failed to load profiles: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); } } } @@ -355,7 +393,7 @@ export class ConfigHandler { ); this.fetchControlPlaneProfiles().catch(async (e) => { console.error("Failed to fetch control plane profiles: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); await this.reloadConfig(); }); } diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts index 550144cd8..1bfc6d1a1 100644 --- a/core/config/getSystemPromptDotFile.ts +++ b/core/config/getSystemPromptDotFile.ts @@ -1,4 +1,6 @@ import { IDE } from ".."; +import { walkDir } from "../indexing/walkDir"; +import { getGlobalAssistantsPath } from "../util/paths"; import { joinPathsToUri } from "../util/uri"; export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; @@ -24,3 +26,56 @@ export async function getSystemPromptDotFile(ide: IDE): Promise { return prompts.join("\n\n"); } + +export const ASSISTANTS_FOLDER = ".continue/assistants"; + +export async function getAssistantFilesFromDir( + ide: IDE, + dir: string, +): Promise<{ path: string; content: string }[]> { + try { + const exists = await ide.fileExists(dir); + + if (!exists) { + return []; + } + + const uris = await walkDir(dir, ide); + const assistantFilePaths = uris.filter( + (p) => p.endsWith(".yaml") || p.endsWith(".yml"), + ); + const results = assistantFilePaths.map(async (uri) => { + const content = await ide.readFile(uri); // make a try catch + return { path: uri, content }; + }); + return Promise.all(results); + } catch (e) { + console.error(e); + return []; + } +} + +export async function getAllAssistantFiles( + ide: IDE, +): Promise<{ path: string; content: string }[]> { + const workspaceDirs = await ide.getWorkspaceDirs(); + let assistantFiles: { path: string; content: string }[] = []; + + let dirsToCheck = [ASSISTANTS_FOLDER]; + const fullDirs = workspaceDirs + .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) + .flat(); + + fullDirs.push(getGlobalAssistantsPath()); + + assistantFiles = ( + await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir))) + ).flat(); + + return await Promise.all( + assistantFiles.map(async (file) => { + const content = await ide.readFile(file.path); + return { path: file.path, content }; + }), + ); +} diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 6df837cf4..fa62d042f 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -68,6 +68,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { undefined, undefined, this.workspaceId, + undefined, ); return { diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 9ccf5c812..921a6170d 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -27,6 +27,7 @@ export default class LocalProfileLoader implements IProfileLoader { private ideSettingsPromise: Promise, private controlPlaneClient: ControlPlaneClient, private writeLog: (message: string) => Promise, + private overrideConfigYamlByPath?: string | undefined, ) {} async doLoadConfig(): Promise> { @@ -39,6 +40,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, undefined, this.description.id, + this.overrideConfigYamlByPath, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index c0fa4c5cc..0a36d7492 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -70,6 +70,7 @@ export default class PlatformProfileLoader implements IProfileLoader { packageSlug: this.packageSlug, }, this.description.id, + undefined ); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 0ec9b4137..2e3e403ef 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -36,6 +36,7 @@ export default async function doLoadConfig( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, profileId: string, + overrideConfigYamlByPath: string | undefined ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -50,7 +51,7 @@ export default async function doLoadConfig( migrateJsonSharedConfig(configJsonPath, ide); } - const configYamlPath = getConfigYamlPath(ideInfo.ideType); + const configYamlPath = overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType); let newConfig: ContinueConfig | undefined; let errors: ConfigValidationError[] | undefined; diff --git a/core/util/paths.ts b/core/util/paths.ts index 31ed8bb02..fc537ed63 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -353,6 +353,10 @@ export function getGlobalPromptsPath(): string { return path.join(getContinueGlobalPath(), "prompts"); } +export function getGlobalAssistantsPath(): string { + return path.join(getContinueGlobalPath(), "assistants"); +} + export function readAllGlobalPromptFiles( folderPath: string = getGlobalPromptsPath(), ): { path: string; content: string }[] { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index ed46978a0..43750054e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.4", + "version": "1.1.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.4", + "version": "1.1.5", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", From edcf5b321cb201c328ed640c13f8e99ac7559137 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 16:09:08 -0800 Subject: [PATCH 069/127] load multiple local assistants --- core/config/ConfigHandler.ts | 56 +++++++++---------- core/config/ProfileLifecycleManager.ts | 1 + .../profile/ControlPlaneProfileLoader.ts | 2 + core/config/profile/LocalProfileLoader.ts | 52 +++++++++++------ core/config/profile/PlatformProfileLoader.ts | 46 ++++++++++++--- core/config/profile/doLoadConfig.ts | 10 +++- core/config/yaml/loadYaml.ts | 6 +- core/control-plane/env.ts | 2 +- core/util/paths.ts | 10 +++- gui/src/components/AddModelButtonSubtext.tsx | 2 +- .../components/modelSelection/ModelSelect.tsx | 14 ++--- .../modelSelection/platform/utils.ts | 3 +- gui/src/pages/AddNewModel/AddNewModel.tsx | 2 +- gui/src/pages/config/index.tsx | 2 +- gui/src/util/index.ts | 2 +- 15 files changed, 134 insertions(+), 76 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 96b5fc6da..d50e63235 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,5 +1,3 @@ -import * as fs from "node:fs"; - import { ConfigResult, FullSlug } from "@continuedev/config-yaml"; import { @@ -17,8 +15,6 @@ import { } from "../index.js"; import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; -import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; -import { localPathToUri } from "../util/pathToUri.js"; import { getAllAssistantFiles } from "./getSystemPromptDotFile.js"; import { @@ -98,7 +94,7 @@ export class ConfigHandler { this.ideSettingsPromise, this.controlPlaneClient, this.writeLog, - assistant.path, + assistant, ); }); return profiles.map( @@ -162,14 +158,12 @@ export class ConfigHandler { async openConfigProfile(profileId?: string) { let openProfileId = profileId || this.selectedProfileId; - if (openProfileId === "local") { + const profile = this.profiles?.find( + (p) => p.profileDescription.id === openProfileId, + ); + if (profile?.profileDescription.profileType === "local") { const ideInfo = await this.ide.getIdeInfo(); - const configYamlPath = getConfigYamlPath(ideInfo.ideType); - if (fs.existsSync(configYamlPath)) { - await this.ide.openFile(localPathToUri(configYamlPath)); - } else { - await this.ide.openFile(localPathToUri(getConfigJsonPath())); - } + await this.ide.openFile(profile.profileDescription.uri); } else { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); @@ -194,25 +188,27 @@ export class ConfigHandler { const assistants = await this.controlPlaneClient.listAssistants(selectedOrgId); - const hubProfiles = assistants.map((assistant) => { - const profileLoader = new PlatformProfileLoader( - { - ...assistant.configResult, - config: assistant.configResult.config, - }, - assistant.ownerSlug, - assistant.packageSlug, - assistant.iconUrl, - assistant.configResult.config?.version ?? "latest", - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); + const hubProfiles = await Promise.all( + assistants.map(async (assistant) => { + const profileLoader = await PlatformProfileLoader.create( + { + ...assistant.configResult, + config: assistant.configResult.config, + }, + assistant.ownerSlug, + assistant.packageSlug, + assistant.iconUrl, + assistant.configResult.config?.version ?? "latest", + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); - return new ProfileLifecycleManager(profileLoader, this.ide); - }); + return new ProfileLifecycleManager(profileLoader, this.ide); + }), + ); if (selectedOrgId === null) { // Personal diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index deaf5f40e..b7946ed7d 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -21,6 +21,7 @@ export interface ProfileDescription { id: string; iconUrl: string; errors: ConfigValidationError[] | undefined; + uri: string; } export interface OrganizationDescription { diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index fa62d042f..cce940ab7 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -10,6 +10,7 @@ import { } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { PRODUCTION_ENV } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -40,6 +41,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { }, title: workspaceTitle, errors: undefined, + uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`, }; setInterval(async () => { diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 921a6170d..13a1480c9 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,34 +1,54 @@ -import { ConfigResult } from "@continuedev/config-yaml"; +import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { getPrimaryConfigFilePath } from "../../util/paths.js"; +import { localPathToUri } from "../../util/pathToUri.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; export default class LocalProfileLoader implements IProfileLoader { static ID = "local"; - description: ProfileDescription = { - id: LocalProfileLoader.ID, - profileType: "local", - fullSlug: { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - iconUrl: "", - title: "Local Config", - errors: undefined, - }; constructor( private ide: IDE, private ideSettingsPromise: Promise, private controlPlaneClient: ControlPlaneClient, private writeLog: (message: string) => Promise, - private overrideConfigYamlByPath?: string | undefined, - ) {} + private overrideAssistantFile?: + | { path: string; content: string } + | undefined, + ) { + const description: ProfileDescription = { + id: overrideAssistantFile?.path ?? LocalProfileLoader.ID, + profileType: "local", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + iconUrl: "", + title: overrideAssistantFile?.path ?? "Local Config", + errors: undefined, + uri: + overrideAssistantFile?.path ?? + localPathToUri(getPrimaryConfigFilePath()), + }; + this.description = description; + if (overrideAssistantFile?.content) { + try { + const parsedAssistant = parseConfigYaml( + overrideAssistantFile?.content ?? "", + ); + this.description.title = parsedAssistant.name; + } catch (e) { + console.error("Failed to parse assistant file: ", e); + } + } + } + description: ProfileDescription; async doLoadConfig(): Promise> { const result = await doLoadConfig( @@ -40,7 +60,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, undefined, this.description.id, - this.overrideConfigYamlByPath, + this.overrideAssistantFile?.path, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 0a36d7492..329a7a59e 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -5,6 +5,7 @@ import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { getControlPlaneEnv } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -21,21 +22,35 @@ export interface PlatformConfigMetadata { export default class PlatformProfileLoader implements IProfileLoader { static RELOAD_INTERVAL = 1000 * 5; // 5 seconds - description: ProfileDescription; - - constructor( + private constructor( private configResult: ConfigResult, private readonly ownerSlug: string, private readonly packageSlug: string, private readonly iconUrl: string, - versionSlug: string, + private readonly versionSlug: string, private readonly controlPlaneClient: ControlPlaneClient, private readonly ide: IDE, private ideSettingsPromise: Promise, private writeLog: (message: string) => Promise, private readonly onReload: () => void, - ) { - this.description = { + readonly description: ProfileDescription, + ) {} + + static async create( + configResult: ConfigResult, + ownerSlug: string, + packageSlug: string, + iconUrl: string, + versionSlug: string, + controlPlaneClient: ControlPlaneClient, + ide: IDE, + ideSettingsPromise: Promise, + writeLog: (message: string) => Promise, + onReload: () => void, + ): Promise { + const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise); + + const description: ProfileDescription = { id: `${ownerSlug}/${packageSlug}`, profileType: "platform", fullSlug: { @@ -45,8 +60,23 @@ export default class PlatformProfileLoader implements IProfileLoader { }, title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`, errors: configResult.errors, - iconUrl: this.iconUrl, + iconUrl: iconUrl, + uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`, }; + + return new PlatformProfileLoader( + configResult, + ownerSlug, + packageSlug, + iconUrl, + versionSlug, + controlPlaneClient, + ide, + ideSettingsPromise, + writeLog, + onReload, + description, + ); } async doLoadConfig(): Promise> { @@ -70,7 +100,7 @@ export default class PlatformProfileLoader implements IProfileLoader { packageSlug: this.packageSlug, }, this.description.id, - undefined + undefined, ); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 2e3e403ef..224b7b64e 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -19,13 +19,14 @@ import { getControlPlaneEnv } from "../../control-plane/env.js"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; +import { localPathOrUriToPath } from "../../util/pathToUri"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; import { loadContinueConfigFromJson } from "../load"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; +import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; -import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; export default async function doLoadConfig( ide: IDE, @@ -36,7 +37,7 @@ export default async function doLoadConfig( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, profileId: string, - overrideConfigYamlByPath: string | undefined + overrideConfigYamlByPath: string | undefined, ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -51,7 +52,9 @@ export default async function doLoadConfig( migrateJsonSharedConfig(configJsonPath, ide); } - const configYamlPath = overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType); + const configYamlPath = localPathOrUriToPath( + overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType), + ); let newConfig: ContinueConfig | undefined; let errors: ConfigValidationError[] | undefined; @@ -69,6 +72,7 @@ export default async function doLoadConfig( overrideConfigYaml, platformConfigMetadata, controlPlaneClient, + configYamlPath, ); newConfig = result.config; errors = result.errors; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index b008092e9..8d0ebf60a 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -366,10 +366,14 @@ export async function loadContinueConfigFromYaml( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, controlPlaneClient: ControlPlaneClient, + configYamlPath: string | undefined, ): Promise> { const rawYaml = overrideConfigYaml === undefined - ? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8") + ? fs.readFileSync( + configYamlPath ?? getConfigYamlPath(ideInfo.ideType), + "utf-8", + ) : ""; const configYamlResult = await loadConfigYaml( diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 288901cab..8995dca7e 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -18,7 +18,7 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; const WORKOS_ENV_ID_PRODUCTION = "continue"; const WORKOS_ENV_ID_STAGING = "continue-staging"; -const PRODUCTION_ENV: ControlPlaneEnv = { +export const PRODUCTION_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", CONTROL_PLANE_URL: diff --git a/core/util/paths.ts b/core/util/paths.ts index fc537ed63..02d2f43b5 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -103,7 +103,7 @@ export function getConfigJsonPath(ideType: IdeType = "vscode"): string { return p; } -export function getConfigYamlPath(ideType: IdeType): string { +export function getConfigYamlPath(ideType?: IdeType): string { const p = path.join(getContinueGlobalPath(), "config.yaml"); // if (!fs.existsSync(p)) { // if (ideType === "jetbrains") { @@ -115,6 +115,14 @@ export function getConfigYamlPath(ideType: IdeType): string { return p; } +export function getPrimaryConfigFilePath(): string { + const configYamlPath = getConfigYamlPath(); + if (fs.existsSync(configYamlPath)) { + return configYamlPath; + } + return getConfigJsonPath(); +} + export function getConfigTsPath(): string { const p = path.join(getContinueGlobalPath(), "config.ts"); if (!fs.existsSync(p)) { diff --git a/gui/src/components/AddModelButtonSubtext.tsx b/gui/src/components/AddModelButtonSubtext.tsx index 0ebb2ed9d..aa7ef99b5 100644 --- a/gui/src/components/AddModelButtonSubtext.tsx +++ b/gui/src/components/AddModelButtonSubtext.tsx @@ -12,7 +12,7 @@ function AddModelButtonSubtext() { className="cursor-pointer underline" onClick={() => ideMessenger.post("config/openProfile", { - profileId: "local", + profileId: undefined, }) } > diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index d99ced546..7cf854e4d 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -19,14 +19,10 @@ import { setDefaultModel, } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { - getFontSize, - getMetaKeyLabel, - isMetaEquivalentKeyPressed, -} from "../../util"; +import { getFontSize, isMetaEquivalentKeyPressed } from "../../util"; import ConfirmationDialog from "../dialogs/ConfirmationDialog"; +import Shortcut from "../gui/Shortcut"; import { Divider } from "./platform/shared"; -import Shortcut from '../gui/Shortcut'; interface ModelOptionProps { option: Option; @@ -166,9 +162,7 @@ function ModelOption({ e.stopPropagation(); e.preventDefault(); - ideMessenger.post("config/openProfile", { - profileId: "local", - }); + ideMessenger.post("config/openProfile", { profileId: undefined }); } function handleOptionClick(e: any) { @@ -351,7 +345,7 @@ function ModelSelect() {
- {selectedProfile?.id === "local" && ( + {selectedProfile?.profileType === "local" && ( <> { ideMessenger.post("config/openProfile", { - profileId: "local", + profileId: undefined, }); }} > diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index 79c81a221..f82443531 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -297,7 +297,7 @@ function ConfigPage() {
{selectedProfile && ( - {selectedProfile.id === "local" + {selectedProfile.profileType === "local" ? "Open Config File" : hubEnabled ? "Open Assistant" diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts index eb5fc2324..2636a3b67 100644 --- a/gui/src/util/index.ts +++ b/gui/src/util/index.ts @@ -108,5 +108,5 @@ export function updatedObj(old: any, pathToValue: { [key: string]: any }) { } export function isLocalProfile(profile: ProfileDescription): boolean { - return profile.id === "local"; + return profile.profileType === "local"; } From 5dfc9110c6f22104a16920e19f82ce21b84c9d7f Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 16:18:51 -0800 Subject: [PATCH 070/127] ignore .continue folder --- .continueignore | 3 ++- .gitignore | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.continueignore b/.continueignore index 79e924012..50684c187 100644 --- a/.continueignore +++ b/.continueignore @@ -5,4 +5,5 @@ docs/docs/languages .vscode/ .archive/ **/*.scm -**/*.diff \ No newline at end of file +**/*.diff +.continue/ \ No newline at end of file diff --git a/.gitignore b/.gitignore index f331ec68c..94efa5983 100644 --- a/.gitignore +++ b/.gitignore @@ -168,4 +168,5 @@ extensions/.continue-debug/ *.vsix -.continuerules \ No newline at end of file +.continuerules +.continue/ \ No newline at end of file From 693540155b719e5059d838a0cc82fa487690fb43 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 16:19:05 -0800 Subject: [PATCH 071/127] hot reload local assistants --- core/core.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/core/core.ts b/core/core.ts index d5b0f6d8e..4861013bf 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,12 +30,7 @@ import { ChatDescriber } from "./util/chatDescriber"; import { clipboardCache } from "./util/clipboardCache"; import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; -import { - editConfigJson, - getConfigJsonPath, - migrateV1DevDataFiles, -} from "./util/paths"; -import { localPathToUri } from "./util/pathToUri"; +import { editConfigJson, migrateV1DevDataFiles } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; @@ -860,7 +855,10 @@ export class Core { for (const uri of data.uris) { // Listen for file changes in the workspace // URI TODO is this equality statement valid? - if (URI.equal(uri, localPathToUri(getConfigJsonPath()))) { + const currentProfileUri = + this.configHandler.currentProfile?.profileDescription.uri ?? ""; + + if (URI.equal(uri, currentProfileUri)) { // Trigger a toast notification to provide UI feedback that config has been updated const showToast = this.globalContext.get("showConfigUpdateToast") ?? true; @@ -874,6 +872,8 @@ export class Core { this.globalContext.update("showConfigUpdateToast", false); } } + await this.configHandler.reloadConfig(); + continue; } if ( From e426b3afe97e0eca6848e0267200b9fb62bcf7d9 Mon Sep 17 00:00:00 2001 From: aadarshkt Date: Sun, 9 Mar 2025 11:58:39 +0530 Subject: [PATCH 072/127] Remove keyboard shortcut hints from chat menu options to match exact quickPick item's label --- extensions/vscode/src/commands.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index fa6b44c2a..87455e210 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -954,11 +954,11 @@ const getCommandsMap: ( } } else if (selectedOption === "$(feedback) Give feedback") { vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); - } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { + } else if (selectedOption === "$(comment) Open chat") { vscode.commands.executeCommand("continue.focusContinueInput"); } else if ( selectedOption === - "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" + "$(screen-full) Open full screen chat" ) { vscode.commands.executeCommand("continue.toggleFullScreen"); } else if (selectedOption === "$(question) Open help center") { From e41bceffe55d7532bfbf98943162af1e8cb66eb3 Mon Sep 17 00:00:00 2001 From: aadarshkt Date: Sun, 9 Mar 2025 11:58:51 +0530 Subject: [PATCH 073/127] Update command name for focusing Continue chat input --- 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 04b3aee59..392108ee6 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -319,7 +319,7 @@ "group": "Continue" }, { - "command": "continue.focusContinueSessionId", + "command": "continue.focusContinueInput", "category": "Continue", "title": "Focus Continue Chat", "group": "Continue" From 7e0b3d93870ad10ecb7f8f1e4092511af74fa7dc Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Sun, 9 Mar 2025 06:25:23 -0400 Subject: [PATCH 074/127] Fix logic for setting IGNORE_SSH_TESTS The logic for checking for dependabot introduced in fda4cc8096 skip ssh on dependabot PRs was somewhat confused; this was partially fixed in 98739c63ec fix ignore api key tests Make IGNORE_SSH_TESTS match. --- .github/workflows/pr_checks.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index da4d69970..6dbae92a6 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -460,7 +460,7 @@ jobs: - name: Run e2e tests run: | cd extensions/vscode - IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} + IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} env: DISPLAY: :99 From ba80343cabe080e6098eee39004f48b3725070d1 Mon Sep 17 00:00:00 2001 From: Daniel Barduhn Date: Sun, 9 Mar 2025 16:33:17 +0100 Subject: [PATCH 075/127] added tools support for fireworks.ai --- core/llm/llms/OpenAI.ts | 12 +++++++++++- core/llm/toolSupport.ts | 13 +++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 92f0aca08..139d033ab 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -97,6 +97,10 @@ class OpenAI extends BaseLLM { return !!model && (model.startsWith("o1") || model.startsWith("o3")); } + private isFireworksAiModel(model?: string): boolean { + return !!model && model.startsWith("accounts/fireworks/models"); + } + protected supportsPrediction(model: string): boolean { const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"]; return SUPPORTED_MODELS.some((m) => model.includes(m)); @@ -274,7 +278,13 @@ class OpenAI extends BaseLLM { body.max_completion_tokens = undefined; } - if (body.tools?.length && !body.model?.startsWith("o3")) { + if (body.tools?.length) { + if (this.isFireworksAiModel(body.model)) { + // fireworks.ai does not support parallel tool calls, but their api expects this to be true anyway otherwise they return an error. + // tooling works with them as a inference provider once this is set to true. + // https://docs.fireworks.ai/guides/function-calling#openai-compatibility + body.parallel_tool_calls = true; + } // To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs // In practice, setting this to true and asking for multiple tool calls // leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}' diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index ebe6599f8..06994ec93 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -39,6 +39,19 @@ export const PROVIDER_TOOL_SUPPORT: Record< ) { return true; } + // firworks-ai https://docs.fireworks.ai/guides/function-calling + if (model.startsWith("accounts/fireworks/models/")) { + switch (model.substring(26)) { + case "llama-v3p1-405b-instruct": + case "llama-v3p1-70b-instruct": + case "qwen2p5-72b-instruct": + case "firefunction-v1": + case "firefunction-v2": + return true; + default: + return false; + } + } }, gemini: (model) => { // All gemini models support function calling From d7b30155c2b139a3c11c9c9db85c4be2d86c038c Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 10:51:37 -0700 Subject: [PATCH 076/127] fix bug in codebase retrieval --- core/indexing/LanceDbIndex.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 168a4ff07..2b2f23a77 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -24,6 +24,7 @@ import { } from "./types"; import type * as LanceType from "vectordb"; +import { localPathToUri } from "../util/pathToUri"; interface LanceDbRow { uuid: string; @@ -498,7 +499,7 @@ export class LanceDbIndex implements CodebaseIndex { return data.map((d) => { return { digest: d.cacheKey, - filepath: d.path, + filepath: localPathToUri(d.path), startLine: d.startLine, endLine: d.endLine, index: 0, From 91426f233cbdbb04c9af894d8b3340031257df88 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 10:54:58 -0700 Subject: [PATCH 077/127] isolate errors in the different codebase retrieval steps --- .../pipelines/BaseRetrievalPipeline.ts | 27 ++++------ .../pipelines/NoRerankerRetrievalPipeline.ts | 46 ++++++++++++----- .../pipelines/RerankerRetrievalPipeline.ts | 51 ++++++++++++++----- 3 files changed, 81 insertions(+), 43 deletions(-) diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index d91931327..a3dcc0f7e 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -80,24 +80,19 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { args: RetrievalPipelineRunArguments, n: number, ): Promise { - try { - if (args.query.trim() === "") { - return []; - } - - const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); - const tokens = this.escapeFtsQueryString(tokensRaw); - - return await this.ftsIndex.retrieve({ - n, - text: tokens, - tags: args.tags, - directory: args.filterDirectory, - }); - } catch (e) { - console.warn("Error retrieving from FTS:", e); + if (args.query.trim() === "") { return []; } + + const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); + const tokens = this.escapeFtsQueryString(tokensRaw); + + return await this.ftsIndex.retrieve({ + n, + text: tokens, + tags: args.tags, + directory: args.filterDirectory, + }); } protected async retrieveAndChunkRecentlyEditedFiles( diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index 889005414..f35809fed 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -19,22 +19,42 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(args, ftsNFinal); + let ftsChunks: Chunk[] = []; + try { + ftsChunks = await this.retrieveFts(args, ftsNFinal); + } catch (error) { + console.error("Error retrieving FTS chunks:", error); + } - const embeddingsChunks = !!config.selectedModelByRole.embed - ? await this.retrieveEmbeddings(input, embeddingsNFinal) - : []; + let embeddingsChunks: Chunk[] = []; + try { + embeddingsChunks = !!config.selectedModelByRole.embed + ? await this.retrieveEmbeddings(input, embeddingsNFinal) + : []; + } catch (error) { + console.error("Error retrieving embeddings:", error); + } - const recentlyEditedFilesChunks = - await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); + let recentlyEditedFilesChunks: Chunk[] = []; + try { + recentlyEditedFilesChunks = + await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); + } catch (error) { + console.error("Error retrieving recently edited files:", error); + } - const repoMapChunks = await requestFilesFromRepoMap( - this.options.llm, - this.options.config, - this.options.ide, - input, - filterDirectory, - ); + let repoMapChunks: Chunk[] = []; + try { + repoMapChunks = await requestFilesFromRepoMap( + this.options.llm, + this.options.config, + this.options.ide, + input, + filterDirectory, + ); + } catch (error) { + console.error("Error retrieving repo map chunks:", error); + } retrievalResults.push( ...recentlyEditedFilesChunks, diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 5fc4f240b..a3e4d830f 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -16,20 +16,42 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(args, nRetrieve); - const embeddingsChunks = !!config.selectedModelByRole.embed - ? await this.retrieveEmbeddings(input, nRetrieve) - : []; - const recentlyEditedFilesChunks = - await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); + let ftsChunks: Chunk[] = []; + try { + ftsChunks = await this.retrieveFts(args, nRetrieve); + } catch (error) { + console.error("Error retrieving FTS chunks:", error); + } - const repoMapChunks = await requestFilesFromRepoMap( - this.options.llm, - this.options.config, - this.options.ide, - input, - filterDirectory, - ); + let embeddingsChunks: Chunk[] = []; + try { + embeddingsChunks = !!config.selectedModelByRole.embed + ? await this.retrieveEmbeddings(input, nRetrieve) + : []; + } catch (error) { + console.error("Error retrieving embeddings chunks:", error); + } + + let recentlyEditedFilesChunks: Chunk[] = []; + try { + recentlyEditedFilesChunks = + await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); + } catch (error) { + console.error("Error retrieving recently edited files chunks:", error); + } + + let repoMapChunks: Chunk[] = []; + try { + repoMapChunks = await requestFilesFromRepoMap( + this.options.llm, + this.options.config, + this.options.ide, + input, + filterDirectory, + ); + } catch (error) { + console.error("Error retrieving repo map chunks:", error); + } retrievalResults.push( ...recentlyEditedFilesChunks, @@ -41,7 +63,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { if (filterDirectory) { // Backup if the individual retrieval methods don't listen retrievalResults = retrievalResults.filter( - (chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, + (chunk) => + !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, ); } From 26d7eb4631b2b41f1b38c180cd4d6f376a8b52f0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 11:57:14 -0700 Subject: [PATCH 078/127] anthropic tool call fix in openai-adapters --- packages/openai-adapters/package.json | 2 +- .../openai-adapters/src/apis/Anthropic.ts | 26 ++++++++ packages/openai-adapters/src/apis/Gemini.ts | 42 ++++++++++++- packages/openai-adapters/src/test/util.ts | 59 +++++++++++++++++++ packages/openai-adapters/src/types.ts | 1 + 5 files changed, 128 insertions(+), 2 deletions(-) diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index b2d293852..f11313bad 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.15", + "version": "1.0.16", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index d8c5b0c44..04b0fbce9 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -71,6 +71,32 @@ export class AnthropicApi implements BaseLlmApi { msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], ): any[] { const messages = msgs.map((message) => { + if (message.role === "tool") { + return { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: message.tool_call_id, + content: + typeof message.content === "string" + ? message.content + : message.content.map((part) => part.text).join(""), + }, + ], + }; + } else if (message.role === "assistant" && message.tool_calls) { + return { + role: "assistant", + content: message.tool_calls.map((toolCall) => ({ + type: "tool_use", + id: toolCall.id, + name: toolCall.function?.name, + input: JSON.parse(toolCall.function?.arguments || "{}"), + })), + }; + } + if (!Array.isArray(message.content)) { return message; } diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index ae2235d25..c17527674 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -86,11 +86,50 @@ export class GeminiApi implements BaseLlmApi { } const isV1API = url.includes("/v1/"); + + const toolCallIdToNameMap = new Map(); const contents = oaiBody.messages .map((msg) => { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents } + + if (msg.role == "assistant" && msg.tool_calls?.length) { + for (const toolCall of msg.tool_calls) { + toolCallIdToNameMap.set(toolCall.id, toolCall.function.name); + } + + return { + role: "model", + parts: msg.tool_calls.map((toolCall) => ({ + functionCall: { + name: toolCall.function.name, + args: JSON.parse(toolCall.function.arguments || "{}"), + }, + })), + }; + } + + if (msg.role === "tool") { + return { + role: "user", + parts: [ + { + functionResponse: { + name: msg.tool_call_id, + response: { + name: toolCallIdToNameMap.get(msg.tool_call_id), + content: + typeof msg.content === "string" + ? msg.content + : msg.content.map((part) => part.text).join(""), + }, + }, + }, + ], + }; + } + if (!msg.content) { return null; } @@ -246,9 +285,10 @@ export class GeminiApi implements BaseLlmApi { `models/${body.model}:streamGenerateContent?key=${this.config.apiKey}`, this.apiBase, ).toString(); + const convertedBody = this._convertBody(body, apiURL); const resp = await customFetch(this.config.requestOptions)(apiURL, { method: "POST", - body: JSON.stringify(this._convertBody(body, apiURL)), + body: JSON.stringify(convertedBody), signal, }); diff --git a/packages/openai-adapters/src/test/util.ts b/packages/openai-adapters/src/test/util.ts index 5b1b52ab1..ba4490f2a 100644 --- a/packages/openai-adapters/src/test/util.ts +++ b/packages/openai-adapters/src/test/util.ts @@ -260,6 +260,65 @@ export function testChat(api: BaseLlmApi, model: string) { const parsedArgs = JSON.parse(args); expect(parsedArgs.name).toBe("Nate"); }); + + test("Tool Call second message works", async () => { + let response = ""; + for await (const chunk of api.chatCompletionStream( + { + messages: [ + { + role: "user", + content: + "Hi, my name is Nate. Please call the say_hello function to respond to me, then respond to me again.", + }, + { + role: "assistant", + tool_calls: [ + { + function: { + arguments: '{"name":"Nate"}', + name: "say_hello", + }, + id: "tool_call_1", + type: "function", + }, + ], + }, + { + role: "tool", + tool_call_id: "tool_call_1", + content: "Nate was greeted", + }, + ], + tools: [ + { + function: { + name: "say_hello", + description: "Say Hello", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the person to greet", + }, + }, + }, + }, + type: "function", + }, + ], + stream: true, + model, + }, + new AbortController().signal, + )) { + console.log(JSON.stringify(chunk, null, 2)); + response += chunk.choices[0].delta.content ?? ""; + } + + expect(response.length).toBeGreaterThan(0); + }); } export function testCompletion(api: BaseLlmApi, model: string) { diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index c59c8c8f7..30fd2cef0 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -54,6 +54,7 @@ export const OpenAIConfigSchema = BasePlusConfig.extend({ z.literal("vllm"), z.literal("x-ai"), z.literal("scaleway"), + z.literal("ncompass"), ]), }); export type OpenAIConfig = z.infer; From 21934981cd90594c5d75ce9cbada90d6b37115a0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 18:10:15 -0700 Subject: [PATCH 079/127] only ignore assistants --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 94efa5983..b24d52983 100644 --- a/.gitignore +++ b/.gitignore @@ -169,4 +169,4 @@ extensions/.continue-debug/ *.vsix .continuerules -.continue/ \ No newline at end of file +.continue/assistants/ \ No newline at end of file From 81511a10640aa5a5eca40a253e5fc8bff6b117cd Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 18:13:31 -0700 Subject: [PATCH 080/127] fix uri bug --- core/config/getSystemPromptDotFile.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts index 1bfc6d1a1..de2c25db8 100644 --- a/core/config/getSystemPromptDotFile.ts +++ b/core/config/getSystemPromptDotFile.ts @@ -1,6 +1,7 @@ import { IDE } from ".."; import { walkDir } from "../indexing/walkDir"; import { getGlobalAssistantsPath } from "../util/paths"; +import { localPathToUri } from "../util/pathToUri"; import { joinPathsToUri } from "../util/uri"; export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; @@ -34,7 +35,7 @@ export async function getAssistantFilesFromDir( dir: string, ): Promise<{ path: string; content: string }[]> { try { - const exists = await ide.fileExists(dir); + const exists = await ide.fileExists(localPathToUri(dir)); if (!exists) { return []; From fc306c736374661f56fb73204f1149ffb05865a0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 19:55:19 -0700 Subject: [PATCH 081/127] bump --- 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 caa49d1dc..347351b00 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.5", + "version": "1.1.6", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From be0fc05f2bacb0bb0efe1182ea872978802a5b02 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 21:54:48 -0700 Subject: [PATCH 082/127] fix --- core/config/getSystemPromptDotFile.ts | 4 ++-- extensions/vscode/package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts index de2c25db8..fa07b9cfd 100644 --- a/core/config/getSystemPromptDotFile.ts +++ b/core/config/getSystemPromptDotFile.ts @@ -35,7 +35,7 @@ export async function getAssistantFilesFromDir( dir: string, ): Promise<{ path: string; content: string }[]> { try { - const exists = await ide.fileExists(localPathToUri(dir)); + const exists = await ide.fileExists(dir); if (!exists) { return []; @@ -67,7 +67,7 @@ export async function getAllAssistantFiles( .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) .flat(); - fullDirs.push(getGlobalAssistantsPath()); + fullDirs.push(localPathToUri(getGlobalAssistantsPath())); assistantFiles = ( await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir))) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 46ba6fa70..e313d1ddd 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.6", + "version": "1.1.7", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From f01c37feb3777e3939d7deb9a43abae4ba14c942 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 22:12:12 -0700 Subject: [PATCH 083/127] load local profiles when logged out --- core/config/ConfigHandler.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index d50e63235..8f2c6ad4c 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -182,7 +182,8 @@ export class ConfigHandler { let profiles: ProfileLifecycleManager[] | null = null; if (!userId) { // Not logged in - profiles = [this.localProfileManager]; + const allLocalProfiles = await this.getAllLocalProfiles(); + profiles = [...allLocalProfiles]; } else { // Logged in const assistants = From f84eee6c0b2eb4cd7fab6bd87223563c4d0f3ec3 Mon Sep 17 00:00:00 2001 From: gyeongmin-ju Date: Mon, 10 Mar 2025 19:18:24 +0900 Subject: [PATCH 084/127] Issue #4474 bug fixed. Fixed the problem where log information was not transmitted even when registering an autocomplete event in the data section of config.json. Signed-off-by: Ju, Gyeongmin --- core/data/log.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/data/log.ts b/core/data/log.ts index 1b810d851..6af4738eb 100644 --- a/core/data/log.ts +++ b/core/data/log.ts @@ -47,7 +47,7 @@ export class DataLogger { newBody.eventName = eventName; } if ("timestamp" in zodSchema.shape) { - newBody.timestamp = new Date().toISOString(); + newBody.timestamp = Date.now(); } if ("schema" in zodSchema.shape) { newBody.schema = schema; From c6cfa9334690cf7f9ecdf99959537ce522728079 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 11:35:15 -0700 Subject: [PATCH 085/127] feat: explore dialog ui --- gui/src/redux/slices/uiSlice.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 4751fed5c..fe54f388c 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -16,6 +16,7 @@ type UIState = { dialogMessage: string | JSX.Element | undefined; dialogEntryOn: boolean; onboardingCard: OnboardingCardState; + isExploreDialogOpen: boolean; shouldAddFileForEditing: boolean; useTools: boolean; toolSettings: { [toolName: string]: ToolSetting }; @@ -31,6 +32,7 @@ export const uiSlice = createSlice({ dialogMessage: "", dialogEntryOn: false, onboardingCard: defaultOnboardingCardState, + isExploreDialogOpen: false, shouldAddFileForEditing: false, ttsActive: false, useTools: false, @@ -67,6 +69,12 @@ export const uiSlice = createSlice({ setShowDialog: (state, action: PayloadAction) => { state.showDialog = action.payload; }, + setIsExploreDialogOpen: ( + state, + action: PayloadAction, + ) => { + state.isExploreDialogOpen = action.payload; + }, // Tools toggleUseTools: (state) => { state.useTools = !state.useTools; @@ -105,6 +113,7 @@ export const { setDialogMessage, setDialogEntryOn, setShowDialog, + setIsExploreDialogOpen, toggleUseTools, toggleToolSetting, addTool, From d11376ba7f2b7ab1a85c75f361631fc2c5c26ab5 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 11:44:54 -0700 Subject: [PATCH 086/127] feat: reusable card --- gui/src/components/ReusableCard.tsx | 42 +++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 gui/src/components/ReusableCard.tsx diff --git a/gui/src/components/ReusableCard.tsx b/gui/src/components/ReusableCard.tsx new file mode 100644 index 000000000..2eb2c483d --- /dev/null +++ b/gui/src/components/ReusableCard.tsx @@ -0,0 +1,42 @@ +import { XMarkIcon } from "@heroicons/react/24/outline"; +import styled from "styled-components"; +import { CloseButton, defaultBorderRadius, vscInputBackground } from "."; + +const StyledCard = styled.div` + margin: auto; + border-radius: ${defaultBorderRadius}; + background-color: ${vscInputBackground}; + box-shadow: + 0 20px 25px -5px rgb(0 0 0 / 0.1), + 0 8px 10px -6px rgb(0 0 0 / 0.1); +`; + +interface ReusableCardProps { + children: React.ReactNode; + showCloseButton?: boolean; + onClose?: () => void; + className?: string; + testId?: string; +} + +export function ReusableCard({ + children, + showCloseButton, + onClose, + className = "", + testId, +}: ReusableCardProps) { + return ( + + {showCloseButton && ( + + + + )} +
{children}
+
+ ); +} From 3c0e6d453fa5c06a963f26a21e0912742226562a Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 11:45:54 -0700 Subject: [PATCH 087/127] improv: ui --- .../OnboardingCard/OnboardingCard.tsx | 37 ++++++------------- 1 file changed, 11 insertions(+), 26 deletions(-) diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index f48e2939d..466c1309e 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -1,20 +1,9 @@ -import * as Tabs from "./tabs"; -import { TabTitle, OnboardingCardTabs } from "./components/OnboardingCardTabs"; -import { XMarkIcon } from "@heroicons/react/24/outline"; -import styled from "styled-components"; -import { CloseButton, defaultBorderRadius, vscInputBackground } from "../"; -import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; -import { useOnboardingCard } from "./hooks/useOnboardingCard"; import { useAppSelector } from "../../redux/hooks"; - -const StyledCard = styled.div` - margin: auto; - border-radius: ${defaultBorderRadius}; - background-color: ${vscInputBackground}; - box-shadow: - 0 20px 25px -5px rgb(0 0 0 / 0.1), - 0 8px 10px -6px rgb(0 0 0 / 0.1); -`; +import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; +import { OnboardingCardTabs, TabTitle } from "./components/OnboardingCardTabs"; +import { ReusableCard } from "./components/ReusableCard"; +import { useOnboardingCard } from "./hooks/useOnboardingCard"; +import * as Tabs from "./tabs"; export interface OnboardingCardState { show?: boolean; @@ -47,20 +36,16 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) { } return ( - onboardingCard.close()} + testId="onboarding-card" > - {!isDialog && !!config.models.length && ( - onboardingCard.close()}> - - - )} -
{renderTabContent()}
-
+ {renderTabContent()} + ); } From f2900ec12e1d749f899773b5a8115c84cbe55206 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 11:46:48 -0700 Subject: [PATCH 088/127] improv: ui --- .../OnboardingCard/OnboardingCard.tsx | 2 +- .../platform/PlatformOnboardingCard.tsx | 73 +++++++------------ 2 files changed, 29 insertions(+), 46 deletions(-) diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index 466c1309e..a4baa9a1e 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -1,7 +1,7 @@ import { useAppSelector } from "../../redux/hooks"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; +import { ReusableCard } from "../ReusableCard"; import { OnboardingCardTabs, TabTitle } from "./components/OnboardingCardTabs"; -import { ReusableCard } from "./components/ReusableCard"; import { useOnboardingCard } from "./hooks/useOnboardingCard"; import * as Tabs from "./tabs"; diff --git a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx index a48845c44..63d2c4f32 100644 --- a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx @@ -1,23 +1,12 @@ -import { XMarkIcon } from "@heroicons/react/24/outline"; import { useState } from "react"; -import styled from "styled-components"; -import { CloseButton, defaultBorderRadius, vscInputBackground } from "../.."; +import { useAppSelector } from "../../../redux/hooks"; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; import Alert from "../../gui/Alert"; +import { ReusableCard } from "../../ReusableCard"; import { TabTitle } from "../components/OnboardingCardTabs"; import { useOnboardingCard } from "../hooks"; import OnboardingLocalTab from "../tabs/OnboardingLocalTab"; import MainTab from "./tabs/main"; -import { useAppSelector } from "../../../redux/hooks"; - -const StyledCard = styled.div` - margin: auto; - border-radius: ${defaultBorderRadius}; - background-color: ${vscInputBackground}; - box-shadow: - 0 20px 25px -5px rgb(0 0 0 / 0.1), - 0 8px 10px -6px rgb(0 0 0 / 0.1); -`; export interface OnboardingCardState { show?: boolean; @@ -31,44 +20,38 @@ interface OnboardingCardProps { export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { const onboardingCard = useOnboardingCard(); const config = useAppSelector((store) => store.config.config); + const [currentTab, setCurrentTab] = useState<"main" | "local">("main"); if (getLocalStorage("onboardingStatus") === undefined) { setLocalStorage("onboardingStatus", "Started"); } - const [currentTab, setCurrentTab] = useState<"main" | "local">("main"); - return ( - - {!isDialog && !!config.models.length && ( - onboardingCard.close()}> - - - )} -
-
- {currentTab === "main" ? ( - setCurrentTab("local")} - isDialog={isDialog} - /> - ) : ( -
- - By choosing this option, Continue will be configured by a local{" "} - config.yaml file. If you're just looking to use - Ollama and still want to manage your configuration through - Continue, click{" "} - setCurrentTab("main")}> - here - - - - -
- )} -
+ onboardingCard.close()} + > +
+ {currentTab === "main" ? ( + setCurrentTab("local")} + isDialog={isDialog} + /> + ) : ( +
+ + By choosing this option, Continue will be configured by a local{" "} + config.yaml file. If you're just looking to use + Ollama and still want to manage your configuration through + Continue, click{" "} + setCurrentTab("main")}> + here + + + +
+ )}
- +
); } From 5a777ce464243b09d466d7a11a39ff9e45a74ec5 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 12:12:28 -0700 Subject: [PATCH 089/127] feat: explore hub card --- gui/src/components/ExploreHubCard/index.tsx | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 gui/src/components/ExploreHubCard/index.tsx diff --git a/gui/src/components/ExploreHubCard/index.tsx b/gui/src/components/ExploreHubCard/index.tsx new file mode 100644 index 000000000..bb6341e54 --- /dev/null +++ b/gui/src/components/ExploreHubCard/index.tsx @@ -0,0 +1,38 @@ +import { Button } from ".."; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { setIsExploreDialogOpen } from "../../redux/slices/uiSlice"; +import { ReusableCard } from "../ReusableCard"; + +export function ExploreHubCard() { + const dispatch = useAppDispatch(); + const isOpen = useAppSelector((state) => state.ui.isExploreDialogOpen); + + if (!isOpen) return null; + + return ( + dispatch(setIsExploreDialogOpen(false))} + > +
+

+ Discover Custom AI Assistants +

+ +

+ Explore specialized AI assistants designed to enhance your development + workflow. Find the perfect assistant for code review, documentation, + and more. +

+ + +
+
+ ); +} From 7de0b96776441cb054d791dc77688123ddc5366a Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 12:20:24 -0700 Subject: [PATCH 090/127] improv: ui --- gui/src/pages/gui/Chat.tsx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 51c164799..2eb517df5 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -22,6 +22,7 @@ import { import CodeToEditCard from "../../components/CodeToEditCard"; import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; +import { ExploreHubCard } from "../../components/ExploreHubCard"; import { useFindWidget } from "../../components/find/FindWidget"; import TimelineItem from "../../components/gui/TimelineItem"; import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks"; @@ -587,6 +588,12 @@ export function Chat() {
)} + + {!onboardingCard.show && showTutorialCard === false && ( +
+ +
+ )} )} From c9b444c1ea92e53fd40c35849522447d1db66451 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 12:24:21 -0700 Subject: [PATCH 091/127] improv: ui --- gui/src/components/ExploreHubCard/index.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/gui/src/components/ExploreHubCard/index.tsx b/gui/src/components/ExploreHubCard/index.tsx index bb6341e54..39bf59dac 100644 --- a/gui/src/components/ExploreHubCard/index.tsx +++ b/gui/src/components/ExploreHubCard/index.tsx @@ -26,9 +26,10 @@ export function ExploreHubCard() {

From dce5ff6a364925af14f99e589ed7b7fba771ab93 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 12:29:46 -0700 Subject: [PATCH 092/127] improv: ui --- gui/src/components/ExploreHubCard/index.tsx | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/gui/src/components/ExploreHubCard/index.tsx b/gui/src/components/ExploreHubCard/index.tsx index 39bf59dac..82ec1e545 100644 --- a/gui/src/components/ExploreHubCard/index.tsx +++ b/gui/src/components/ExploreHubCard/index.tsx @@ -1,4 +1,5 @@ -import { Button } from ".."; +import { ChevronRightIcon } from "@heroicons/react/24/outline"; +import { Button, ButtonSubtext } from ".."; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { setIsExploreDialogOpen } from "../../redux/slices/uiSlice"; import { ReusableCard } from "../ReusableCard"; @@ -14,7 +15,7 @@ export function ExploreHubCard() { showCloseButton={true} onClose={() => dispatch(setIsExploreDialogOpen(false))} > -
+

Discover Custom AI Assistants

@@ -31,8 +32,15 @@ export function ExploreHubCard() { // target="_blank" // rel="noopener noreferrer" > - Explore Assistants Hub + Explore Assistants + + console.log("button subtext")}> +
+ Or, create your own assistant + +
+
); From 561dcd931f207d10b5d1d38b5bcd90ac73063fd6 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 10 Mar 2025 13:29:13 -0700 Subject: [PATCH 093/127] catch rerank errors --- .../pipelines/RerankerRetrievalPipeline.ts | 49 ++++++++++--------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index a3e4d830f..6e69a4078 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -82,29 +82,34 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { // remove empty chunks -- some APIs fail on that chunks = chunks.filter((chunk) => chunk.content); - let scores: number[] = - await this.options.config.selectedModelByRole.rerank.rerank( - input, - chunks, + try { + let scores: number[] = + await this.options.config.selectedModelByRole.rerank.rerank( + input, + chunks, + ); + + // Filter out low-scoring results + let results = chunks; + // let results = chunks.filter( + // (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold, + // ); + // scores = scores.filter( + // (score) => score >= RETRIEVAL_PARAMS.rerankThreshold, + // ); + + const chunkIndexMap = new Map(); + chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); + + results.sort( + (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!], ); - - // Filter out low-scoring results - let results = chunks; - // let results = chunks.filter( - // (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold, - // ); - // scores = scores.filter( - // (score) => score >= RETRIEVAL_PARAMS.rerankThreshold, - // ); - - const chunkIndexMap = new Map(); - chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); - - results.sort( - (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!], - ); - results = results.slice(-this.options.nFinal); - return results; + results = results.slice(-this.options.nFinal); + return results; + } catch (e) { + console.warn(`Failed to rerank codebase retrieval results ${e}`); + return chunks; + } } private async _expandWithEmbeddings(chunks: Chunk[]): Promise { From c096a4fd32d04ea55114ad348b9e14a38e843b22 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 10 Mar 2025 13:40:23 -0700 Subject: [PATCH 094/127] ide warnings --- core/context/providers/DocsContextProvider.ts | 5 ++++- .../retrieval/pipelines/RerankerRetrievalPipeline.ts | 7 +++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index f4b816f33..3b9fa0cf4 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -5,6 +5,7 @@ import { ContextProviderDescription, ContextProviderExtras, ContextSubmenuItem, + IDE, LoadSubmenuItemsArgs, } from "../.."; import DocsService from "../../indexing/docs/DocsService"; @@ -36,6 +37,7 @@ class DocsContextProvider extends BaseContextProvider { chunks: Chunk[], reranker: NonNullable, fullInput: ContextProviderExtras["fullInput"], + ide: IDE, ) { let chunksCopy = [...chunks]; @@ -51,7 +53,7 @@ class DocsContextProvider extends BaseContextProvider { this.options?.nFinal ?? DocsContextProvider.nFinal, ); } catch (e) { - console.warn(`Failed to rerank docs results: ${e}`); + void ide.showToast("warning", `Failed to rerank retrieval results\n${e}`); chunksCopy = chunksCopy.splice( 0, @@ -116,6 +118,7 @@ class DocsContextProvider extends BaseContextProvider { chunks, extras.reranker, extras.fullInput, + extras.ide, ); } diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 6e69a4078..e73edf118 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -107,8 +107,11 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { results = results.slice(-this.options.nFinal); return results; } catch (e) { - console.warn(`Failed to rerank codebase retrieval results ${e}`); - return chunks; + void this.options.ide.showToast( + "warning", + `Failed to rerank retrieval results\n${e}`, + ); + return chunks.slice(-this.options.nFinal); } } From 8f2095d10bcc06dadd546624bc39f39c7a1efe1a Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 14:05:23 -0700 Subject: [PATCH 095/127] improv: copy --- gui/src/components/ExploreHubCard/index.tsx | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/gui/src/components/ExploreHubCard/index.tsx b/gui/src/components/ExploreHubCard/index.tsx index 82ec1e545..715c22dea 100644 --- a/gui/src/components/ExploreHubCard/index.tsx +++ b/gui/src/components/ExploreHubCard/index.tsx @@ -16,14 +16,10 @@ export function ExploreHubCard() { onClose={() => dispatch(setIsExploreDialogOpen(false))} >
-

- Discover Custom AI Assistants -

+

Create Your Own Assistant

- Explore specialized AI assistants designed to enhance your development - workflow. Find the perfect assistant for code review, documentation, - and more. + Discover and remix popular assistants, or create your own from scratch

- console.log("button subtext")}> + { + ideMessenger.request("controlPlane/openUrl", { + path: "/new?type=assistant", + orgSlug: undefined, + }); + }} + >
Or, create your own assistant from scratch From 3733d0d670aebae9f80a024f5480e47a4a114b9b Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 15:45:01 -0700 Subject: [PATCH 098/127] bump config-yaml --- core/config/yaml/models.ts | 4 ++++ core/package-lock.json | 8 ++++---- core/package.json | 2 +- extensions/vscode/package-lock.json | 6 +++--- gui/package-lock.json | 2 +- 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index b4392d519..f2270c429 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -49,6 +49,10 @@ async function modelConfigToBaseLLM( title: model.name, systemMessage, promptTemplates: model.promptTemplates, + capabilities: { + tools: model.capabilities?.includes("tool_use"), + uploadImage: model.capabilities?.includes("image_input"), + }, }; if (model.embedOptions?.maxBatchSize) { diff --git a/core/package-lock.json b/core/package-lock.json index a15d33faf..ec99105e1 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.56", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", @@ -3038,9 +3038,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.52", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.52.tgz", - "integrity": "sha512-x0m4bcQpjHrrv95cq5tsen4Hb6yKCVGn+NeojyzNQYnRD0If/On+ATgX78uXtQtZxsdO4ip73HHCyQlA0O3ZyQ==", + "version": "1.0.56", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.56.tgz", + "integrity": "sha512-2OBhmlSFOgZ+Z/ZQ18R/JR9zo6HIzkQ09PCuHQQ9NanN+g5AEVCdWgEtMyOq5DmQM3HLJCoLMXwqzQ9qSJEfFg==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/core/package.json b/core/package.json index a88bf0cf1..75c47caf6 100644 --- a/core/package.json +++ b/core/package.json @@ -46,7 +46,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.56", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 43750054e..5f7702aee 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.5", + "version": "1.1.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.5", + "version": "1.1.7", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.56", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/gui/package-lock.json b/gui/package-lock.json index 74273c5aa..20ade99a1 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -107,7 +107,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.56", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", From f0cae280e481c493a8098039368e8c405d427675 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 10 Mar 2025 15:50:56 -0700 Subject: [PATCH 099/127] this.fetch additions --- core/llm/llms/HuggingFaceTEI.ts | 30 +++++++++------------ core/llm/llms/Voyage.ts | 2 +- core/llm/llms/stubs/ContinueProxy.ts | 2 +- packages/openai-adapters/src/apis/OpenAI.ts | 8 +++--- 4 files changed, 19 insertions(+), 23 deletions(-) diff --git a/core/llm/llms/HuggingFaceTEI.ts b/core/llm/llms/HuggingFaceTEI.ts index 206bbd5e2..52580c187 100644 --- a/core/llm/llms/HuggingFaceTEI.ts +++ b/core/llm/llms/HuggingFaceTEI.ts @@ -1,5 +1,4 @@ import { Chunk, LLMOptions } from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; import { BaseLLM } from "../index.js"; class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { @@ -36,17 +35,15 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { } async doEmbedRequest(batch: string[]): Promise { - const resp = await withExponentialBackoff(() => - this.fetch(new URL("embed", this.apiBase), { - method: "POST", - body: JSON.stringify({ - inputs: batch, - }), - headers: { - "Content-Type": "application/json", - }, + const resp = await this.fetch(new URL("embed", this.apiBase), { + method: "POST", + body: JSON.stringify({ + inputs: batch, }), - ); + headers: { + "Content-Type": "application/json", + }, + }); if (!resp.ok) { const text = await resp.text(); const embedError = JSON.parse(text) as TEIEmbedErrorResponse; @@ -59,11 +56,10 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { } async doInfoRequest(): Promise { - const resp = await withExponentialBackoff(() => - this.fetch(new URL("info", this.apiBase), { - method: "GET", - }), - ); + // TODO - need to use custom fetch for this request? + const resp = await this.fetch(new URL("info", this.apiBase), { + method: "GET", + }); if (!resp.ok) { throw new Error(await resp.text()); } @@ -79,7 +75,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { headers["Authorization"] = `Bearer ${this.apiKey}`; } - const resp = await fetch(new URL("rerank", this.apiBase), { + const resp = await this.fetch(new URL("rerank", this.apiBase), { method: "POST", headers, body: JSON.stringify({ diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index 27db04e17..fe08d8b1d 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -14,7 +14,7 @@ class Voyage extends OpenAI { return []; } const url = new URL("rerank", this.apiBase); - const resp = await fetch(url, { + const resp = await this.fetch(url, { method: "POST", headers: { "Content-Type": "application/json", diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 00ec93dbc..94221ec1c 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -65,7 +65,7 @@ class ContinueProxy extends OpenAI { async rerank(query: string, chunks: Chunk[]): Promise { const url = new URL("rerank", this.apiBase); - const resp = await fetch(url, { + const resp = await this.fetch(url, { method: "POST", headers: { "Content-Type": "application/json", diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index aa059f7db..358f52dca 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -14,7 +14,7 @@ import { } from "openai/resources/index"; import { z } from "zod"; import { OpenAIConfigSchema } from "../types.js"; -import { maybeCustomFetch } from "../util.js"; +import { customFetch, maybeCustomFetch } from "../util.js"; import { BaseLlmApi, CreateRerankResponse, @@ -31,7 +31,7 @@ export class OpenAIApi implements BaseLlmApi { this.openai = new OpenAI({ apiKey: config.apiKey, baseURL: this.apiBase, - fetch: maybeCustomFetch(config.requestOptions), + fetch: customFetch(config.requestOptions), }); } @@ -100,7 +100,7 @@ export class OpenAIApi implements BaseLlmApi { signal: AbortSignal, ): AsyncGenerator { const endpoint = new URL("fim/completions", this.apiBase); - const resp = await fetch(endpoint, { + const resp = await customFetch(this.config.requestOptions)(endpoint, { method: "POST", body: JSON.stringify({ model: body.model, @@ -139,7 +139,7 @@ export class OpenAIApi implements BaseLlmApi { async rerank(body: RerankCreateParams): Promise { const endpoint = new URL("rerank", this.apiBase); - const response = await fetch(endpoint, { + const response = await customFetch(this.config.requestOptions)(endpoint, { method: "POST", body: JSON.stringify(body), headers: { From 9d2a873abce95d4fa9b11bd567c245ee3429e093 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 10 Mar 2025 16:03:03 -0700 Subject: [PATCH 100/127] cohere --- core/llm/llms/Cohere.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 1c895c2fe..86834cb74 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -117,7 +117,7 @@ class Cohere extends BaseLLM { } async rerank(query: string, chunks: Chunk[]): Promise { - const resp = await fetch(new URL("rerank", this.apiBase), { + const resp = await this.fetch(new URL("rerank", this.apiBase), { method: "POST", headers: { Authorization: `Bearer ${this.apiKey}`, From 28d2c7d7e0a00c23c33ad25b8bfc3651ddafa2c5 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 16:25:23 -0700 Subject: [PATCH 101/127] feat: editor change listener --- core/core.ts | 30 +++++++++++++++++++----------- core/protocol/passThrough.ts | 1 + core/protocol/webview.ts | 1 + 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/core/core.ts b/core/core.ts index 4861013bf..a8260fb12 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1002,18 +1002,26 @@ export class Core { return { url }; }); - on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - try { - const ignore = shouldIgnore(filepath, this.ide); - if (!ignore) { - recentlyEditedFilesCache.set(filepath, filepath); + on( + "didChangeActiveTextEditor", + async ({ data: { filepath, filename } }) => { + this.messenger.send("didChangeActiveTextEditor", { + filepath, + filename, + }); + + try { + const ignore = shouldIgnore(filepath, this.ide); + if (!ignore) { + recentlyEditedFilesCache.set(filepath, filepath); + } + } catch (e) { + console.error( + `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, + ); } - } catch (e) { - console.error( - `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, - ); - } - }); + }, + ); on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => { const { config } = await this.configHandler.loadConfig(); diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index ef71c66a1..def86939f 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -84,4 +84,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "getWebviewHistoryLength", "getCurrentSessionId", "docs/suggestions", + "didChangeActiveTextEditor", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 90df4bd0f..7f57d2d1d 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -26,6 +26,7 @@ export type ToWebviewFromIdeOrCoreProtocol = { }, void, ]; + didChangeActiveTextEditor: [{ filepath: string; filename: string }, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ { From 6e01c7d0ca0d139e471edf40018d35e1033638f3 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 10 Mar 2025 16:43:14 -0700 Subject: [PATCH 102/127] feat: tutorial listener --- gui/src/pages/gui/Chat.tsx | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 2eb517df5..bc24bb8ad 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -58,6 +58,7 @@ import { import { setDialogEntryOn, setDialogMessage, + setIsExploreDialogOpen, setShowDialog, } from "../../redux/slices/uiSlice"; import { RootState } from "../../redux/store"; @@ -189,6 +190,24 @@ const useAutoScroll = ( }, [ref, history.length, userHasScrolled]); }; +const useTutorialListener = (onTutorialClosed: () => void) => { + const [isTutorialOpen, setIsTutorialOpen] = useState(false); + console.log("IS TUTORIAL OPEN", isTutorialOpen); + + useWebviewListener("didChangeActiveTextEditor", async (data) => { + console.log("DATA", data.filepath); + const isTutorial = + data?.filepath?.toLowerCase().endsWith("continue_tutorial.py") ?? false; + + if (isTutorialOpen && !isTutorial) { + onTutorialClosed(); + console.log("Tutorial was closed!"); + } + + setIsTutorialOpen(isTutorial); + }); +}; + export function Chat() { const posthog = usePostHog(); const dispatch = useAppDispatch(); @@ -229,6 +248,11 @@ export function Chat() { const lastSessionId = useAppSelector((state) => state.session.lastSessionId); const useHub = useAppSelector(selectUseHub); + useTutorialListener(() => { + setLocalStorage("isExploreDialogOpen", true); + dispatch(setIsExploreDialogOpen(true)); + }); + useEffect(() => { // Cmd + Backspace to delete current step const listener = (e: any) => { From af36d82f418527d090439812825c38a3baf1e5a9 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 17:06:59 -0700 Subject: [PATCH 103/127] localPathToUri don't convert if already converted --- core/util/pathToUri.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/util/pathToUri.ts b/core/util/pathToUri.ts index 67a249d74..36c2bc35f 100644 --- a/core/util/pathToUri.ts +++ b/core/util/pathToUri.ts @@ -6,6 +6,10 @@ import * as URI from "uri-js"; // Converts a local path to a file:/// URI export function localPathToUri(path: string) { + if (path.startsWith("file://")) { + console.warn("localPathToUri: path already starts with file://"); + return path; + } const url = pathToFileURL(path); return URI.normalize(url.toString()); } From 71f0f0fb04d34fb2339673a73d5d808fb2227a3a Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 17:07:20 -0700 Subject: [PATCH 104/127] localPathToUri-related at-codebase fixes --- core/context/retrieval/repoMapRequest.ts | 8 +++++--- core/indexing/LanceDbIndex.ts | 3 +-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 5637019ad..5a4f9be2a 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -2,6 +2,7 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; import { getModelByRole } from "../../config/util"; import generateRepoMap from "../../util/generateRepoMap"; import { renderChatMessage } from "../../util/messageContent"; +import { localPathToUri } from "../../util/pathToUri"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", @@ -72,7 +73,7 @@ This is the question that you should select relevant files for: "${input}"`; return []; } - const fileUris = content + const filepaths = content .split("")[1] ?.split("")[0] ?.split("\n") @@ -80,8 +81,9 @@ This is the question that you should select relevant files for: "${input}"`; .map((uri) => uri.trim()); const chunks = await Promise.all( - fileUris.map(async (uri) => { - const content = await ide.readFile(uri); + filepaths.map(async (filepath) => { + const uri = localPathToUri(filepath); + const content = await ide.readFile(filepath); const lineCount = content.split("\n").length; const chunk: Chunk = { digest: uri, diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 2b2f23a77..168a4ff07 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -24,7 +24,6 @@ import { } from "./types"; import type * as LanceType from "vectordb"; -import { localPathToUri } from "../util/pathToUri"; interface LanceDbRow { uuid: string; @@ -499,7 +498,7 @@ export class LanceDbIndex implements CodebaseIndex { return data.map((d) => { return { digest: d.cacheKey, - filepath: localPathToUri(d.path), + filepath: d.path, startLine: d.startLine, endLine: d.endLine, index: 0, From 4b227f1d3f5a75398700b5445f975dab88d0e19b Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 17:07:27 -0700 Subject: [PATCH 105/127] fix reranker through continue-proxy --- core/llm/llms/stubs/ContinueProxy.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 00ec93dbc..4dd8976b2 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -75,6 +75,7 @@ class ContinueProxy extends OpenAI { query, documents: chunks.map((chunk) => chunk.content), model: this.model, + ...this.extraBodyProperties(), }), }); const data: any = await resp.json(); From a31f0d6a48a730ea263a160fb973b6b9091d806f Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 17:07:41 -0700 Subject: [PATCH 106/127] 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 e313d1ddd..942724cda 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.7", + "version": "1.1.8", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From c819cbf81f9b75191ad0c0bdcbbe3a154167ef98 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 10 Mar 2025 17:13:25 -0700 Subject: [PATCH 107/127] .local env --- core/control-plane/env.ts | 10 +++++++++- core/util/paths.ts | 4 ++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 8995dca7e..7d3ae9eb0 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -1,6 +1,9 @@ import * as fs from "node:fs"; import { IdeSettings } from ".."; -import { getStagingEnvironmentDotFilePath } from "../util/paths"; +import { + getLocalEnvironmentDotFilePath, + getStagingEnvironmentDotFilePath, +} from "../util/paths"; export interface ControlPlaneEnv { DEFAULT_CONTROL_PLANE_PROXY_URL: string; @@ -78,6 +81,11 @@ export function getControlPlaneEnvSync( ideTestEnvironment: IdeSettings["continueTestEnvironment"], enableControlServerBeta: IdeSettings["enableControlServerBeta"], ): ControlPlaneEnv { + // Note .local overrides .staging + if (fs.existsSync(getLocalEnvironmentDotFilePath())) { + return LOCAL_ENV; + } + if (fs.existsSync(getStagingEnvironmentDotFilePath())) { return STAGING_ENV; } diff --git a/core/util/paths.ts b/core/util/paths.ts index 02d2f43b5..3bc2ee3cf 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -418,6 +418,10 @@ export function migrateV1DevDataFiles() { moveToV1FolderIfExists("autocomplete", "autocomplete"); } +export function getLocalEnvironmentDotFilePath(): string { + return path.join(getContinueGlobalPath(), ".local"); +} + export function getStagingEnvironmentDotFilePath(): string { return path.join(getContinueGlobalPath(), ".staging"); } From cfc99b7e57a9ce1a73872a9056d65f0b4a8d174b Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 20:41:40 -0700 Subject: [PATCH 108/127] remove legacy server cache logic --- core/indexing/CodebaseIndexer.ts | 1 - core/indexing/LanceDbIndex.test.ts | 2 - core/indexing/LanceDbIndex.ts | 63 +----------------------------- 3 files changed, 1 insertion(+), 65 deletions(-) diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index d59f0ded8..03fb23897 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -97,7 +97,6 @@ export class CodebaseIndexer { const lanceDbIndex = await LanceDbIndex.create( embeddingsModel, this.ide.readFile.bind(this.ide), - this.continueServerClient, ); if (lanceDbIndex) { diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts index ac6ed3591..ad28b3456 100644 --- a/core/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -9,7 +9,6 @@ import { DatabaseConnection, SqliteDb } from "./refreshIndex"; import { mockPathAndCacheKey, mockTag, - testContinueServerClient, updateIndexAndAwaitGenerator, } from "./test/indexing"; import { IndexResultType } from "./types"; @@ -37,7 +36,6 @@ describe.skip("ChunkCodebaseIndex", () => { index = (await LanceDbIndex.create( mockConfig.selectedModelByRole.embed, testIde.readFile.bind(testIde), - testContinueServerClient, ))!; sqliteDb = await SqliteDb.get(); diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 168a4ff07..3f9630eb1 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -2,7 +2,6 @@ import { RunResult } from "sqlite3"; import { v4 as uuidv4 } from "uuid"; import { isSupportedLanceDbCpuTargetForLinux } from "../config/util"; -import { IContinueServerClient } from "../continueServer/interface"; import { BranchAndDir, Chunk, @@ -57,7 +56,6 @@ export class LanceDbIndex implements CodebaseIndex { static async create( embeddingsProvider: ILLM, readFile: (filepath: string) => Promise, - continueServerClient?: IContinueServerClient, ): Promise { if (!isSupportedLanceDbCpuTargetForLinux()) { return null; @@ -65,11 +63,7 @@ export class LanceDbIndex implements CodebaseIndex { try { this.lance = await import("vectordb"); - return new LanceDbIndex( - embeddingsProvider, - readFile, - continueServerClient, - ); + return new LanceDbIndex(embeddingsProvider, readFile); } catch (err) { console.error("Failed to load LanceDB:", err); return null; @@ -79,7 +73,6 @@ export class LanceDbIndex implements CodebaseIndex { private constructor( private readonly embeddingsProvider: ILLM, private readonly readFile: (filepath: string) => Promise, - private readonly continueServerClient?: IContinueServerClient, ) { if (!LanceDbIndex.lance) { throw new Error("LanceDB not initialized"); @@ -278,60 +271,6 @@ export class LanceDbIndex implements CodebaseIndex { await markComplete(pathAndCacheKeys, IndexResultType.Compute); }; - if (this.continueServerClient?.connected) { - try { - const keys = results.compute.map(({ cacheKey }) => cacheKey); - const resp = await this.continueServerClient.getFromIndexCache( - keys, - "embeddings", - repoName, - ); - for (const [cacheKey, chunks] of Object.entries(resp.files)) { - const path = results.compute.find( - (item) => item.cacheKey === cacheKey, - )?.path; - if (!path) { - console.warn( - "Continue server sent a cacheKey that wasn't requested", - cacheKey, - ); - continue; - } - - const rows: LanceDbRow[] = []; - for (const chunk of chunks) { - const row = { - path, - cachekey: cacheKey, - uuid: uuidv4(), - vector: chunk.vector, - }; - rows.push(row); - - await sqliteDb.run( - "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - row.uuid, - row.cachekey, - row.path, - this.artifactId, - JSON.stringify(row.vector), - chunk.startLine, - chunk.endLine, - chunk.contents, - ); - } - - await addComputedLanceDbRows([{ cacheKey, path }], rows); - } - - results.compute = results.compute.filter( - (item) => !resp.files[item.cacheKey], - ); - } catch (e) { - console.log("Error checking remote cache: ", e); - } - } - yield { progress: 0, desc: `Computing embeddings for ${ From ec092ca498a4576deedfde203145f06ddbc9206f Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 21:25:04 -0700 Subject: [PATCH 109/127] use relative paths and fix URI resolution in codebase repo map retrieval --- core/context/retrieval/repoMapRequest.ts | 15 +++++++++------ core/util/pathToUri.ts | 1 + 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 5a4f9be2a..ee0d5aaf7 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -1,8 +1,8 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; import { getModelByRole } from "../../config/util"; import generateRepoMap from "../../util/generateRepoMap"; +import { resolveRelativePathInDir } from "../../util/ideUtils"; import { renderChatMessage } from "../../util/messageContent"; -import { localPathToUri } from "../../util/pathToUri"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", @@ -49,14 +49,14 @@ export async function requestFilesFromRepoMap( const repoMap = await generateRepoMap(llm, ide, { dirUris: filterDirUri ? [filterDirUri] : undefined, includeSignatures: false, - outputRelativeUriPaths: false, + outputRelativeUriPaths: true, }); const prompt = `${repoMap} Given the above repo map, your task is to decide which files are most likely to be relevant in answering a question. Before giving your answer, you should write your reasoning about which files/folders are most important. This thinking should start with a tag, followed by a paragraph explaining your reasoning, and then a closing tag on the last line. -After this, your response should begin with a tag, followed by a list of each file, one per line, and then a closing tag on the last line. You should select between 5 and 10 files. The names that you list should be the full path from the root of the repo, not just the basename of the file. +After this, your response should begin with a tag, followed by a list of each file, one per line, and then a closing tag on the last line. You should select between 5 and 10 files. The names that you list should be the exact relative path that you saw in the repo map, not just the basename of the file. This is the question that you should select relevant files for: "${input}"`; @@ -78,11 +78,14 @@ This is the question that you should select relevant files for: "${input}"`; ?.split("")[0] ?.split("\n") .filter(Boolean) - .map((uri) => uri.trim()); + .map((filepath) => filepath.trim()); const chunks = await Promise.all( filepaths.map(async (filepath) => { - const uri = localPathToUri(filepath); + const uri = await resolveRelativePathInDir(filepath, ide); + if (!uri) { + return undefined; + } const content = await ide.readFile(filepath); const lineCount = content.split("\n").length; const chunk: Chunk = { @@ -97,7 +100,7 @@ This is the question that you should select relevant files for: "${input}"`; }), ); - return chunks; + return chunks.filter((c) => c !== undefined) as Chunk[]; } catch (e) { console.debug("Error requesting files from repo map", e); return []; diff --git a/core/util/pathToUri.ts b/core/util/pathToUri.ts index 36c2bc35f..ce83563fd 100644 --- a/core/util/pathToUri.ts +++ b/core/util/pathToUri.ts @@ -6,6 +6,7 @@ import * as URI from "uri-js"; // Converts a local path to a file:/// URI export function localPathToUri(path: string) { + // This may incidentally solve bugs, but it is primarily here to warn us if we accidentally try to double-convert. It doesn't handle other URI schemes. if (path.startsWith("file://")) { console.warn("localPathToUri: path already starts with file://"); return path; From eeab38802e0c35463888f0652683e1f5e9668763 Mon Sep 17 00:00:00 2001 From: aadarshkt Date: Tue, 11 Mar 2025 11:17:47 +0530 Subject: [PATCH 110/127] Add new DeepSeek models to config schema --- extensions/vscode/config_schema.json | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 8a1153d0b..807e950df 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1319,7 +1319,17 @@ "nvidia/Llama-3.1-Nemotron-70B-Instruct", "Qwen/Qwen2-VL-72B-Instruct", "TeleAI/TeleMM", - "deepseek-ai/DeepSeek-V2.5" + "deepseek-ai/DeepSeek-V2.5", + "deepseek-ai/deepseek-vl2", + "deepseek-ai/Janus-Pro-7B", + "deepseek-ai/DeepSeek-V3", + "deepseek-ai/DeepSeek-R1", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-14B", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B", + "deepseek-ai/DeepSeek-R1-Distill-Llama-70B", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", + "deepseek-ai/DeepSeek-R1-Distill-Llama-8B" ] } } From ce5d664f828de8681ee7129dfec3c16cad667c46 Mon Sep 17 00:00:00 2001 From: TKSun <1037305420@qq.com> Date: Tue, 11 Mar 2025 21:05:26 +0800 Subject: [PATCH 111/127] fix: issue 3732 ollama version 0.3.12 responses first line as {"id":"x","done":false} without a response value which crashes execution. --- core/llm/llms/Ollama.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 675fd8663..1a409c5f9 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -359,6 +359,7 @@ class Ollama extends BaseLLM implements ModelInstaller{ if ("error" in j) { throw new Error(j.error); } + j.response ??= '' yield j.response; } catch (e) { throw new Error(`Error parsing Ollama response: ${e} ${chunk}`); From d4d3102b61c800576513cbb07c9d482fe973a0ef Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 08:07:46 -0700 Subject: [PATCH 112/127] feat: close tutorial listener --- gui/src/pages/gui/Chat.tsx | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index bc24bb8ad..f594e471e 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -191,20 +191,17 @@ const useAutoScroll = ( }; const useTutorialListener = (onTutorialClosed: () => void) => { - const [isTutorialOpen, setIsTutorialOpen] = useState(false); - console.log("IS TUTORIAL OPEN", isTutorialOpen); + const isTutorialOpenRef = useRef(false); useWebviewListener("didChangeActiveTextEditor", async (data) => { - console.log("DATA", data.filepath); const isTutorial = data?.filepath?.toLowerCase().endsWith("continue_tutorial.py") ?? false; - if (isTutorialOpen && !isTutorial) { + if (isTutorialOpenRef.current && !isTutorial) { onTutorialClosed(); - console.log("Tutorial was closed!"); } - setIsTutorialOpen(isTutorial); + isTutorialOpenRef.current = isTutorial; }); }; From 192a47f998d639f307933f33a731832ff35305ac Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 08:22:06 -0700 Subject: [PATCH 113/127] feat: explore dialog watcher --- gui/src/components/ExploreHubCard/index.tsx | 5 ++-- gui/src/pages/gui/Chat.tsx | 27 +++++-------------- gui/src/pages/gui/ExploreDialogWatcher.tsx | 30 +++++++++++++++++++++ gui/src/redux/slices/uiSlice.ts | 14 +++++++--- gui/src/util/localStorage.ts | 6 +++++ 5 files changed, 56 insertions(+), 26 deletions(-) create mode 100644 gui/src/pages/gui/ExploreDialogWatcher.tsx diff --git a/gui/src/components/ExploreHubCard/index.tsx b/gui/src/components/ExploreHubCard/index.tsx index 3e7f7e9a7..c546becd4 100644 --- a/gui/src/components/ExploreHubCard/index.tsx +++ b/gui/src/components/ExploreHubCard/index.tsx @@ -4,7 +4,7 @@ import { Button, ButtonSubtext } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { setIsExploreDialogOpen } from "../../redux/slices/uiSlice"; -import { setLocalStorage } from "../../util/localStorage"; +import { LocalStorageKey, setLocalStorage } from "../../util/localStorage"; import { ReusableCard } from "../ReusableCard"; export function ExploreHubCard() { @@ -18,7 +18,8 @@ export function ExploreHubCard() { { - setLocalStorage("isExploreDialogOpen", false); + setLocalStorage(LocalStorageKey.IsExploreDialogOpen, false); + setLocalStorage(LocalStorageKey.HasDismissedExploreDialog, true); return dispatch(setIsExploreDialogOpen(false)); }} > diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index f594e471e..9a50285d3 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -58,7 +58,6 @@ import { import { setDialogEntryOn, setDialogMessage, - setIsExploreDialogOpen, setShowDialog, } from "../../redux/slices/uiSlice"; import { RootState } from "../../redux/store"; @@ -78,6 +77,7 @@ import { import getMultifileEditPrompt from "../../util/getMultifileEditPrompt"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import ConfigErrorIndicator from "./ConfigError"; +import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; import ToolOutput from "./ToolCallDiv/ToolOutput"; @@ -190,21 +190,6 @@ const useAutoScroll = ( }, [ref, history.length, userHasScrolled]); }; -const useTutorialListener = (onTutorialClosed: () => void) => { - const isTutorialOpenRef = useRef(false); - - useWebviewListener("didChangeActiveTextEditor", async (data) => { - const isTutorial = - data?.filepath?.toLowerCase().endsWith("continue_tutorial.py") ?? false; - - if (isTutorialOpenRef.current && !isTutorial) { - onTutorialClosed(); - } - - isTutorialOpenRef.current = isTutorial; - }); -}; - export function Chat() { const posthog = usePostHog(); const dispatch = useAppDispatch(); @@ -244,11 +229,9 @@ export function Chat() { ); const lastSessionId = useAppSelector((state) => state.session.lastSessionId); const useHub = useAppSelector(selectUseHub); - - useTutorialListener(() => { - setLocalStorage("isExploreDialogOpen", true); - dispatch(setIsExploreDialogOpen(true)); - }); + const hasDismissedExploreDialog = useAppSelector( + (state) => state.ui.hasDismissedExploreDialog, + ); useEffect(() => { // Cmd + Backspace to delete current step @@ -592,6 +575,8 @@ export function Chat() { /> )} + {!hasDismissedExploreDialog && } + {history.length === 0 && ( <> {onboardingCard.show && ( diff --git a/gui/src/pages/gui/ExploreDialogWatcher.tsx b/gui/src/pages/gui/ExploreDialogWatcher.tsx new file mode 100644 index 000000000..a08d44675 --- /dev/null +++ b/gui/src/pages/gui/ExploreDialogWatcher.tsx @@ -0,0 +1,30 @@ +import { useRef } from "react"; +import { useWebviewListener } from "../../hooks/useWebviewListener"; +import { useAppDispatch } from "../../redux/hooks"; +import { setIsExploreDialogOpen } from "../../redux/slices/uiSlice"; +import { LocalStorageKey, setLocalStorage } from "../../util/localStorage"; + +const useTutorialListener = (onTutorialClosed: () => void) => { + const isTutorialOpenRef = useRef(false); + + useWebviewListener("didChangeActiveTextEditor", async (data) => { + const isTutorial = + data?.filepath?.toLowerCase().endsWith("continue_tutorial.py") ?? false; + + if (isTutorialOpenRef.current && !isTutorial) { + onTutorialClosed(); + } + + isTutorialOpenRef.current = isTutorial; + }); +}; + +export const ExploreDialogWatcher = () => { + const dispatch = useAppDispatch(); + + useTutorialListener(() => { + setLocalStorage(LocalStorageKey.IsExploreDialogOpen, true); + dispatch(setIsExploreDialogOpen(true)); + }); + return null; +}; diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 3362fc0a2..01c398eb5 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -5,7 +5,7 @@ import { defaultOnboardingCardState, OnboardingCardState, } from "../../components/OnboardingCard"; -import { getLocalStorage } from "../../util/localStorage"; +import { getLocalStorage, LocalStorageKey } from "../../util/localStorage"; type ToolSetting = | "allowedWithPermission" @@ -18,6 +18,7 @@ type UIState = { dialogEntryOn: boolean; onboardingCard: OnboardingCardState; isExploreDialogOpen: boolean; + hasDismissedExploreDialog: boolean; shouldAddFileForEditing: boolean; useTools: boolean; toolSettings: { [toolName: string]: ToolSetting }; @@ -33,7 +34,10 @@ export const uiSlice = createSlice({ dialogMessage: "", dialogEntryOn: false, onboardingCard: defaultOnboardingCardState, - isExploreDialogOpen: getLocalStorage("isExploreDialogOpen"), + isExploreDialogOpen: getLocalStorage(LocalStorageKey.IsExploreDialogOpen), + hasDismissedExploreDialog: getLocalStorage( + LocalStorageKey.HasDismissedExploreDialog, + ), shouldAddFileForEditing: false, ttsActive: false, useTools: false, @@ -72,10 +76,13 @@ export const uiSlice = createSlice({ }, setIsExploreDialogOpen: ( state, - action: PayloadAction, + action: PayloadAction, ) => { state.isExploreDialogOpen = action.payload; }, + setHasDismissedExploreDialog: (state, action: PayloadAction) => { + state.hasDismissedExploreDialog = action.payload; + }, // Tools toggleUseTools: (state) => { state.useTools = !state.useTools; @@ -115,6 +122,7 @@ export const { setDialogEntryOn, setShowDialog, setIsExploreDialogOpen, + setHasDismissedExploreDialog, toggleUseTools, toggleToolSetting, addTool, diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index b1863de3a..28d63b847 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -3,6 +3,7 @@ import { OnboardingStatus } from "../components/OnboardingCard"; type LocalStorageTypes = { isExploreDialogOpen: boolean; + hasDismissedExploreDialog: boolean; onboardingStatus?: OnboardingStatus; hasDismissedOnboardingCard: boolean; mainTextEntryCounter: number; @@ -18,6 +19,11 @@ type LocalStorageTypes = { seenHubIntro: boolean; }; +export enum LocalStorageKey { + IsExploreDialogOpen = "isExploreDialogOpen", + HasDismissedExploreDialog = "hasDismissedExploreDialog", +} + export function getLocalStorage( key: T, ): LocalStorageTypes[T] | undefined { From 741ad35195d6b841b459076b8dbca1057d5f6358 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 08:27:33 -0700 Subject: [PATCH 114/127] feat: explore dialog watcher --- gui/src/pages/gui/ExploreDialogWatcher.tsx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/gui/src/pages/gui/ExploreDialogWatcher.tsx b/gui/src/pages/gui/ExploreDialogWatcher.tsx index a08d44675..840dc53c7 100644 --- a/gui/src/pages/gui/ExploreDialogWatcher.tsx +++ b/gui/src/pages/gui/ExploreDialogWatcher.tsx @@ -2,7 +2,11 @@ import { useRef } from "react"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch } from "../../redux/hooks"; import { setIsExploreDialogOpen } from "../../redux/slices/uiSlice"; -import { LocalStorageKey, setLocalStorage } from "../../util/localStorage"; +import { + getLocalStorage, + LocalStorageKey, + setLocalStorage, +} from "../../util/localStorage"; const useTutorialListener = (onTutorialClosed: () => void) => { const isTutorialOpenRef = useRef(false); @@ -24,7 +28,10 @@ export const ExploreDialogWatcher = () => { useTutorialListener(() => { setLocalStorage(LocalStorageKey.IsExploreDialogOpen, true); - dispatch(setIsExploreDialogOpen(true)); + + if (!getLocalStorage(LocalStorageKey.HasDismissedExploreDialog)) { + dispatch(setIsExploreDialogOpen(true)); + } }); return null; }; From dfd46286800f290562d0ac7ed4073ae1bd61a74b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 08:30:37 -0700 Subject: [PATCH 115/127] improv: clean up code --- gui/src/pages/gui/Chat.tsx | 53 +----------------------------- gui/src/pages/gui/useAutoScroll.ts | 53 ++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 52 deletions(-) create mode 100644 gui/src/pages/gui/useAutoScroll.ts diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 9a50285d3..9fe39d41e 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -81,6 +81,7 @@ import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; import ToolOutput from "./ToolCallDiv/ToolOutput"; +import { useAutoScroll } from "./useAutoScroll"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -138,58 +139,6 @@ 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(); diff --git a/gui/src/pages/gui/useAutoScroll.ts b/gui/src/pages/gui/useAutoScroll.ts new file mode 100644 index 000000000..a787e7ec9 --- /dev/null +++ b/gui/src/pages/gui/useAutoScroll.ts @@ -0,0 +1,53 @@ +import { useEffect, useState } from "react"; + +export 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]); +}; From 41a79166aadc2bbbe80145d12bfeb1336d94c7e2 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 08:39:04 -0700 Subject: [PATCH 116/127] fix: types --- core/core.ts | 32 ++++++++++++++------------------ core/protocol/webview.ts | 2 +- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/core/core.ts b/core/core.ts index a8260fb12..d63dec9f8 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1002,26 +1002,22 @@ export class Core { return { url }; }); - on( - "didChangeActiveTextEditor", - async ({ data: { filepath, filename } }) => { - this.messenger.send("didChangeActiveTextEditor", { - filepath, - filename, - }); + on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { + this.messenger.send("didChangeActiveTextEditor", { + filepath, + }); - try { - const ignore = shouldIgnore(filepath, this.ide); - if (!ignore) { - recentlyEditedFilesCache.set(filepath, filepath); - } - } catch (e) { - console.error( - `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, - ); + try { + const ignore = shouldIgnore(filepath, this.ide); + if (!ignore) { + recentlyEditedFilesCache.set(filepath, filepath); } - }, - ); + } catch (e) { + console.error( + `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, + ); + } + }); on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => { const { config } = await this.configHandler.loadConfig(); diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 7f57d2d1d..c492068d2 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -26,7 +26,7 @@ export type ToWebviewFromIdeOrCoreProtocol = { }, void, ]; - didChangeActiveTextEditor: [{ filepath: string; filename: string }, void]; + didChangeActiveTextEditor: [{ filepath: string }, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ { From be153f8ab966e210d6249ff179c4ec1580507d88 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 10:47:11 -0700 Subject: [PATCH 117/127] fix: watcher --- gui/src/pages/gui/ExploreDialogWatcher.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gui/src/pages/gui/ExploreDialogWatcher.tsx b/gui/src/pages/gui/ExploreDialogWatcher.tsx index 840dc53c7..70233b9ca 100644 --- a/gui/src/pages/gui/ExploreDialogWatcher.tsx +++ b/gui/src/pages/gui/ExploreDialogWatcher.tsx @@ -12,8 +12,11 @@ const useTutorialListener = (onTutorialClosed: () => void) => { const isTutorialOpenRef = useRef(false); useWebviewListener("didChangeActiveTextEditor", async (data) => { + const filepath = data?.filepath?.toLowerCase() ?? ""; const isTutorial = - data?.filepath?.toLowerCase().endsWith("continue_tutorial.py") ?? false; + filepath.endsWith("continue_tutorial.py") || + filepath.endsWith("continue_tutorial.java") || + filepath.endsWith("continue_tutorial.ts"); if (isTutorialOpenRef.current && !isTutorial) { onTutorialClosed(); From c8a24c0c9040a0da02bdd215b77b0320c160256f Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 10:58:48 -0700 Subject: [PATCH 118/127] fix: protocols --- core/core.ts | 9 +++++---- core/protocol/core.ts | 1 + core/protocol/passThrough.ts | 2 +- core/protocol/webview.ts | 2 +- extensions/vscode/src/extension/VsCodeExtension.ts | 6 ++++++ 5 files changed, 14 insertions(+), 6 deletions(-) diff --git a/core/core.ts b/core/core.ts index d63dec9f8..cbe42d7c2 100644 --- a/core/core.ts +++ b/core/core.ts @@ -934,6 +934,11 @@ export class Core { void refreshIfNotIgnored(data.uris); } }); + + on("files/closed", async ({ data }) => { + this.messenger.send("didCloseFiles", data); + }); + on("files/opened", async ({ data }) => { if (data?.uris?.length) { // Do something on files opened @@ -1003,10 +1008,6 @@ export class Core { }); on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - this.messenger.send("didChangeActiveTextEditor", { - filepath, - }); - try { const ignore = shouldIgnore(filepath, this.ide); if (!ignore) { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index ac991622a..1b19a46cb 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -184,6 +184,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "files/opened": [{ uris?: string[] }, void]; "files/created": [{ uris?: string[] }, void]; "files/deleted": [{ uris?: string[] }, void]; + "files/closed": [{ uris?: string[] }, void]; // Docs etc. Indexing. TODO move codebase to this "indexing/reindex": [{ type: string; id: string }, void]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index def86939f..352075d2e 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -84,5 +84,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "getWebviewHistoryLength", "getCurrentSessionId", "docs/suggestions", - "didChangeActiveTextEditor", + "didCloseFiles", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index c492068d2..eb587ae60 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -26,7 +26,7 @@ export type ToWebviewFromIdeOrCoreProtocol = { }, void, ]; - didChangeActiveTextEditor: [{ filepath: string }, void]; + didCloseFiles: [{ uris: string[] }, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ { diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 814f6be97..41e91211c 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -310,6 +310,12 @@ export class VsCodeExtension { }); }); + vscode.workspace.onDidCloseTextDocument(async (event) => { + this.core.invoke("files/closed", { + uris: [event.uri.toString()], + }); + }); + vscode.workspace.onDidCreateFiles(async (event) => { this.core.invoke("files/created", { uris: event.files.map((uri) => uri.toString()), From f41c8194fc11da9c76de0531cccd73df78a4b1c2 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 11:01:05 -0700 Subject: [PATCH 119/127] fix: watcher --- gui/src/pages/gui/ExploreDialogWatcher.tsx | 24 ++++++++++++---------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/gui/src/pages/gui/ExploreDialogWatcher.tsx b/gui/src/pages/gui/ExploreDialogWatcher.tsx index 70233b9ca..51851c0f5 100644 --- a/gui/src/pages/gui/ExploreDialogWatcher.tsx +++ b/gui/src/pages/gui/ExploreDialogWatcher.tsx @@ -1,4 +1,3 @@ -import { useRef } from "react"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch } from "../../redux/hooks"; import { setIsExploreDialogOpen } from "../../redux/slices/uiSlice"; @@ -9,20 +8,23 @@ import { } from "../../util/localStorage"; const useTutorialListener = (onTutorialClosed: () => void) => { - const isTutorialOpenRef = useRef(false); + useWebviewListener("didCloseFiles", async (data) => { + const uris = data?.uris ?? []; - useWebviewListener("didChangeActiveTextEditor", async (data) => { - const filepath = data?.filepath?.toLowerCase() ?? ""; - const isTutorial = - filepath.endsWith("continue_tutorial.py") || - filepath.endsWith("continue_tutorial.java") || - filepath.endsWith("continue_tutorial.ts"); + const isTutorial = uris.some((uri) => { + const lowercaseUri = uri.toLowerCase(); + return ( + lowercaseUri.endsWith("continue_tutorial.py") || + lowercaseUri.endsWith("continue_tutorial.java") || + lowercaseUri.endsWith("continue_tutorial.ts") + ); + }); - if (isTutorialOpenRef.current && !isTutorial) { + console.log("IS TUTORIAL", isTutorial, uris); + + if (isTutorial) { onTutorialClosed(); } - - isTutorialOpenRef.current = isTutorial; }); }; From a88f5d771ced366926c9d6d821c697e52847a2f9 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 11:04:09 -0700 Subject: [PATCH 120/127] fix: types --- core/core.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index cbe42d7c2..037bb48ce 100644 --- a/core/core.ts +++ b/core/core.ts @@ -936,7 +936,11 @@ export class Core { }); on("files/closed", async ({ data }) => { - this.messenger.send("didCloseFiles", data); + if (data.uris) { + this.messenger.send("didCloseFiles", { + uris: data.uris, + }); + } }); on("files/opened", async ({ data }) => { From 054b095dab51b3abc7a3d83587e0b5f67b8acdf6 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 11:33:55 -0700 Subject: [PATCH 121/127] feat: jetbrains tutorial explore hub --- .../activities/ContinuePluginStartupActivity.kt | 13 ++++++++++++- .../constants/MessageTypes.kt | 1 + 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 53a8ebd0b..ea5edff96 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -1,5 +1,5 @@ package com.github.continuedev.continueintellijextension.activities - +import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.github.continuedev.continueintellijextension.auth.AuthListener import com.github.continuedev.continueintellijextension.auth.ContinueAuthService import com.github.continuedev.continueintellijextension.auth.ControlPlaneSessionInfo @@ -37,6 +37,7 @@ import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.ide.ui.LafManagerListener +import com.intellij.openapi.vfs.VirtualFile fun showTutorial(project: Project) { val tutorialFileName = getTutorialFileName() @@ -199,6 +200,16 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { } }) + + connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener { + override fun fileClosed(source: FileEditorManager, file: VirtualFile) { + file.toUriOrNull()?.let { uri -> + val data = mapOf("uris" to listOf(uri)) + continuePluginService.coreMessenger?.request("files/closed", data, null) { _ -> } + } + } + }) + // Listen for theme changes connection.subscribe(LafManagerListener.TOPIC, LafManagerListener { val colors = GetTheme().getTheme(); 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 e71401b15..81a6e1313 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 @@ -71,6 +71,7 @@ class MessageTypes { "getWebviewHistoryLength", "getCurrentSessionId", "docs/suggestions", + "didCloseFiles", ) // Note: If updating these values, make a corresponding update in From d1eca9deeb3c1550982f679a58265593af603453 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 11:35:32 -0700 Subject: [PATCH 122/127] feat: close files --- .../activities/ContinuePluginStartupActivity.kt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index ea5edff96..9d48705df 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -208,8 +208,16 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware { continuePluginService.coreMessenger?.request("files/closed", data, null) { _ -> } } } + override fun fileOpened(source: FileEditorManager, file: VirtualFile) { + file.toUriOrNull()?.let { uri -> + val data = mapOf("uris" to listOf(uri)) + continuePluginService.coreMessenger?.request("files/opened", data, null) { _ -> } + } + } }) + + // Listen for theme changes connection.subscribe(LafManagerListener.TOPIC, LafManagerListener { val colors = GetTheme().getTheme(); From e3cf75e0779d3bc02a468ea6551e2499979c08f7 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 11:51:01 -0700 Subject: [PATCH 123/127] fix: logs --- gui/src/pages/gui/ExploreDialogWatcher.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/gui/src/pages/gui/ExploreDialogWatcher.tsx b/gui/src/pages/gui/ExploreDialogWatcher.tsx index 51851c0f5..2bea99d9d 100644 --- a/gui/src/pages/gui/ExploreDialogWatcher.tsx +++ b/gui/src/pages/gui/ExploreDialogWatcher.tsx @@ -20,8 +20,6 @@ const useTutorialListener = (onTutorialClosed: () => void) => { ); }); - console.log("IS TUTORIAL", isTutorial, uris); - if (isTutorial) { onTutorialClosed(); } From ef5d7535f0860978baeb337930f266b1201a7a5c Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 13:58:33 -0700 Subject: [PATCH 124/127] fix: browse functionality --- .../auth/ContinueAuthService.kt | 4 +- .../utils/Desktop.kt | 261 ++++++++++++++++++ 2 files changed, 263 insertions(+), 2 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt index 23b6b66bd..cd44d3e3b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt @@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.auth import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils. import com.google.gson.Gson import com.intellij.credentialStore.Credentials import com.intellij.ide.passwordSafe.PasswordSafe @@ -12,7 +13,6 @@ import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.remoteServer.util.CloudConfigurationUtil.createCredentialAttributes import kotlinx.coroutines.CoroutineScope -import java.awt.Desktop import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -154,7 +154,7 @@ class ContinueAuthService { val authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String if (authUrl != null) { // Open the auth URL in the browser - Desktop.getDesktop().browse(java.net.URI(authUrl)) + Desktop.browse(java.net.URI(authUrl)) } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt new file mode 100644 index 000000000..152a8630b --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt @@ -0,0 +1,261 @@ +/* + * Copyright © 2017 jjYBdx4IL (https://github.com/jjYBdx4IL) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//CHECKSTYLE:OFF +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.SystemUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * @author jjYBdx4IL + */ +public class Desktop { + + private static final Logger LOG = LoggerFactory.getLogger(Desktop.class); + + public static boolean browse(URI uri) { + + if (browseDESKTOP(uri)) { + return true; + } + + if (openSystemSpecific(uri.toString())) { + return true; + } + + LOG.warn(String.format("failed to browse %s", uri)); + + return false; + } + + + public static boolean open(File file) { + + if (openDESKTOP(file)) { + return true; + } + + if (openSystemSpecific(file.getPath())) { + return true; + } + + LOG.warn(String.format("failed to open %s", file.getAbsolutePath())); + + return false; + } + + + public static boolean edit(File file) { + + if (editDESKTOP(file)) { + return true; + } + + if (openSystemSpecific(file.getPath())) { + return true; + } + + LOG.warn(String.format("failed to edit %s", file.getAbsolutePath())); + + return false; + } + + + private static boolean openSystemSpecific(String what) { + + if (SystemUtils.IS_OS_LINUX) { + if (isXDG()) { + if (runCommand("xdg-open", "%s", what)) { + return true; + } + } + if (isKDE()) { + if (runCommand("kde-open", "%s", what)) { + return true; + } + } + if (isGNOME()) { + if (runCommand("gnome-open", "%s", what)) { + return true; + } + } + if (runCommand("kde-open", "%s", what)) { + return true; + } + if (runCommand("gnome-open", "%s", what)) { + return true; + } + } + + if (SystemUtils.IS_OS_MAC) { + if (runCommand("open", "%s", what)) { + return true; + } + } + + if (SystemUtils.IS_OS_WINDOWS) { + if (runCommand("explorer", "%s", what)) { + return true; + } + } + + return false; + } + + + private static boolean browseDESKTOP(URI uri) { + + try { + if (!java.awt.Desktop.isDesktopSupported()) { + LOG.debug("Platform is not supported."); + return false; + } + + if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.BROWSE)) { + LOG.debug("BROWSE is not supported."); + return false; + } + + LOG.info("Trying to use Desktop.getDesktop().browse() with " + uri.toString()); + java.awt.Desktop.getDesktop().browse(uri); + + return true; + } catch (Throwable t) { + LOG.error("Error using desktop browse.", t); + return false; + } + } + + + private static boolean openDESKTOP(File file) { + try { + if (!java.awt.Desktop.isDesktopSupported()) { + LOG.debug("Platform is not supported."); + return false; + } + + if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.OPEN)) { + LOG.debug("OPEN is not supported."); + return false; + } + + LOG.info("Trying to use Desktop.getDesktop().open() with " + file.toString()); + java.awt.Desktop.getDesktop().open(file); + + return true; + } catch (Throwable t) { + LOG.error("Error using desktop open.", t); + return false; + } + } + + + private static boolean editDESKTOP(File file) { + try { + if (!java.awt.Desktop.isDesktopSupported()) { + LOG.debug("Platform is not supported."); + return false; + } + + if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.EDIT)) { + LOG.debug("EDIT is not supported."); + return false; + } + + LOG.info("Trying to use Desktop.getDesktop().edit() with " + file); + java.awt.Desktop.getDesktop().edit(file); + + return true; + } catch (Throwable t) { + LOG.error("Error using desktop edit.", t); + return false; + } + } + + + private static boolean runCommand(String command, String args, String file) { + + LOG.info("Trying to exec:\n cmd = " + command + "\n args = " + args + "\n %s = " + file); + + String[] parts = prepareCommand(command, args, file); + + try { + Process p = Runtime.getRuntime().exec(parts); + if (p == null) { + return false; + } + + try { + int retval = p.exitValue(); + if (retval == 0) { + LOG.error("Process ended immediately."); + return false; + } else { + LOG.error("Process crashed."); + return false; + } + } catch (IllegalThreadStateException itse) { + LOG.error("Process is running."); + return true; + } + } catch (IOException e) { + LOG.error("Error running command.", e); + return false; + } + } + + + private static String[] prepareCommand(String command, String args, String file) { + + List parts = new ArrayList<>(); + parts.add(command); + + if (args != null) { + for (String s : args.split(" ")) { + s = String.format(s, file); // put in the filename thing + + parts.add(s.trim()); + } + } + + return parts.toArray(new String[parts.size()]); + } + + private static boolean isXDG() { + String xdgSessionId = System.getenv("XDG_SESSION_ID"); + return xdgSessionId != null && !xdgSessionId.isEmpty(); + } + + private static boolean isGNOME() { + String gdmSession = System.getenv("GDMSESSION"); + return gdmSession != null && gdmSession.toLowerCase().contains("gnome"); + } + + private static boolean isKDE() { + String gdmSession = System.getenv("GDMSESSION"); + return gdmSession != null && gdmSession.toLowerCase().contains("kde"); + } + + private Desktop() { + } +} \ No newline at end of file From fa5d2c5aa2cdcc580486f81fde3ae69e9d3069e5 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 14:34:46 -0700 Subject: [PATCH 125/127] fix: sign in --- .../auth/ContinueAuthService.kt | 2 +- .../utils/Desktop.kt | 271 ++++++++---------- 2 files changed, 113 insertions(+), 160 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt index cd44d3e3b..da775da36 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt @@ -2,7 +2,7 @@ package com.github.continuedev.continueintellijextension.auth import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService -import com.github.continuedev.continueintellijextension.utils. +import com.github.continuedev.continueintellijextension.utils.Desktop import com.google.gson.Gson import com.intellij.credentialStore.Credentials import com.intellij.ide.passwordSafe.PasswordSafe diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt index 152a8630b..8dd20536c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/utils/Desktop.kt @@ -13,249 +13,202 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package com.github.continuedev.continueintellijextension.utils -//CHECKSTYLE:OFF -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; +import org.apache.commons.lang3.SystemUtils +import org.slf4j.LoggerFactory +import java.io.File +import java.io.IOException +import java.net.URI -import org.apache.commons.lang3.SystemUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * @author jjYBdx4IL - */ -public class Desktop { - - private static final Logger LOG = LoggerFactory.getLogger(Desktop.class); - - public static boolean browse(URI uri) { +object Desktop { + private val LOG = LoggerFactory.getLogger(Desktop::class.java) + fun browse(uri: URI): Boolean { if (browseDESKTOP(uri)) { - return true; + return true } if (openSystemSpecific(uri.toString())) { - return true; + return true } - LOG.warn(String.format("failed to browse %s", uri)); - - return false; + LOG.warn("failed to browse {}", uri) + return false } - - public static boolean open(File file) { - + fun open(file: File): Boolean { if (openDESKTOP(file)) { - return true; + return true } - if (openSystemSpecific(file.getPath())) { - return true; + if (openSystemSpecific(file.path)) { + return true } - LOG.warn(String.format("failed to open %s", file.getAbsolutePath())); - - return false; + LOG.warn("failed to open {}", file.absolutePath) + return false } - - public static boolean edit(File file) { - + fun edit(file: File): Boolean { if (editDESKTOP(file)) { - return true; + return true } - if (openSystemSpecific(file.getPath())) { - return true; + if (openSystemSpecific(file.path)) { + return true } - LOG.warn(String.format("failed to edit %s", file.getAbsolutePath())); - - return false; + LOG.warn("failed to edit {}", file.absolutePath) + return false } - - private static boolean openSystemSpecific(String what) { - + private fun openSystemSpecific(what: String): Boolean { if (SystemUtils.IS_OS_LINUX) { - if (isXDG()) { - if (runCommand("xdg-open", "%s", what)) { - return true; - } + if (isXDG() && runCommand("xdg-open", "%s", what)) { + return true } - if (isKDE()) { - if (runCommand("kde-open", "%s", what)) { - return true; - } + if (isKDE() && runCommand("kde-open", "%s", what)) { + return true } - if (isGNOME()) { - if (runCommand("gnome-open", "%s", what)) { - return true; - } + if (isGNOME() && runCommand("gnome-open", "%s", what)) { + return true } if (runCommand("kde-open", "%s", what)) { - return true; + return true } if (runCommand("gnome-open", "%s", what)) { - return true; + return true } } - if (SystemUtils.IS_OS_MAC) { - if (runCommand("open", "%s", what)) { - return true; - } + if (SystemUtils.IS_OS_MAC && runCommand("open", "%s", what)) { + return true } - if (SystemUtils.IS_OS_WINDOWS) { - if (runCommand("explorer", "%s", what)) { - return true; - } + if (SystemUtils.IS_OS_WINDOWS && runCommand("explorer", "%s", what)) { + return true } - return false; + return false } - - private static boolean browseDESKTOP(URI uri) { - - try { + private fun browseDESKTOP(uri: URI): Boolean { + return try { if (!java.awt.Desktop.isDesktopSupported()) { - LOG.debug("Platform is not supported."); - return false; + LOG.debug("Platform is not supported.") + return false } if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.BROWSE)) { - LOG.debug("BROWSE is not supported."); - return false; + LOG.debug("BROWSE is not supported.") + return false } - LOG.info("Trying to use Desktop.getDesktop().browse() with " + uri.toString()); - java.awt.Desktop.getDesktop().browse(uri); - - return true; - } catch (Throwable t) { - LOG.error("Error using desktop browse.", t); - return false; + LOG.info("Trying to use Desktop.getDesktop().browse() with {}", uri.toString()) + java.awt.Desktop.getDesktop().browse(uri) + true + } catch (t: Throwable) { + LOG.error("Error using desktop browse.", t) + false } } - - private static boolean openDESKTOP(File file) { - try { + private fun openDESKTOP(file: File): Boolean { + return try { if (!java.awt.Desktop.isDesktopSupported()) { - LOG.debug("Platform is not supported."); - return false; + LOG.debug("Platform is not supported.") + return false } if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.OPEN)) { - LOG.debug("OPEN is not supported."); - return false; + LOG.debug("OPEN is not supported.") + return false } - LOG.info("Trying to use Desktop.getDesktop().open() with " + file.toString()); - java.awt.Desktop.getDesktop().open(file); - - return true; - } catch (Throwable t) { - LOG.error("Error using desktop open.", t); - return false; + LOG.info("Trying to use Desktop.getDesktop().open() with {}", file.toString()) + java.awt.Desktop.getDesktop().open(file) + true + } catch (t: Throwable) { + LOG.error("Error using desktop open.", t) + false } } - - private static boolean editDESKTOP(File file) { - try { + private fun editDESKTOP(file: File): Boolean { + return try { if (!java.awt.Desktop.isDesktopSupported()) { - LOG.debug("Platform is not supported."); - return false; + LOG.debug("Platform is not supported.") + return false } if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.EDIT)) { - LOG.debug("EDIT is not supported."); - return false; + LOG.debug("EDIT is not supported.") + return false } - LOG.info("Trying to use Desktop.getDesktop().edit() with " + file); - java.awt.Desktop.getDesktop().edit(file); - - return true; - } catch (Throwable t) { - LOG.error("Error using desktop edit.", t); - return false; + LOG.info("Trying to use Desktop.getDesktop().edit() with {}", file) + java.awt.Desktop.getDesktop().edit(file) + true + } catch (t: Throwable) { + LOG.error("Error using desktop edit.", t) + false } } + private fun runCommand(command: String, args: String, file: String): Boolean { + LOG.info("Trying to exec:\n cmd = {}\n args = {}\n %s = {}", command, args, file) - private static boolean runCommand(String command, String args, String file) { + val parts = prepareCommand(command, args, file) - LOG.info("Trying to exec:\n cmd = " + command + "\n args = " + args + "\n %s = " + file); - - String[] parts = prepareCommand(command, args, file); - - try { - Process p = Runtime.getRuntime().exec(parts); + return try { + val p = Runtime.getRuntime().exec(parts) if (p == null) { - return false; - } - - try { - int retval = p.exitValue(); - if (retval == 0) { - LOG.error("Process ended immediately."); - return false; - } else { - LOG.error("Process crashed."); - return false; + false + } else { + try { + val retval = p.exitValue() + if (retval == 0) { + LOG.error("Process ended immediately.") + false + } else { + LOG.error("Process crashed.") + false + } + } catch (itse: IllegalThreadStateException) { + LOG.error("Process is running.") + true } - } catch (IllegalThreadStateException itse) { - LOG.error("Process is running."); - return true; } - } catch (IOException e) { - LOG.error("Error running command.", e); - return false; + } catch (e: IOException) { + LOG.error("Error running command.", e) + false } } + private fun prepareCommand(command: String, args: String?, file: String): Array { + val parts = mutableListOf() + parts.add(command) - private static String[] prepareCommand(String command, String args, String file) { - - List parts = new ArrayList<>(); - parts.add(command); - - if (args != null) { - for (String s : args.split(" ")) { - s = String.format(s, file); // put in the filename thing - - parts.add(s.trim()); - } + args?.split(" ")?.forEach { s -> + parts.add(String.format(s, file).trim()) } - return parts.toArray(new String[parts.size()]); + return parts.toTypedArray() } - private static boolean isXDG() { - String xdgSessionId = System.getenv("XDG_SESSION_ID"); - return xdgSessionId != null && !xdgSessionId.isEmpty(); + private fun isXDG(): Boolean { + val xdgSessionId = System.getenv("XDG_SESSION_ID") + return !xdgSessionId.isNullOrEmpty() } - private static boolean isGNOME() { - String gdmSession = System.getenv("GDMSESSION"); - return gdmSession != null && gdmSession.toLowerCase().contains("gnome"); + private fun isGNOME(): Boolean { + val gdmSession = System.getenv("GDMSESSION") + return gdmSession?.lowercase()?.contains("gnome") == true } - private static boolean isKDE() { - String gdmSession = System.getenv("GDMSESSION"); - return gdmSession != null && gdmSession.toLowerCase().contains("kde"); - } - - private Desktop() { + private fun isKDE(): Boolean { + val gdmSession = System.getenv("GDMSESSION") + return gdmSession?.lowercase()?.contains("kde") == true } } \ No newline at end of file From 7a11446bfc5d4cb9c05f64f1377518456d30f530 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 14:37:57 -0700 Subject: [PATCH 126/127] fix: Desktop.browse on linux --- .../continueintellijextension/auth/ContinueAuthService.kt | 1 - .../continueintellijextension/continue/IntelliJIde.kt | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt index da775da36..f65404dcd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt @@ -153,7 +153,6 @@ class ContinueAuthService { ) { response -> val authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String if (authUrl != null) { - // Open the auth URL in the browser Desktop.browse(java.net.URI(authUrl)) } } 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 796b3aac6..4c5aac0b8 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 @@ -6,6 +6,7 @@ import com.github.continuedev.continueintellijextension.utils.OS import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID import com.github.continuedev.continueintellijextension.utils.getOS import com.github.continuedev.continueintellijextension.utils.toUriOrNull +import com.github.continuedev.continueintellijextension.utils.Desktop import com.google.gson.Gson import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine @@ -36,7 +37,6 @@ import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody -import java.awt.Desktop import java.awt.Toolkit import java.awt.datatransfer.DataFlavor import java.io.BufferedReader @@ -239,7 +239,7 @@ class IntelliJIDE( override suspend fun openUrl(url: String) { withContext(Dispatchers.IO) { - Desktop.getDesktop().browse(URI(url)) + Desktop.browse(java.net.URI(URI(url)) } } From 72b253d14faf2d19832b0307fb4fba1e9aed11dd Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 11 Mar 2025 14:43:54 -0700 Subject: [PATCH 127/127] fix: types --- .../continueintellijextension/continue/IntelliJIde.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 4c5aac0b8..ade988875 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 @@ -239,7 +239,7 @@ class IntelliJIDE( override suspend fun openUrl(url: String) { withContext(Dispatchers.IO) { - Desktop.browse(java.net.URI(URI(url)) + Desktop.browse(java.net.URI(url)) } }