diff --git a/.gitignore b/.gitignore index 106cef892..9621811de 100644 --- a/.gitignore +++ b/.gitignore @@ -142,7 +142,7 @@ codeql .tiktoken_cache -# IntelliJ Plugin +# IntelliJ Plugin **/**/.gradle **/**/.qodana **/**/build @@ -168,4 +168,6 @@ extensions/intellij/.idea/** **/.idea/shelf/ extensions/intellij/bin -extensions/.continue-debug/ \ No newline at end of file +extensions/.continue-debug/ + +*.vsix \ No newline at end of file diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..d59df2ef6 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +npx prettier --write . \ No newline at end of file diff --git a/.prettierignore b/.prettierignore index db326191f..15619929d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,4 +1,17 @@ +binary/bin +binary/build +binary/out +binary/tmp +core/.continue-test +docs/.docusaurus +extensions/.continue-debug extensions/vscode/continue_rc_schema.json +extensions/vscode/.vscode-test +extensions/vscode/bin +extensions/vscode/build +extensions/vscode/out +gui/dist **/.continueignore CHANGELOG.md **/continue_tutorial.py +**/node_modules \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 4a982ecff..22d8d3287 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -20,6 +20,7 @@ "binary/build/**": true, "binary/out/**": true, "binary/tmp/**": true, + "core/edit/lazy/test-examples/**": true, "core/llm/llamaTokenizer.js": true, "core/llm/llamaTokenizer.mjs": true, "core/vendor/**": true, diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 9667352fd..3cc1ce65c 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -6,7 +6,7 @@ import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; -import { constructAutocompletePrompt } from "./constructPrompt.js"; +import { aggregateSnippets } from "./aggregateSnippets"; // @prettier-ignore import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; @@ -29,6 +29,7 @@ const autocompleteCache = AutocompleteLruCache.get(); const ERRORS_TO_IGNORE = [ // From Ollama "unexpected server status", + "operation was aborted" ]; export type GetLspDefinitionsFunction = ( @@ -176,17 +177,18 @@ export class CompletionProvider { // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); - let snippets = await constructAutocompletePrompt( - helper, - extraSnippets, - this.contextRetrievalService, - ); + const [snippets, diff, workspaceDirs] = await Promise.all([ + aggregateSnippets(helper, extraSnippets, this.contextRetrievalService), + this.ide.getDiff(true), + this.ide.getWorkspaceDirs(), + ]); - const { prompt, prefix, suffix, completionOptions } = renderPrompt( + const { prompt, prefix, suffix, completionOptions } = renderPrompt({ snippets, - await this.ide.getWorkspaceDirs(), + diff, + workspaceDirs, helper, - ); + }); // Completion let completion: string | undefined = ""; diff --git a/core/autocomplete/aggregateSnippets.ts b/core/autocomplete/aggregateSnippets.ts new file mode 100644 index 000000000..f47b9021f --- /dev/null +++ b/core/autocomplete/aggregateSnippets.ts @@ -0,0 +1,45 @@ +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; +import { + fillPromptWithSnippets, + rankAndOrderSnippets, + type AutocompleteSnippet, +} from "./context/ranking/index.js"; +import { HelperVars } from "./util/HelperVars.js"; + +function filterSnippetsAlreadyInCaretWindow( + snippets: AutocompleteSnippet[], + caretWindow: string, +): AutocompleteSnippet[] { + return snippets + .map((snippet) => ({ ...snippet })) + .filter( + (s) => + s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), + ); +} + +export async function aggregateSnippets( + helper: HelperVars, + extraSnippets: AutocompleteSnippet[], + contextRetrievalService: ContextRetrievalService, +): Promise { + let snippets = await contextRetrievalService.retrieveCandidateSnippets( + helper, + extraSnippets, + ); + + snippets = filterSnippetsAlreadyInCaretWindow( + snippets, + helper.prunedCaretWindow, + ); + + const scoredSnippets = rankAndOrderSnippets(snippets, helper); + + const finalSnippets = fillPromptWithSnippets( + scoredSnippets, + helper.maxSnippetTokens, + helper.modelName, + ); + + return finalSnippets; +} diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts deleted file mode 100644 index f15b1c4e1..000000000 --- a/core/autocomplete/constructPrompt.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { Position, Range } from "../index.js"; - -import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; -import { - fillPromptWithSnippets, - rankAndOrderSnippets, - removeRangeFromSnippets, - type AutocompleteSnippet, -} from "./context/ranking/index.js"; -import { HelperVars } from "./util/HelperVars.js"; - -function filterSnippetsAlreadyInCaretWindow( - snippets: AutocompleteSnippet[], - caretWindow: string, -): AutocompleteSnippet[] { - return snippets - .map((snippet) => ({ ...snippet })) - .filter( - (s) => - s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), - ); -} - -function getRangeOfPrefixAndSuffixWithBuffer( - prefix: string, - suffix: string, - caretPos: Position, -): Range { - // Remove prefix range from snippets - const prefixLines = prefix.split("\n").length; - const suffixLines = suffix.split("\n").length; - const buffer = 8; - const prefixSuffixRangeWithBuffer = { - start: { - line: caretPos.line - prefixLines - buffer, - character: 0, - }, - end: { - line: caretPos.line + suffixLines + buffer, - character: 0, - }, - }; - - return prefixSuffixRangeWithBuffer; -} - -export async function constructAutocompletePrompt( - helper: HelperVars, - extraSnippets: AutocompleteSnippet[], - contextRetrievalService: ContextRetrievalService, -): Promise { - let snippets = await contextRetrievalService.retrieveCandidateSnippets( - helper, - extraSnippets, - ); - - snippets = filterSnippetsAlreadyInCaretWindow( - snippets, - helper.prunedCaretWindow, - ); - - const scoredSnippets = rankAndOrderSnippets(snippets, helper); - - // This might be redundant with filterSnippetsAlreadyInCaretWindow - let finalSnippets = removeRangeFromSnippets( - scoredSnippets, - helper.filepath.split("://").slice(-1)[0], - getRangeOfPrefixAndSuffixWithBuffer( - helper.prunedPrefix, - helper.prunedSuffix, - helper.pos, - ), - ); - - // Filter snippets below similarity threshold - finalSnippets = finalSnippets.filter( - (snippet) => - snippet.score >= helper.options.recentlyEditedSimilarityThreshold, - ); - - finalSnippets = fillPromptWithSnippets( - scoredSnippets, - helper.maxSnippetTokens, - helper.modelName, - ); - - return finalSnippets; -} diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index e761d994e..3e83afca5 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -153,24 +153,6 @@ export function fillPromptWithSnippets( return keptSnippets; } -function rangeIntersectionByLines(a: Range, b: Range): Range | null { - const startLine = Math.max(a.start.line, b.start.line); - const endLine = Math.min(a.end.line, b.end.line); - if (startLine >= endLine) { - return null; - } - return { - start: { - line: startLine, - character: 0, - }, - end: { - line: endLine, - character: 0, - }, - }; -} - /** * Remove one range from another range, which may lead to returning two disjoint ranges */ @@ -225,31 +207,3 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { } return [orig]; } - -export function removeRangeFromSnippets( - snippets: Required[], - filepath: string, - range: Range, -): Required[] { - const finalSnippets: Required[] = []; - for (const snippet of snippets) { - if (snippet.filepath !== filepath) { - finalSnippets.push(snippet); - continue; - } - - const intersection = rangeIntersectionByLines(range, snippet.range); - if (!intersection) { - finalSnippets.push(snippet); - } else { - finalSnippets.push( - ...rangeDifferenceByLines(snippet.range, intersection).map((range) => ({ - ...snippet, - range, - })), - ); - } - } - - return finalSnippets; -} diff --git a/core/autocomplete/filtering/BracketMatchingService.ts b/core/autocomplete/filtering/BracketMatchingService.ts index d4415259e..da7d38e61 100644 --- a/core/autocomplete/filtering/BracketMatchingService.ts +++ b/core/autocomplete/filtering/BracketMatchingService.ts @@ -1,3 +1,13 @@ +export const BRACKETS: { [key: string]: string } = { + "(": ")", + "{": "}", + "[": "]", +}; +export const BRACKETS_REVERSE: { [key: string]: string } = { + ")": "(", + "}": "{", + "]": "[", +}; /** * We follow the policy of only completing bracket pairs that we started * But sometimes we started the pair in a previous autocomplete suggestion @@ -6,30 +16,18 @@ export class BracketMatchingService { private openingBracketsFromLastCompletion: string[] = []; private lastCompletionFile: string | undefined = undefined; - static BRACKETS: { [key: string]: string } = { "(": ")", "{": "}", "[": "]" }; - static BRACKETS_REVERSE: { [key: string]: string } = { - ")": "(", - "}": "{", - "]": "[", - }; - handleAcceptedCompletion(completion: string, filepath: string) { this.openingBracketsFromLastCompletion = []; const stack: string[] = []; for (let i = 0; i < completion.length; i++) { const char = completion[i]; - if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) { + if (Object.keys(BRACKETS).includes(char)) { // It's an opening bracket stack.push(char); - } else if ( - Object.values(BracketMatchingService.BRACKETS).includes(char) - ) { + } else if (Object.values(BRACKETS).includes(char)) { // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { + if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) { break; } } @@ -63,17 +61,12 @@ export class BracketMatchingService { (prefix.split("\n").pop() ?? "") + (suffix.split("\n")[0] ?? ""); for (let i = 0; i < currentLine.length; i++) { const char = currentLine[i]; - if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) { + if (Object.keys(BRACKETS).includes(char)) { // It's an opening bracket stack.push(char); - } else if ( - Object.values(BracketMatchingService.BRACKETS).includes(char) - ) { + } else if (Object.values(BRACKETS).includes(char)) { // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { + if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) { break; } } @@ -87,7 +80,7 @@ export class BracketMatchingService { if (suffix[i] === " ") { continue; } - const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]]; + const openBracket = BRACKETS_REVERSE[suffix[i]]; if (!openBracket) { break; } @@ -115,19 +108,14 @@ export class BracketMatchingService { const allLines = all.split("\n"); for (let i = 0; i < chunk.length; i++) { const char = chunk[i]; - if (Object.values(BracketMatchingService.BRACKETS).includes(char)) { + if (Object.values(BRACKETS).includes(char)) { // It's a closing bracket - if ( - stack.length === 0 || - BracketMatchingService.BRACKETS[stack.pop()!] !== char - ) { + if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) { // If the stack is empty or the top of the stack doesn't match the current closing bracket yield chunk.slice(0, i); return; // Stop the generator if the closing bracket doesn't have a matching opening bracket in the stream } - } else if ( - Object.keys(BracketMatchingService.BRACKETS).includes(char) - ) { + } else if (Object.keys(BRACKETS).includes(char)) { // It's an opening bracket stack.push(char); } diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 5576ee26b..6097ff797 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -6,6 +6,7 @@ import { stopAtStopTokens } from "./charStream"; import { avoidEmptyComments, avoidPathLine, + noDoubleNewlineAfterClosingBracket, showWhateverWeHaveAtXMs, skipPrefixes, stopAtLines, @@ -47,6 +48,7 @@ export class StreamTransformPipeline { ); lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); lineGenerator = skipPrefixes(lineGenerator); + lineGenerator = noDoubleNewlineAfterClosingBracket(lineGenerator); for (const lineFilter of helper.lang.lineFilters ?? []) { lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 8c7936e2d..160fc9d85 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -2,6 +2,7 @@ import { distance } from "fastest-levenshtein"; import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; +import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService"; export type LineFilter = (args: { lines: LineStream; @@ -545,3 +546,43 @@ export async function* showWhateverWeHaveAtXMs( } } } + +export async function* noDoubleNewlineAfterClosingBracket( + lines: LineStream, +): LineStream { + const bracketTypeCounts = new Map(); + + for await (const line of lines) { + if (line.trim() === "") { + // Double newline detected + // Check if any bracket counts are negative + let hasNegativeCount = false; + for (const count of bracketTypeCounts.values()) { + if (count < 0) { + hasNegativeCount = true; + break; + } + } + if (hasNegativeCount) { + // Stop the generator if we've closed brackets we didn't open + return; + } + } + + yield line; + + // Update bracket counts + for (const char of line) { + if (BRACKETS[char]) { + // It's an opening bracket + const count = bracketTypeCounts.get(char) || 0; + bracketTypeCounts.set(char, count + 1); + } else if (BRACKETS_REVERSE[char]) { + // It's a closing bracket + const openingBracket = BRACKETS_REVERSE[char]; + const count = bracketTypeCounts.get(openingBracket) || 0; + bracketTypeCounts.set(openingBracket, count - 1); + } + } + } +} diff --git a/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts b/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts new file mode 100644 index 000000000..a25b5d4bf --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/noDoubleNewlineAfterClosingBracket.test.ts @@ -0,0 +1,166 @@ +import { noDoubleNewlineAfterClosingBracket } from "./lineStream"; + +describe("noDoubleNewlineAfterClosingBracket", () => { + // Helper function to convert an array to an async generator + async function* arrayToAsyncGenerator(array: T[]): AsyncGenerator { + for (const item of array) { + yield item; + } + } + + // Helper function to collect lines from the async generator + async function collectLines(lines: AsyncIterable): Promise { + const result: string[] = []; + for await (const line of lines) { + result.push(line); + } + return result; + } + + test("should yield all lines when no double newline and no unmatched brackets", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should yield all lines when double newline but brackets are matched", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + "", + "", + "// End of function", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should stop yielding after double newline when unmatched closing bracket is found before double newline", async () => { + const inputLines = [ + // "function test() {", + ' console.log("Hello World");', + // Unmatched closing bracket + "}", + "", + "", + "// This should not be yielded", + 'console.log("End");', + ]; + const expectedOutputLines = [' console.log("Hello World");', "}"]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(expectedOutputLines); + }); + + test("should yield all lines when unmatched brackets but no double newline", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + // Unmatched closing bracket + ")", + "// Continue code", + 'console.log("End");', + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should continue yielding if unmatched closing bracket occurs after double newline", async () => { + const inputLines = [ + "function test() {", + ' console.log("Hello World");', + "}", + "", + "", + // Unmatched closing bracket after double newline + ")", + 'console.log("End");', + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should yield all lines when brackets are matched even with double newline", async () => { + const inputLines = [ + "const arr = [", + " 1, 2, 3,", + "];", + "", + "", + "console.log(arr);", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); + + test("should stop yielding when unmatched closing bracket occurs before double newline", async () => { + const inputLines = [ + "if (condition) {", + " doSomething();", + "}", + // Unmatched closing bracket + "}", + "", + "", + "doSomethingElse();", + ]; + const expectedOutputLines = [ + "if (condition) {", + " doSomething();", + "}", + "}", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(expectedOutputLines); + }); + + test("should yield all lines when no unmatched closing brackets and double newline", async () => { + const inputLines = [ + "while (true) {", + " // Infinite loop", + "}", + "", + "", + "// Loop exited", + ]; + const lines = arrayToAsyncGenerator(inputLines); + const outputLines = await collectLines( + noDoubleNewlineAfterClosingBracket(lines), + ); + + expect(outputLines).toEqual(inputLines); + }); +}); diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index 406faf66f..f0584ab48 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -63,7 +63,7 @@ function sayHello() { `, llmOutput: `world!"); `, - expectedCompletion: "world!\");", + expectedCompletion: 'world!");', }, { description: "Should autocomplete Java when inside a block", @@ -131,10 +131,6 @@ public class Calculator { } `, expectedCompletion: ` - } - - public void subtract(double number) { - result -= number; }`, }, { @@ -489,8 +485,8 @@ echo calculateArea(5, 3);`, $colors = array("Red", "Green", <|fim|>); echo "First color is: " . $colors[0];`, - llmOutput: "\"Blue\"", - expectedCompletion: "\"Blue\"", + llmOutput: '"Blue"', + expectedCompletion: '"Blue"', filename: "colors.php", }, { @@ -775,8 +771,10 @@ func main() { FROM users u WHERE u.active = 1 <|fim|>`, - llmOutput: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", - expectedCompletion: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", + llmOutput: + " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", + expectedCompletion: + " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", }, { description: @@ -817,8 +815,8 @@ func main() {

Description text.

`, - llmOutput: "alt=\"Description of image\"", - expectedCompletion: "alt=\"Description of image\"", + llmOutput: 'alt="Description of image"', + expectedCompletion: 'alt="Description of image"', filename: "test.html", }, { @@ -930,8 +928,8 @@ public class App { <|fim|> ] }`, - llmOutput: ", { \"id\": 3, \"name\": \"Charlie\" }", - expectedCompletion: ", { \"id\": 3, \"name\": \"Charlie\" }", + llmOutput: ', { "id": 3, "name": "Charlie" }', + expectedCompletion: ', { "id": 3, "name": "Charlie" }', }, { description: "Should autocomplete within a CSV record", @@ -1237,8 +1235,8 @@ class Counter { :age 30 <|fim|> (println "User information loaded"))`, - llmOutput: ":location \"Unknown\"}", - expectedCompletion: ":location \"Unknown\"}", + llmOutput: ':location "Unknown"}', + expectedCompletion: ':location "Unknown"}', filename: "test.clj", }, { @@ -1301,8 +1299,8 @@ if (grade >= 90) { } else { print("C") }`, - llmOutput: "print(\"B\")", - expectedCompletion: "print(\"B\")", + llmOutput: 'print("B")', + expectedCompletion: 'print("B")', }, { description: "Should autocomplete R ggplot2 plot structure", @@ -1324,8 +1322,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) + <|fim|> } }`, - llmOutput: "s\"Hello, my name is $name and I am $age years old.\"", - expectedCompletion: "s\"Hello, my name is $name and I am $age years old.\"", + llmOutput: 's"Hello, my name is $name and I am $age years old."', + expectedCompletion: 's"Hello, my name is $name and I am $age years old."', }, { @@ -1335,8 +1333,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) + case class Person(name: String, age: Int, address: Address) val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`, - llmOutput: "\"12345\")", - expectedCompletion: "\"12345\")", + llmOutput: '"12345")', + expectedCompletion: '"12345")', }, { @@ -2066,8 +2064,8 @@ export default { /> `, - llmOutput: "name=\"World\"", - expectedCompletion: "name=\"World\"", + llmOutput: 'name="World"', + expectedCompletion: 'name="World"', }, { diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index f516ad04b..d44957d15 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -25,10 +25,10 @@ export class CompletionStreamer { // Try to reuse pending requests if what the user typed matches start of completion const generator = this.generatorReuseManager.getGenerator( prefix, - () => + (abortSignal: AbortSignal) => llm.supportsFim() - ? llm.streamFim(prefix, suffix, completionOptions) - : llm.streamComplete(prompt, { + ? llm.streamFim(prefix, suffix, abortSignal, completionOptions) + : llm.streamComplete(prompt, abortSignal, { ...completionOptions, raw: true, }), diff --git a/core/autocomplete/generation/GeneratorReuseManager.test.ts b/core/autocomplete/generation/GeneratorReuseManager.test.ts new file mode 100644 index 000000000..039059903 --- /dev/null +++ b/core/autocomplete/generation/GeneratorReuseManager.test.ts @@ -0,0 +1,215 @@ +import { jest } from "@jest/globals"; +import { GeneratorReuseManager } from "./GeneratorReuseManager"; + +function createMockGenerator( + data: string[], + delay: number = 0, +): (abortSignal: AbortSignal) => AsyncGenerator { + const mockGenerator = async function* () { + for (const chunk of data) { + yield chunk; + + if (delay > 0) { + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + }; + const newGenerator = jest + .fn<() => AsyncGenerator>() + .mockReturnValue(mockGenerator()); + + return newGenerator; +} + +describe("GeneratorReuseManager", () => { + let reuseManager: GeneratorReuseManager; + let onErrorMock: jest.Mock; + + beforeEach(() => { + onErrorMock = jest.fn(); + reuseManager = new GeneratorReuseManager(onErrorMock); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + test("creates new generator when there is no current generator", async () => { + const data = ["hello ", "world"]; + const newGenerator = createMockGenerator(data); + + const prefix = ""; + + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(data); + expect(newGenerator).toHaveBeenCalledTimes(1); + }); + + test("reuses generator when prefix matches pending completion", async () => { + const newGenerator = createMockGenerator(["llo ", "world"]); + + // First call with initial prefix + const prefix1 = "he"; + const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true); + + const output1: string[] = []; + for await (const chunk of generator1) { + output1.push(chunk); + } + + expect(output1).toEqual(["llo ", "world"]); + + // Second call with extended prefix that matches pending completion + const prefix2 = "hello "; + const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true); + + const output2: string[] = []; + for await (const chunk of generator2) { + output2.push(chunk); + } + + expect(output2).toEqual(["world"]); + + // Ensure generator was reused (newGenerator should be called only once) + expect(newGenerator).toHaveBeenCalledTimes(1); + }); + + test("creates new generator when prefix does not match pending completion", async () => { + const data = ["goodbye ", "world"]; + const newGenerator = createMockGenerator(data); + + // Initial generator with different prefix + reuseManager.pendingGeneratorPrefix = "hello "; + reuseManager.pendingCompletion = "world"; + + const prefix = "good"; + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(data); + // Ensure a new generator was created + expect(newGenerator).toHaveBeenCalledTimes(1); + }); + + test("handles multiline=false by stopping at newline", async () => { + const data = ["first line\n", "second line"]; + const newGenerator = createMockGenerator(data); + + const prefix = ""; + const generator = reuseManager.getGenerator(prefix, newGenerator, false); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(["first line"]); + // Ensure it stops after the first newline + }); + + test("handles multiline=true by not stopping at newline", async () => { + const data = ["first line\n", "second line"]; + const newGenerator = createMockGenerator(data); + + const prefix = ""; + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + for await (const chunk of generator) { + output.push(chunk); + } + + expect(output).toEqual(data); + }); + + test("cancels previous generator when creating a new one", async () => { + const data1 = ["data from generator 1", "not generated"]; + const data2 = ["data from generator 2"]; + + const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it + const newGenerator2 = createMockGenerator(data2); + + const prefix1 = "prefix1"; + const prefix2 = "prefix2"; + + // First generator + const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); + const output1: string[] = []; + for await (const chunk of generator1) { + output1.push(chunk); + // Simulate the generator being canceled before completing + reuseManager.currentGenerator?.cancel(); + } + + expect(output1.length).toEqual(1); + expect(output1[0]).toEqual(data1[0]); + + // Second generator + const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); + const output2: string[] = []; + for await (const chunk of generator2) { + output2.push(chunk); + } + + expect(output2).toEqual(data2); + }); + + test("calls onError when generator throws an error", async () => { + const error = new Error("Generator error"); + const mockGenerator = async function* () { + throw error; + }; + const newGenerator = jest + .fn<() => AsyncGenerator>() + .mockReturnValue(mockGenerator()); + + const prefix = ""; + const generator = reuseManager.getGenerator(prefix, newGenerator, true); + + const output: string[] = []; + await expect(async () => { + for await (const chunk of generator) { + output.push(chunk); + } + }).not.toThrow(); // getGenerator handles errors internally + + expect(onErrorMock).toHaveBeenCalledWith(error); + expect(output).toEqual([]); + }); + + test("handles backspacing by creating new generator when prefix is shorter", async () => { + const data = ["hello world"]; + const newGenerator1 = createMockGenerator(data); + const newGenerator2 = createMockGenerator(data); + + // First prefix + const prefix1 = "hello world"; + const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); + const output1: string[] = []; + for await (const chunk of generator1) { + output1.push(chunk); + } + + // Simulate backspace (prefix is shorter) + const prefix2 = "hello worl"; + const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); + const output2: string[] = []; + for await (const chunk of generator2) { + output2.push(chunk); + } + + // Ensure a new generator was created + expect(newGenerator1).toHaveBeenCalledTimes(1); + expect(newGenerator2).toHaveBeenCalledTimes(1); + }); +}); diff --git a/core/autocomplete/generation/GeneratorReuseManager.ts b/core/autocomplete/generation/GeneratorReuseManager.ts index 7a67e686f..e099b92f4 100644 --- a/core/autocomplete/generation/GeneratorReuseManager.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.ts @@ -8,12 +8,13 @@ export class GeneratorReuseManager { constructor(private readonly onError: (err: any) => void) {} private _createListenableGenerator( + abortController: AbortController, gen: AsyncGenerator, prefix: string, ) { this.currentGenerator?.cancel(); - const listenableGen = new ListenableGenerator(gen, this.onError); + const listenableGen = new ListenableGenerator(gen, this.onError, abortController); listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? "")); this.pendingGeneratorPrefix = prefix; @@ -21,47 +22,55 @@ export class GeneratorReuseManager { this.currentGenerator = listenableGen; } + private shouldReuseExistingGenerator(prefix: string): boolean { + return ( + !!this.currentGenerator && + !!this.pendingGeneratorPrefix && + (this.pendingGeneratorPrefix + this.pendingCompletion).startsWith( + prefix, + ) && + // for e.g. backspace + this.pendingGeneratorPrefix?.length <= prefix?.length + ); + } + async *getGenerator( prefix: string, - newGenerator: () => AsyncGenerator, + newGenerator: (abortSignal: AbortSignal) => AsyncGenerator, multiline: boolean, ): AsyncGenerator { - // Check if current can be reused - if ( - !( - this.currentGenerator && - this.pendingGeneratorPrefix && - (this.pendingGeneratorPrefix + this.pendingCompletion).startsWith( - prefix, - ) && - // for e.g. backspace - this.pendingGeneratorPrefix?.length <= prefix?.length - ) - ) { + // If we can't reuse, then create a new generator + if (!this.shouldReuseExistingGenerator(prefix)) { // Create a wrapper over the current generator to fix the prompt - this._createListenableGenerator(newGenerator(), prefix); + const abortController = new AbortController(); + this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix); } - let alreadyTyped = prefix.slice(this.pendingGeneratorPrefix?.length) || ""; + // Already typed characters are those that are new in the prefix from the old generator + let typedSinceLastGenerator = + prefix.slice(this.pendingGeneratorPrefix?.length) || ""; for await (let chunk of this.currentGenerator?.tee() ?? []) { if (!chunk) { continue; } - while (chunk.length && alreadyTyped.length) { - if (chunk[0] === alreadyTyped[0]) { - alreadyTyped = alreadyTyped.slice(1); + + // Ignore already typed characters in the completion + while (chunk.length && typedSinceLastGenerator.length) { + if (chunk[0] === typedSinceLastGenerator[0]) { + typedSinceLastGenerator = typedSinceLastGenerator.slice(1); chunk = chunk.slice(1); } else { break; } } + // Break at newline unless we are in multiline mode const newLineIndex = chunk.indexOf("\n"); - if (multiline || newLineIndex === -1) { - yield chunk; - } else { + if (newLineIndex >= 0 && !multiline) { yield chunk.slice(0, newLineIndex); break; + } else if (chunk !== "") { + yield chunk; } } } diff --git a/core/autocomplete/generation/ListenableGenerator.test.ts b/core/autocomplete/generation/ListenableGenerator.test.ts new file mode 100644 index 000000000..69797959e --- /dev/null +++ b/core/autocomplete/generation/ListenableGenerator.test.ts @@ -0,0 +1,149 @@ +import { jest } from "@jest/globals"; +import { ListenableGenerator } from "./ListenableGenerator"; + +describe("ListenableGenerator", () => { + // Helper function to create an async generator + async function* asyncGenerator(values: T[], delay = 0) { + for (const value of values) { + if (delay > 0) { + await new Promise((resolve) => setTimeout(resolve, delay)); + } + yield value; + } + } + + it("should yield values from the source generator via tee()", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const result: number[] = []; + for await (const value of lg.tee()) { + result.push(value); + } + + expect(result).toEqual(values); + expect(onError).not.toHaveBeenCalled(); + }); + + it("should allow listeners to receive values", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const listener = jest.fn(); + + // Add listener after some delay to simulate late subscription + setTimeout(() => { + lg.listen(listener); + }, 15); + + // Wait for generator to finish + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect(listener).toHaveBeenCalledWith(1); + expect(listener).toHaveBeenCalledWith(2); + expect(listener).toHaveBeenCalledWith(3); + // Listener should receive null at the end + expect(listener).toHaveBeenCalledWith(null); + }); + + it("should buffer values for listeners added after some values have been yielded", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values, 10); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const initialListener = jest.fn(); + + lg.listen(initialListener); + + // Wait for the first value to be yielded + await new Promise((resolve) => setTimeout(resolve, 15)); + + // Add a second listener + const newListener = jest.fn(); + lg.listen(newListener); + + // Wait for generator to finish + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Both listeners should have received all values + [initialListener, newListener].forEach((listener) => { + expect(listener).toHaveBeenCalledWith(1); + expect(listener).toHaveBeenCalledWith(2); + expect(listener).toHaveBeenCalledWith(3); + expect(listener).toHaveBeenCalledWith(null); + }); + }); + + it("should handle cancellation", async () => { + const values = [1, 2, 3, 4, 5]; + const source = asyncGenerator(values, 10); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const result: number[] = []; + const teeIterator = lg.tee(); + + const consume = async () => { + for await (const value of teeIterator) { + result.push(value); + if (value === 3) { + lg.cancel(); + } + } + }; + + await consume(); + + expect(result).toEqual([1, 2, 3]); + expect(lg["_isEnded"]).toBe(true); + }); + + it("should call onError when the source generator throws an error", async () => { + async function* errorGenerator() { + yield 1; + throw new Error("Test error"); + } + + const source = errorGenerator(); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const result: number[] = []; + for await (const value of lg.tee()) { + result.push(value); + } + + expect(result).toEqual([1]); + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(new Error("Test error")); + }); + + it("should notify listeners when the generator ends", async () => { + const values = [1, 2, 3]; + const source = asyncGenerator(values); + const onError = jest.fn(); + + const lg = new ListenableGenerator(source, onError); + + const listener = jest.fn(); + lg.listen(listener); + + // Wait for the generator to finish + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(listener).toHaveBeenCalledWith(1); + expect(listener).toHaveBeenCalledWith(2); + expect(listener).toHaveBeenCalledWith(3); + expect(listener).toHaveBeenCalledWith(null); + }); +}); diff --git a/core/autocomplete/generation/ListenableGenerator.ts b/core/autocomplete/generation/ListenableGenerator.ts index 0cc9f664e..e6b36019b 100644 --- a/core/autocomplete/generation/ListenableGenerator.ts +++ b/core/autocomplete/generation/ListenableGenerator.ts @@ -3,16 +3,20 @@ export class ListenableGenerator { private _buffer: T[] = []; private _listeners: Set<(value: T) => void> = new Set(); private _isEnded = false; + private _abortController: AbortController constructor( source: AsyncGenerator, private readonly onError: (e: any) => void, + abortController: AbortController ) { this._source = source; + this._abortController = abortController; this._start(); } public cancel() { + this._abortController.abort(); this._isEnded = true; } diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index bc3b3bcaa..40ffa5384 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -1,5 +1,7 @@ import path from "node:path"; +import ignore from "ignore"; + import { IDE } from "../.."; import { getBasename } from "../../util"; import { getConfigJsonPath } from "../../util/paths"; @@ -31,7 +33,7 @@ async function isDisabledForFile( } // @ts-ignore - const pattern = ignore.default().add(options.disableInFiles); + const pattern = ignore.default().add(disableInFiles); if (pattern.ignores(filepath)) { return true; } diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 87bc7cfd9..f847e3b2a 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -11,6 +11,7 @@ import { getTemplateForModel, } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; +import { countTokens } from "../../llm/countTokens"; export function formatExternalSnippet( filepath: string, @@ -28,42 +29,22 @@ export function formatExternalSnippet( ]; return lines.join("\n"); } -function renderStringTemplate( - template: string, - prefix: string, - suffix: string, + +function getContextComments( snippets: AutocompleteSnippet[], lang: AutocompleteLanguageInfo, filepath: string, - reponame: string, ) { - const filename = getBasename(filepath); - const compiledTemplate = Handlebars.compile(template); + const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`; - // Format snippets as comments and prepend to prefix - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - prefix = `${formattedSnippets}\n\n${prefix}`; - } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { - // If it's an empty file, include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts( - filepath, - 2, - )}\n${prefix}`; - } + const formattedSnippets = + snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n") + fileNameSnippet; - const prompt = compiledTemplate({ - prefix, - suffix, - filename, - reponame, - language: lang.name, - }); - return prompt; + return formattedSnippets; } function getTemplate(helper: HelperVars): AutocompleteTemplate { @@ -77,29 +58,61 @@ function getTemplate(helper: HelperVars): AutocompleteTemplate { return getTemplateForModel(helper.modelName); } -export function renderPrompt( - snippets: AutocompleteSnippet[], - workspaceDirs: string[], - helper: HelperVars, -): { +function renderStringTemplate( + template: string, + prefix: string, + suffix: string, + lang: AutocompleteLanguageInfo, + filepath: string, + reponame: string, +) { + const filename = getBasename(filepath); + const compiledTemplate = Handlebars.compile(template); + + return compiledTemplate({ + prefix, + suffix, + filename, + reponame, + language: lang.name, + }); +} + +const formatDiff = (helper: HelperVars, diff?: string) => { + if (!diff) return ""; + + const tokenCount = countTokens(diff, helper.modelName); + + if (tokenCount > helper.maxDiffTokens) { + return ""; + } + + return `${diff}\n\n`; +}; + +export function renderPrompt({ + snippets, + workspaceDirs, + helper, + diff, +}: { + snippets: AutocompleteSnippet[]; + workspaceDirs: string[]; + helper: HelperVars; + diff?: string; +}): { prompt: string; prefix: string; suffix: string; completionOptions: Partial | undefined; } { // If prefix is manually passed - let prefix = helper.prunedPrefix; - let suffix = helper.prunedSuffix; + let prefix = helper.input.manuallyPassPrefix || helper.prunedPrefix; + let suffix = helper.input.manuallyPassPrefix ? "" : helper.prunedSuffix; - if (helper.input.manuallyPassPrefix) { - prefix = helper.input.manuallyPassPrefix; - suffix = ""; - } - - let prompt: string; const reponame = getBasename(workspaceDirs[0] ?? "myproject"); - let { template, compilePrefixSuffix, completionOptions } = + const { template, compilePrefixSuffix, completionOptions } = getTemplate(helper); // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix @@ -112,40 +125,50 @@ export function renderPrompt( reponame, snippets, ); - } - - // Templates can be passed as a Handlebars template string or a function - if (typeof template === "string") { - prompt = renderStringTemplate( - template, - prefix, - suffix, + } else { + const contextComments = getContextComments( snippets, helper.lang, helper.filepath, - reponame, - ); - } else { - prompt = template( - prefix, - suffix, - helper.filepath, - reponame, - helper.lang.name, - snippets, ); + const formattedDiff = formatDiff(helper, diff); + + prefix = `${formattedDiff}${contextComments}${prefix}`; } + const prompt = + // Templates can be passed as a Handlebars template string or a function + typeof template === "string" + ? renderStringTemplate( + template, + prefix, + suffix, + helper.lang, + helper.filepath, + reponame, + ) + : template( + prefix, + suffix, + helper.filepath, + reponame, + helper.lang.name, + snippets, + ); + const stopTokens = getStopTokens( completionOptions, helper.lang, helper.modelName, ); - completionOptions = { - ...completionOptions, - stop: stopTokens, + return { + prompt, + prefix, + suffix, + completionOptions: { + ...completionOptions, + stop: stopTokens, + }, }; - - return { prompt, prefix, suffix, completionOptions }; } diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index 2d9f74ab5..190e9b8ec 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -39,7 +39,9 @@ export class HelperVars { private async init() { // Don't do anything if already initialized - if (this._fileContents !== undefined) {return;} + if (this._fileContents !== undefined) { + return; + } this._fileContents = this.input.manuallyPassFileContents ?? @@ -115,6 +117,11 @@ export class HelperVars { get maxSnippetTokens() { return this.options.maxPromptTokens * this.options.maxSnippetPercentage; } + + get maxDiffTokens() { + return this.options.maxPromptTokens * this.options.maxDiffPercentage; + } + get prunedCaretWindow() { return this.prunedPrefix + this.prunedSuffix; } diff --git a/core/commands/index.ts b/core/commands/index.ts index 806e918db..cb5e162f7 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -58,7 +58,7 @@ export function slashFromCustomCommand( } } - for await (const chunk of llm.streamChat(messages)) { + for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/cmd.ts b/core/commands/slash/cmd.ts index 00ba5b0de..1c3968172 100644 --- a/core/commands/slash/cmd.ts +++ b/core/commands/slash/cmd.ts @@ -24,7 +24,9 @@ const GenerateTerminalCommand: SlashCommand = { "${input}" -Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`); +Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`, + new AbortController().signal + ); const lines = streamLines(gen); let cmd = ""; diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index 034e07e5e..7d5f22a90 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = { const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; for await (const chunk of llm.streamChat([ { role: "user", content: prompt }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 25da6b559..268c68384 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -30,7 +30,7 @@ const DraftIssueCommand: SlashCommand = { return; } let title = await llm.complete( - `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, + `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal, { maxTokens: 20 }, ); @@ -43,7 +43,7 @@ const DraftIssueCommand: SlashCommand = { { role: "user", content: PROMPT(input, title) }, ]; - for await (const chunk of llm.streamChat(messages)) { + for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { body += chunk.content; yield stripImages(chunk.content); } diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index fc71838df..78d86beee 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -478,7 +478,7 @@ const EditSlashCommand: SlashCommand = { messages = rendered; } - const completion = llm.streamComplete(rendered as string, { + const completion = llm.streamComplete(rendered as string, new AbortController().signal, { maxTokens: Math.min(maxTokens, Math.floor(llm.contextLength / 2), 4096), raw: true, }); @@ -494,7 +494,7 @@ const EditSlashCommand: SlashCommand = { ); } else { async function* gen() { - for await (const chunk of llm.streamChat(messages, { + for await (const chunk of llm.streamChat(messages, new AbortController().signal,{ temperature: 0.5, // TODO maxTokens: Math.min( maxTokens, @@ -609,7 +609,7 @@ ${lines.join("\n")} Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`; - for await (const update of llm.streamComplete(prompt)) { + for await (const update of llm.streamComplete(prompt, new AbortController().signal)) { yield update; } } diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts index 740243a5a..c8cf64679 100644 --- a/core/commands/slash/multifileEdit.ts +++ b/core/commands/slash/multifileEdit.ts @@ -39,7 +39,7 @@ const MultiFileEditSlashCommand: SlashCommand = { const content = createPrompt(filesToEditStr, additionalContextStr, input); - for await (const chunk of llm.streamChat([{ role: "user", content }])) { + for await (const chunk of llm.streamChat([{ role: "user", content }], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index 8d3433c25..4d8aa3a38 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -47,7 +47,7 @@ const OnboardSlashCommand: SlashCommand = { for await (const chunk of llm.streamChat([ { role: "user", content: prompt }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, @@ -134,7 +134,7 @@ function createOnboardingPrompt(context: string): string { Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole. Here is an example of a valid response: - + ## Important folders ### /folder1 diff --git a/core/commands/slash/review.ts b/core/commands/slash/review.ts index 34859d94c..77357647a 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/review.ts @@ -45,7 +45,7 @@ const ReviewMessageCommand: SlashCommand = { for await (const chunk of llm.streamChat([ { role: "user", content: content }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index aa19f3b0c..1ec963513 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -125,7 +125,7 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages)) { + for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } diff --git a/core/config/types.ts b/core/config/types.ts index ad80cdeab..370689dde 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -836,7 +836,7 @@ declare global { slidingWindowPrefixPercentage: number; slidingWindowSize: number; maxSnippetPercentage: number; - recentlyEditedSimilarityThreshold: number; + maxDiffPercentage: number; useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index ba2bf29b6..6eab55fa4 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -9,7 +9,6 @@ import { } from "../.."; import DocsService from "../../indexing/docs/DocsService"; import preIndexedDocs from "../../indexing/docs/preIndexedDocs"; -import { Telemetry } from "../../util/posthog"; import { INSTRUCTIONS_BASE_ITEM } from "./utils"; @@ -88,38 +87,10 @@ class DocsContextProvider extends BaseContextProvider { return []; } - const isJetBrainsAndPreIndexedDocsProvider = - await docsService.isJetBrainsAndPreIndexedDocsProvider(); - - if (isJetBrainsAndPreIndexedDocsProvider) { - void extras.ide.showToast( - "error", - `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + - "the embeddings provider, but it cannot be used with JetBrains. " + - "Please select a different embeddings provider to use the '@docs' " + - "context provider.", - ); - - return []; - } - - const preIndexedDoc = preIndexedDocs[query]; - - if (!!preIndexedDoc) { - void Telemetry.capture("docs_pre_indexed_doc_used", { - doc: preIndexedDoc["title"], - }); - } - - const embeddingsProvider = await docsService.getEmbeddingsProvider( - !!preIndexedDoc, - ); - - const [vector] = await embeddingsProvider.embed([extras.fullInput]); - - let chunks = await docsService.retrieveChunks( + await docsService.isInitialized; + let chunks = await docsService.retrieveChunksFromQuery( + extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case query, - vector, this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, ); @@ -175,7 +146,7 @@ class DocsContextProvider extends BaseContextProvider { return []; } - const docs = (await docsService.list()) ?? []; + const docs = (await docsService.listMetadata()) ?? []; const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); const submenuItemsMap = new Map(); diff --git a/core/context/providers/GitHubIssuesContextProvider.ts b/core/context/providers/GitHubIssuesContextProvider.ts index ef34ad621..7bd64d860 100644 --- a/core/context/providers/GitHubIssuesContextProvider.ts +++ b/core/context/providers/GitHubIssuesContextProvider.ts @@ -21,11 +21,12 @@ class GitHubIssuesContextProvider extends BaseContextProvider { ): Promise { const issueId = query; const { Octokit } = await import("@octokit/rest"); - const domain = this.options?.domain ?? "github.com"; const octokit = new Octokit({ auth: this.options?.githubToken, - baseUrl: `https://${domain}/api/v3`, + baseUrl: this.options?.domain + ? `https://${this.options.domain}/api/v3` + : undefined, request: { fetch: extras.fetch, }, diff --git a/core/context/rerankers/llm.ts b/core/context/rerankers/llm.ts index 5396c8d9b..a673f5dc4 100644 --- a/core/context/rerankers/llm.ts +++ b/core/context/rerankers/llm.ts @@ -6,7 +6,7 @@ const RERANK_PROMPT = ( documentId: string, document: string, ) => `You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query. - + Query: Where is the FastAPI server? Snippet: \`\`\`/Users/andrew/Desktop/server/main.py @@ -17,7 +17,7 @@ const RERANK_PROMPT = ( return {{"Hello": "World"}} \`\`\` Relevant: Yes - + Query: Where in the documentation does it talk about the UI? Snippet: \`\`\`/Users/andrew/Projects/bubble_sort/src/lib.rs @@ -32,13 +32,13 @@ const RERANK_PROMPT = ( }} \`\`\` Relevant: No - + Query: ${query} Snippet: \`\`\`${documentId} ${document} \`\`\` - Relevant: + Relevant: `; export class LLMReranker implements Reranker { @@ -49,6 +49,7 @@ export class LLMReranker implements Reranker { async scoreChunk(chunk: Chunk, query: string): Promise { const completion = await this.llm.complete( RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content), + new AbortController().signal, { maxTokens: 1, model: diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index e4b3e072e..8dc55df9d 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -61,7 +61,7 @@ This is the question that you should select relevant files for: "${input}"`; const response = await llm.chat([ { role: "user", content: prompt }, { role: "assistant", content: "" }, - ]); + ], new AbortController().signal); const content = stripImages(response.content); console.debug("Repo map retrieval response: ", content); diff --git a/core/core.ts b/core/core.ts index 656d89151..03d47c162 100644 --- a/core/core.ts +++ b/core/core.ts @@ -34,6 +34,7 @@ import { setupInitialDotContinueDirectory, } from "./util/paths"; import { Telemetry } from "./util/posthog"; +import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; @@ -46,7 +47,7 @@ export class Core { codebaseIndexerPromise: Promise; completionProvider: CompletionProvider; continueServerClientPromise: Promise; - indexingState: IndexingProgressUpdate; + codebaseIndexingState: IndexingProgressUpdate; controlPlaneClient: ControlPlaneClient; private docsService: DocsService; private globalContext = new GlobalContext(); @@ -92,7 +93,11 @@ export class Core { // Ensure .continue directory is created setupInitialDotContinueDirectory(); - this.indexingState = { status: "loading", desc: "loading", progress: 0 }; + this.codebaseIndexingState = { + status: "loading", + desc: "loading", + progress: 0, + }; const ideSettingsPromise = messenger.request("getIdeSettings", undefined); const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", { @@ -152,6 +157,7 @@ export class Core { // Index on initialization void this.ide.getWorkspaceDirs().then(async (dirs) => { // Respect pauseCodebaseIndexOnStart user settings + this.indexingPauseToken.paused = true; if (ideSettings.pauseCodebaseIndexOnStart) { void this.messenger.request("indexProgress", { progress: 1, @@ -280,34 +286,15 @@ export class Core { // Context providers on("context/addDocs", async (msg) => { - let hasFailed = false; - - for await (const result of this.docsService.indexAndAdd(msg.data)) { - if (result.status === "failed") { - hasFailed = true; - break; - } - } - - if (hasFailed) { - void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); - } else { - void this.ide.showToast( - "info", - `Successfully indexed ${msg.data.startUrl}`, - ); - this.messenger.send("refreshSubmenuItems", undefined); - } + void this.docsService.indexAndAdd(msg.data); }); on("context/removeDocs", async (msg) => { await this.docsService.delete(msg.data.startUrl); - this.messenger.send("refreshSubmenuItems", undefined); }); on("context/indexDocs", async (msg) => { - await this.docsService.indexAllDocs(msg.data.reIndex); - this.messenger.send("refreshSubmenuItems", undefined); + await this.docsService.syncOrReindexAllDocsWithPrompt(msg.data.reIndex); }); on("context/loadSubmenuItems", async (msg) => { @@ -373,6 +360,11 @@ export class Core { } }); + on("context/getSymbolsForFiles", async (msg) => { + const { uris } = msg.data; + return await getSymbolsForManyFiles(uris, this.ide); + }); + on("config/getSerializedProfileInfo", async (msg) => { return { config: await this.configHandler.getSerializedConfig(), @@ -395,6 +387,7 @@ export class Core { const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamChat( msg.data.messages, + new AbortController().signal, msg.data.completionOptions, ); let next = await gen.next(); @@ -436,6 +429,7 @@ export class Core { const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamComplete( msg.data.prompt, + new AbortController().signal, msg.data.completionOptions, ); let next = await gen.next(); @@ -468,6 +462,7 @@ export class Core { const model = await this.configHandler.llmFromTitle(msg.data.title); const completion = await model.complete( msg.data.prompt, + new AbortController().signal, msg.data.completionOptions, ); return completion; @@ -548,33 +543,39 @@ export class Core { } }, 100); - for await (const content of slashCommand.run({ - input, - history, - llm, - contextItems, - params, - ide, - addContextItem: (item) => { - void messenger.request("addContextItem", { - item, - historyIndex, - }); - }, - selectedCode, - config, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - })) { - if (abortedMessageIds.has(msg.messageId)) { - abortedMessageIds.delete(msg.messageId); - break; - } - if (content) { - yield { content }; + try { + for await (const content of slashCommand.run({ + input, + history, + llm, + contextItems, + params, + ide, + addContextItem: (item) => { + void messenger.request("addContextItem", { + item, + historyIndex, + }); + }, + selectedCode, + config, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + })) { + if (abortedMessageIds.has(msg.messageId)) { + abortedMessageIds.delete(msg.messageId); + clearInterval(checkActiveInterval); + break; + } + if (content) { + yield { content }; + } } + } catch (e) { + throw e; + } finally { + clearInterval(checkActiveInterval); } - clearInterval(checkActiveInterval); yield { done: true, content: "" }; } on("command/run", (msg) => @@ -686,6 +687,8 @@ export class Core { const rows = await DevDataSqliteDb.getTokensPerModel(); return rows; }); + + // Codebase indexing on("index/forceReIndex", async ({ data }) => { if (data?.shouldClearIndexes) { const codebaseIndexer = await this.codebaseIndexerPromise; @@ -701,17 +704,41 @@ export class Core { } }); on("index/setPaused", (msg) => { - new GlobalContext().update("indexingPaused", msg.data); + this.globalContext.update("indexingPaused", msg.data); this.indexingPauseToken.paused = msg.data; }); on("index/indexingProgressBarInitialized", async (msg) => { // Triggered when progress bar is initialized. // If a non-default state has been stored, update the indexing display to that state - if (this.indexingState.status !== "loading") { - void this.messenger.request("indexProgress", this.indexingState); + if (this.codebaseIndexingState.status !== "loading") { + void this.messenger.request( + "indexProgress", + this.codebaseIndexingState, + ); } }); + // Docs, etc. indexing + on("indexing/reindex", async (msg) => { + if (msg.data.type === "docs") { + void this.docsService.reindexDoc(msg.data.id); + } + }); + on("indexing/abort", async (msg) => { + if (msg.data.type === "docs") { + this.docsService.abort(msg.data.id); + } + }); + on("indexing/setPaused", async (msg) => { + if (msg.data.type === "docs") { + this.docsService.setPaused(msg.data.id, msg.data.paused); + } + }); + on("indexing/initStatuses", async (msg) => { + return this.docsService.initStatuses(); + }); + // + on("didChangeSelectedProfile", (msg) => { void this.configHandler.setSelectedProfile(msg.data.id); void this.configHandler.reloadConfig(); @@ -768,7 +795,7 @@ export class Core { } void this.messenger.request("indexProgress", updateToSend); - this.indexingState = updateToSend; + this.codebaseIndexingState = updateToSend; if (update.status === "failed") { void this.sendIndexingErrorTelemetry(update); @@ -802,7 +829,7 @@ export class Core { } void this.messenger.request("indexProgress", updateToSend); - this.indexingState = updateToSend; + this.codebaseIndexingState = updateToSend; if (update.status === "failed") { void this.sendIndexingErrorTelemetry(update); @@ -811,4 +838,6 @@ export class Core { this.messenger.send("refreshSubmenuItems", undefined); } + + // private } diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index e6c3183f0..26e174c17 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -86,7 +86,7 @@ export async function* getReplacementWithLlm( const completion = await llm.streamChat([ { role: "user", content: userPrompt }, { role: "assistant", content: assistantPrompt }, - ]); + ], new AbortController().signal); let lines = streamLines(completion); lines = filterLeadingNewline(lines); diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 135aa3170..a5c85ee4d 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -23,7 +23,7 @@ export async function* streamLazyApply( } const promptMessages = promptFactory(oldCode, filename, newCode); - const lazyCompletion = llm.streamChat(promptMessages); + const lazyCompletion = llm.streamChat(promptMessages, new AbortController().signal); // Do find and replace over the lazy edit response async function* replacementFunction( diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index ca47f010d..5ecf273c5 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -96,8 +96,8 @@ export async function* streamDiffLines( const completion = typeof prompt === "string" - ? llm.streamComplete(prompt, { raw: true, prediction }) - : llm.streamChat(prompt, { + ? llm.streamComplete(prompt, new AbortController().signal, { raw: true, prediction }) + : llm.streamChat(prompt, new AbortController().signal, { prediction, }); diff --git a/core/index.d.ts b/core/index.d.ts index 1bad9fd74..ce2e59449 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,3 +1,4 @@ +import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; declare global { @@ -45,6 +46,30 @@ export interface IndexingProgressUpdate { debugInfo?: string; } +// This is more or less a V2 of IndexingProgressUpdate +export interface IndexingStatus { + id: string; + type: "docs"; + progress: number; + description: string; + status: + | "indexing" + | "complete" + | "paused" + | "failed" + | "aborted" + | "deleted" + | "pending"; + embeddingsProviderId: string; + isReindexing?: boolean; + debugInfo?: string; + title: string; + icon?: string; + url?: string; +} + +export type IndexingStatusMap = Map; + export type PromptTemplateFunction = ( history: ChatMessage[], otherData: Record, @@ -78,26 +103,34 @@ export interface ILLM extends LLMOptions { region?: string; projectId?: string; - complete(prompt: string, options?: LLMFullCompletionOptions): Promise; + complete( + prompt: string, + signal: AbortSignal, + options?: LLMFullCompletionOptions + ): Promise; streamComplete( prompt: string, + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; streamFim( prefix: string, suffix: string, + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; streamChat( messages: ChatMessage[], + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; chat( messages: ChatMessage[], + signal: AbortSignal, options?: LLMFullCompletionOptions, ): Promise; @@ -200,11 +233,16 @@ export interface IContextProvider { loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise; } +export interface Checkpoint { + [filepath: string]: string; +} + export interface PersistedSessionInfo { history: ChatHistory; title: string; workspaceDirectory: string; sessionId: string; + checkpoints?: Checkpoint[]; } export interface SessionInfo { @@ -298,13 +336,19 @@ export interface InputModifiers { noContext: boolean; } +export interface SymbolWithRange extends RangeInFile { + name: string; + type: Parser.SyntaxNode["type"]; +} + +export type FileSymbolMap = Record; + export interface PromptLog { modelTitle: string; completionOptions: CompletionOptions; prompt: string; completion: string; } - export interface ChatHistoryItem { message: ChatMessage; editorState?: any; @@ -383,11 +427,13 @@ export interface CustomLLMWithOptionals { options: LLMOptions; streamCompletion?: ( prompt: string, + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; streamChat?: ( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; @@ -654,7 +700,8 @@ type ModelProvider = | "askSage" | "vertexai" | "nebius" - | "xAI"; + | "xAI" + | "moonshot"; export type ModelName = | "AUTODETECT" @@ -749,7 +796,11 @@ export type ModelName = | "starcoder-1b" | "starcoder-3b" | "starcoder2-3b" - | "stable-code-3b"; + | "stable-code-3b" + // Moonshot + | "moonshot-v1-8k" + | "moonshot-v1-32k" + | "moonshot-v1-128k"; export interface RequestOptions { timeout?: number; @@ -927,7 +978,7 @@ export interface TabAutocompleteOptions { slidingWindowPrefixPercentage: number; slidingWindowSize: number; maxSnippetPercentage: number; - recentlyEditedSimilarityThreshold: number; + maxDiffPercentage: number; useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index 599c4202a..8854d8e87 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -95,6 +95,6 @@ export default DocsCrawler; export { CheerioCrawler, ChromiumCrawler, - ChromiumInstaller as ChromiumInstaller, + ChromiumInstaller, GitHubCrawler, }; diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.test.ts index 9bac503c9..67d33020d 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -66,23 +66,20 @@ describe.skip("DocsService Integration Tests", () => { }); test("Indexing, retrieval, and deletion of a new documentation site", async () => { - const generator = docsService.indexAndAdd(mockSiteConfig); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(mockSiteConfig); let latestConfig = await getReloadedConfig(); // Sqlite check - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); // config.json check expect(latestConfig.docs).toContainEqual(mockSiteConfig); // Lance DB check - const embeddingsProvider = await docsService.getEmbeddingsProvider(); - const [mockVector] = await embeddingsProvider.embed(["test"]); - let retrievedChunks = await docsService.retrieveChunks( + let retrievedChunks = await docsService.retrieveChunksFromQuery( + "test", mockSiteConfig.startUrl, - mockVector, 5, ); @@ -91,7 +88,7 @@ describe.skip("DocsService Integration Tests", () => { await docsService.delete(mockSiteConfig.startUrl); // Sqlite check - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); // config.json check latestConfig = await getReloadedConfig(); @@ -100,9 +97,9 @@ describe.skip("DocsService Integration Tests", () => { ); // LanceDB check - retrievedChunks = await docsService.retrieveChunks( + retrievedChunks = await docsService.retrieveChunksFromQuery( + "test", mockSiteConfig.startUrl, - mockVector, 5, ); expect(retrievedChunks.length).toBe(0); @@ -133,17 +130,15 @@ describe.skip("DocsService Integration Tests", () => { test("Handles pulling down and adding pre-indexed docs", async () => { const preIndexedDoc = Object.values(preIndexedDocs)[0]; - const generator = docsService.indexAndAdd(preIndexedDoc); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(preIndexedDoc); }); test("Config synchronization with SQLite", async () => { - const generator = docsService.indexAndAdd(mockSiteConfig); - while (!(await generator.next()).done) {} + await docsService.indexAndAdd(mockSiteConfig); await getReloadedConfig(); - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true); editConfigJson((config) => { const { docs, ...restConfig } = config; @@ -164,6 +159,6 @@ describe.skip("DocsService Integration Tests", () => { await new Promise((resolve) => setTimeout(resolve, 100)); } - expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false); + expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false); }); }); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index dde15f502..838e8fb54 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -7,8 +7,10 @@ import { ContinueConfig, EmbeddingsProvider, IDE, - IndexingProgressUpdate, + IndexingStatusMap, + IndexingStatus, SiteIndexingConfig, + IdeInfo, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; import { addContextProvider } from "../../config/util"; @@ -36,6 +38,12 @@ import { } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +// Progress heuristic values +// subpages -> embeddings -> delete from db -> add to db +const PROGRESS_AT_EMBEDDING = 0.5; +const PROGRESS_AT_DELETE_OPERATIONS = 0.7; +const PROGRESS_AT_ADD_OPERATIONS = 0.8; + // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { title: string; @@ -62,13 +70,27 @@ export type AddParams = { favicon?: string; }; +/* + General process: + - On config update: + - Reindex ALL docs if embeddings provider has changed + - Otherwise, reindex docs with CHANGED URL/DEPTH + - And update docs with CHANGED TITLE/FAVICON + - Also, messages to core can trigger: + - delete + - reindex all + - add/index one + - Currently a full reindex deletes all docs rather than storing PER embeddings provider + - The last successful embeddings provider is stored in global context and updated AFTER an indexing process is successful +*/ export default class DocsService { static lanceTableName = "docs"; static sqlitebTableName = "docs"; + static indexingType = "docs"; + static preIndexedDocsEmbeddingsProvider = new TransformersJsEmbeddingsProvider(); - private static instance?: DocsService; public isInitialized: Promise; public isSyncing: boolean = false; @@ -80,19 +102,19 @@ export default class DocsService { private sqliteDb?: Database; private docsCrawler!: DocsCrawler; + private ideInfoPromise: Promise; constructor( configHandler: ConfigHandler, private readonly ide: IDE, private readonly messenger?: IMessenger, ) { + this.ideInfoPromise = this.ide.getIdeInfo(); this.isInitialized = this.init(configHandler); } - static getSingleton() { - return DocsService.instance; - } - + // Singleton pattern: only one service globally + private static instance?: DocsService; static createSingleton( configHandler: ConfigHandler, ide: IDE, @@ -103,14 +125,79 @@ export default class DocsService { return docsService; } - async isJetBrainsAndPreIndexedDocsProvider(): Promise { - const isJetBrains = await this.isJetBrains(); + static getSingleton() { + return DocsService.instance; + } - const isPreIndexedDocsProvider = - this.config.embeddingsProvider.id === - DocsService.preIndexedDocsEmbeddingsProvider.id; + // Initialization - load config and attach config listener + private async init(configHandler: ConfigHandler) { + const config = await configHandler.loadConfig(); + await this.handleConfigUpdate({ config }); + configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); + } - return isJetBrains && isPreIndexedDocsProvider; + readonly statuses: IndexingStatusMap = new Map(); + + // Function for GUI to retrieve initial pending statuses + // And kickoff indexing where needed + async initStatuses() { + this.config?.docs?.forEach(async (doc) => { + const currentStatus = this.statuses.get(doc.startUrl); + if (currentStatus) { + this.handleStatusUpdate(currentStatus); + } else { + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + progress: 0, + description: "Pending", + status: "pending", + title: doc.title, + debugInfo: `max depth: ${doc.maxDepth}`, + icon: doc.faviconUrl, + url: doc.startUrl, + }); + } + }); + } + + handleStatusUpdate(update: IndexingStatus) { + this.statuses.set(update.id, update); + this.messenger?.send("indexing/statusUpdate", update); + } + + abort(startUrl: string) { + const status = this.statuses.get(startUrl); + if (status) { + this.docsIndexingQueue.delete(startUrl); + this.handleStatusUpdate({ + ...status, + status: "aborted", + progress: 0, + description: "Canceled", + }); + } + } + + isAborted(startUrl: string) { + return this.statuses.get(startUrl)?.status === "aborted"; + } + + // NOTE Pausing not supported for docs yet + setPaused(startUrl: string, pause: boolean) { + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ + ...status, + status: pause ? "paused" : "indexing", + }); + } + } + + isPaused(startUrl: string) { + return this.statuses.get(startUrl)?.status === "paused"; } /* @@ -119,21 +206,95 @@ export default class DocsService { * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. */ async canUsePreindexedDocs() { - const isJetBrains = await this.isJetBrains(); - return !isJetBrains; + const ideInfo = await this.ideInfoPromise; + if (ideInfo.ideType === "jetbrains") { + return false; + } + return true; } - async delete(startUrl: string) { - await this.deleteFromLance(startUrl); - await this.deleteFromSqlite(startUrl); - this.deleteFromConfig(startUrl); + async isUsingUnsupportedPreIndexedEmbeddingsProvider() { + const isPreIndexedDocsProvider = + this.config.embeddingsProvider.id === + DocsService.preIndexedDocsEmbeddingsProvider.id; + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + return isPreIndexedDocsProvider && !canUsePreindexedDocs; + } - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); + async getEmbeddingsProvider( + isPreIndexedDoc: boolean = false, + ): Promise { + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + + if (canUsePreindexedDocs && isPreIndexedDoc) { + return DocsService.preIndexedDocsEmbeddingsProvider; + } + + return this.config.embeddingsProvider; + } + + private async handleConfigUpdate({ + config: newConfig, + }: { + config: ContinueConfig | undefined; + }) { + if (newConfig) { + const oldConfig = this.config; + this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in + + this.docsCrawler = new DocsCrawler(this.ide, newConfig); + + // Skip docs indexing if not supported + const unsupported = + await this.isUsingUnsupportedPreIndexedEmbeddingsProvider(); + if (unsupported) { + return; + } + + await this.syncOrReindexAllDocs(newConfig, oldConfig); } } - async has(startUrl: string): Promise> { + private async syncOrReindexAllDocs( + newConfig: ContinueConfig, + oldConfig?: ContinueConfig, + ) { + // On embeddings provider change, reindex all non-preindexed docs + // change = doesn't match last successful embeddings provider + const curEmbeddingsProviderId = this.globalContext.get( + "curEmbeddingsProviderId", + ); + if ( + !curEmbeddingsProviderId || + curEmbeddingsProviderId !== newConfig.embeddingsProvider.id + ) { + // If not set, we're initializing + const currentDocs = await this.listMetadata(); + if (currentDocs.length > 0) { + await this.reindexDocsOnNewEmbeddingsProvider(); + return; + } + } + + await this.syncDocsOnConfigUpdate(oldConfig, newConfig); + } + + async syncOrReindexAllDocsWithPrompt(reIndex: boolean = false) { + if (!this.hasDocsContextProvider()) { + const didAddDocsContextProvider = + await this.showAddDocsContextProviderToast(); + + if (!didAddDocsContextProvider) { + return; + } + } + + await this.syncOrReindexAllDocs(this.config); + + void this.ide.showToast("info", "Docs indexing completed"); + } + + async hasMetadata(startUrl: string): Promise> { const db = await this.getOrCreateSqliteDb(); const title = await db.get( `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, @@ -166,27 +327,7 @@ export default class DocsService { return res === actionMsg; } - async indexAllDocs(reIndex: boolean = false) { - if (!this.hasDocsContextProvider()) { - const didAddDocsContextProvider = - await this.showAddDocsContextProviderToast(); - - if (!didAddDocsContextProvider) { - return; - } - } - - const docs = await this.list(); - - for (const doc of docs) { - const generator = this.indexAndAdd(doc, reIndex); - while (!(await generator.next()).done) {} - } - - void this.ide.showToast("info", "Docs indexing completed"); - } - - async list() { + async listMetadata() { const db = await this.getOrCreateSqliteDb(); const docs = await db.all( `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}`, @@ -195,162 +336,303 @@ export default class DocsService { return docs; } - async *indexAndAdd( + async reindexDoc(startUrl: string) { + const docConfig = this.config.docs?.find( + (doc) => doc.startUrl === startUrl, + ); + if (docConfig) { + await this.indexAndAdd(docConfig, true); + } + } + + async indexAndAdd( siteIndexingConfig: SiteIndexingConfig, reIndex: boolean = false, - ): AsyncGenerator { + ): Promise { const { startUrl } = siteIndexingConfig; + + // Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs + if (this.docsIndexingQueue.has(startUrl)) { + return; + } + const embeddingsProvider = await this.getEmbeddingsProvider(); - if (this.docsIndexingQueue.has(startUrl)) { - console.log("Already in queue"); - return; - } - - if (!reIndex && (await this.has(startUrl))) { - yield { - progress: 1, - desc: "Already indexed", - status: "done", - }; - return; - } - - // Mark the site as currently being indexed this.docsIndexingQueue.add(startUrl); - yield { - progress: 0, - desc: "Finding subpages", - status: "indexing", + const indexExists = await this.hasMetadata(startUrl); + + const fixedStatus: Pick< + IndexingStatus, + | "type" + | "id" + | "embeddingsProviderId" + | "isReindexing" + | "debugInfo" + | "icon" + | "url" + | "title" + > = { + type: "docs", + id: siteIndexingConfig.startUrl, + embeddingsProviderId: embeddingsProvider.id, + isReindexing: reIndex && indexExists, + title: siteIndexingConfig.title, + debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`, + icon: siteIndexingConfig.faviconUrl, + url: siteIndexingConfig.startUrl, }; - const articles: Article[] = []; - let processedPages = 0; - let maxKnownPages = 1; - - // Crawl pages and retrieve info as articles - for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { - processedPages++; - - const article = pageToArticle(page); - - if (!article) { - continue; - } - - articles.push(article); - - // Use a heuristic approach for progress calculation - const progress = Math.min(processedPages / maxKnownPages, 1); - - yield { - progress, // Yield the heuristic progress - desc: `Finding subpages (${page.path})`, - status: "indexing", - }; - - // Increase maxKnownPages to delay progress reaching 100% too soon - if (processedPages === maxKnownPages) { - maxKnownPages *= 2; - } - - await new Promise((resolve) => setTimeout(resolve, 50)); - } - - void Telemetry.capture("docs_pages_crawled", { - count: processedPages, - }); - - const chunks: Chunk[] = []; - const embeddings: number[][] = []; - - // Create embeddings of retrieved articles - console.log(`Creating embeddings for ${articles.length} articles`); - - for (let i = 0; i < articles.length; i++) { - const article = articles[i]; - yield { - progress: i / articles.length, - desc: `Creating Embeddings: ${article.subpath}`, - status: "indexing", - }; - - try { - const chunkedArticle = chunkArticle( - article, - embeddingsProvider.maxChunkSize, - ); - - const chunkedArticleContents = chunkedArticle.map( - (chunk) => chunk.content, - ); - - chunks.push(...chunkedArticle); - - const subpathEmbeddings = await embeddingsProvider.embed( - chunkedArticleContents, - ); - - embeddings.push(...subpathEmbeddings); - } catch (e) { - console.warn("Error chunking article: ", e); + if (indexExists) { + if (reIndex) { + await this.deleteIndexes(startUrl); + } else { + this.handleStatusUpdate({ + ...fixedStatus, + progress: 1, + description: "Complete", + status: "complete", + debugInfo: "Already indexed", + }); + return; } } - if (embeddings.length === 0) { - console.error( - `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, - ); + try { + this.handleStatusUpdate({ + ...fixedStatus, + status: "indexing", + description: "Finding subpages", + progress: 0, + }); - yield { - progress: 1, - desc: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, - status: "failed", - }; + const articles: Article[] = []; + let processedPages = 0; + let estimatedProgress = 0; + + // Crawl pages and retrieve info as articles + for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { + estimatedProgress += 1 / 2 ** (processedPages + 1); + + // NOTE - during "indexing" phase, check if aborted before each status update + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: `Finding subpages (${page.path})`, + status: "indexing", + progress: + 0.3 * estimatedProgress + + Math.min(0.2, (0.2 * processedPages) / 500), + // For the first 50%, 30% is sum of series 1/(2^n) and the other 20% is based on number of files/ 500 max + }); + + const article = pageToArticle(page); + if (!article) { + continue; + } + articles.push(article); + + processedPages++; + await new Promise((resolve) => setTimeout(resolve, 50)); // Locks down GUI if no sleeping + } + + void Telemetry.capture("docs_pages_crawled", { + count: processedPages, + }); + + const chunks: Chunk[] = []; + const embeddings: number[][] = []; + + // Create embeddings of retrieved articles + console.debug(`Creating embeddings for ${articles.length} articles`); + + for (let i = 0; i < articles.length; i++) { + const article = articles[i]; + + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + status: "indexing", + description: `Creating Embeddings: ${article.subpath}`, + progress: 0.5 + 0.3 * (i / articles.length), // 50% -> 80% + }); + + try { + const chunkedArticle = chunkArticle( + article, + embeddingsProvider.maxChunkSize, + ); + + const chunkedArticleContents = chunkedArticle.map( + (chunk) => chunk.content, + ); + + chunks.push(...chunkedArticle); + + const subpathEmbeddings = await embeddingsProvider.embed( + chunkedArticleContents, + ); + + embeddings.push(...subpathEmbeddings); + } catch (e) { + console.warn("Error chunking article: ", e); + } + } + + if (embeddings.length === 0) { + console.error( + `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, + ); + + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, + status: "failed", + progress: 1, + }); + + void this.ide.showToast("info", `Failed to index ${startUrl}`); + this.docsIndexingQueue.delete(startUrl); + return; + } + + // Add docs to databases + console.log(`Adding ${embeddings.length} embeddings to db`); + + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: "Deleting old embeddings from the db", + status: "indexing", + progress: 0.8, + }); + + // Delete indexed docs if re-indexing + if (reIndex && indexExists) { + console.log("Deleting old embeddings"); + await this.deleteIndexes(startUrl); + } + + const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); + + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: `Adding ${embeddings.length} embeddings to db`, + status: "indexing", + progress: 0.85, + }); + + await this.add({ + siteIndexingConfig, + chunks, + embeddings, + favicon, + }); this.docsIndexingQueue.delete(startUrl); - return; + if (this.isAborted(startUrl)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: "Complete", + status: "complete", + progress: 1, + }); + + void this.ide.showToast("info", `Successfully indexed ${startUrl}`); + + if (this.messenger) { + this.messenger.send("refreshSubmenuItems", undefined); + } + } catch (e) { + console.error("Error indexing docs", e); + this.handleStatusUpdate({ + ...fixedStatus, + description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, + status: "failed", + progress: 1, + }); + } finally { + this.docsIndexingQueue.delete(startUrl); } + } - // Add docs to databases - console.log(`Adding ${embeddings.length} embeddings to db`); + // When user requests a pre-indexed doc for the first time + // And pre-indexed embeddings are supported + // Fetch pre-indexed embeddings from S3, add to Lance, and then search those + private async fetchAndAddPreIndexedDocEmbeddings(title: string) { + const embeddingsProvider = await this.getEmbeddingsProvider(true); - yield { - progress: 0.5, - desc: `Adding ${embeddings.length} embeddings to db`, - status: "indexing", - }; + const data = await downloadFromS3( + S3Buckets.continueIndexedDocs, + getS3Filename(embeddingsProvider.id, title), + ); - // Delete indexed docs if re-indexing - if (reIndex && (await this.has(startUrl.toString()))) { - console.log("Deleting old embeddings"); - await this.delete(startUrl); - } + const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; + const startUrl = new URL(siteEmbeddings.url).toString(); - const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); + const faviconUrl = preIndexedDocs[startUrl].faviconUrl; + const favicon = + typeof faviconUrl === "string" + ? await getFaviconBase64(faviconUrl) + : undefined; await this.add({ - siteIndexingConfig, - chunks, - embeddings, favicon, + siteIndexingConfig: { + startUrl, + title: siteEmbeddings.title, + }, + chunks: siteEmbeddings.chunks, + embeddings: siteEmbeddings.chunks.map((c) => c.embedding), }); + } - this.docsIndexingQueue.delete(startUrl); + // Retrieve docs embeds based on user input + async retrieveChunksFromQuery( + query: string, + startUrl: string, + nRetrieve: number, + ) { + if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) { + await this.ide.showToast( + "error", + `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + + "the embeddings provider, but it cannot be used with JetBrains. " + // TODO "with this IDE" + "Please select a different embeddings provider to use the '@docs' " + + "context provider.", + ); - yield { - progress: 1, - desc: "Done", - status: "done", - }; - - console.log(`Successfully indexed: ${siteIndexingConfig.startUrl}`); - - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); + return []; } + + const preIndexedDoc = preIndexedDocs[startUrl]; + if (!!preIndexedDoc) { + void Telemetry.capture("docs_pre_indexed_doc_used", { + doc: preIndexedDoc["title"], + }); + } + + const embeddingsProvider = + await this.getEmbeddingsProvider(!!preIndexedDoc); + + const [vector] = await embeddingsProvider.embed([query]); + + return await this.retrieveChunks(startUrl, vector, nRetrieve); } async retrieveChunks( @@ -359,9 +641,10 @@ export default class DocsService { nRetrieve: number, isRetry: boolean = false, ): Promise { + const isPreIndexedDoc = !!preIndexedDocs[startUrl]; const table = await this.getOrCreateLanceTable({ initializationVector: vector, - isPreIndexedDoc: !!preIndexedDocs[startUrl], + isPreIndexedDoc, }); let docs: LanceDbDocsRow[] = []; @@ -372,10 +655,10 @@ export default class DocsService { .where(`starturl = '${startUrl}'`) .execute(); } catch (e: any) { - console.error("Error retrieving chunks from LanceDB", e); + console.warn("Error retrieving chunks from LanceDB", e); } - const hasIndexedDoc = await this.hasIndexedDoc(startUrl); + const hasIndexedDoc = await this.hasMetadata(startUrl); if (!hasIndexedDoc && docs.length === 0) { const preIndexedDoc = preIndexedDocs[startUrl]; @@ -401,105 +684,7 @@ export default class DocsService { })); } - async getEmbeddingsProvider(isPreIndexedDoc: boolean = false) { - const canUsePreindexedDocs = await this.canUsePreindexedDocs(); - - if (isPreIndexedDoc && canUsePreindexedDocs) { - return DocsService.preIndexedDocsEmbeddingsProvider; - } - - return this.config.embeddingsProvider; - } - - async getFavicon(startUrl: string) { - const db = await this.getOrCreateSqliteDb(); - const result = await db.get( - `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, - startUrl, - ); - - if (!result) { - return; - } - return result.favicon; - } - - private async init(configHandler: ConfigHandler) { - this.config = await configHandler.loadConfig(); - this.docsCrawler = new DocsCrawler(this.ide, this.config); - - const embeddingsProvider = await this.getEmbeddingsProvider(); - - this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - - configHandler.onConfigUpdate(async ({ config: newConfig }) => { - if (newConfig) { - const oldConfig = this.config; - - // Need to update class property for config at the beginning of this callback - // to ensure downstream methods have access to the latest config. - this.config = newConfig; - - if (oldConfig.docs !== newConfig.docs) { - await this.syncConfigAndSqlite(); - } - - const shouldReindex = - await this.shouldReindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider.id, - ); - - if (shouldReindex) { - await this.reindexDocsOnNewEmbeddingsProvider( - newConfig.embeddingsProvider, - ); - } - } - }); - } - - private async syncConfigAndSqlite() { - this.isSyncing = true; - - const sqliteDocs = await this.list(); - const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || []; - - const configDocs = this.config.docs || []; - const configDocStartUrls = - this.config.docs?.map((doc) => doc.startUrl) || []; - - const newDocs = configDocs.filter( - (doc) => !sqliteDocStartUrls.includes(doc.startUrl), - ); - const deletedDocs = sqliteDocs.filter( - (doc) => - !configDocStartUrls.includes(doc.startUrl) && - !preIndexedDocs[doc.startUrl], - ); - - for (const doc of newDocs) { - console.log(`Indexing new doc: ${doc.startUrl}`); - void Telemetry.capture("add_docs_config", { url: doc.startUrl }); - - const generator = this.indexAndAdd(doc); - while (!(await generator.next()).done) {} - } - - for (const doc of deletedDocs) { - // console.debug(`Deleting doc: ${doc.startUrl}`); - await this.delete(doc.startUrl); - } - - this.isSyncing = false; - } - - private hasDocsContextProvider() { - return !!this.config.contextProviders?.some( - (provider) => - provider.description.title === DocsContextProvider.description.title, - ); - } - + // SQLITE DB private async getOrCreateSqliteDb() { if (!this.sqliteDb) { const db = await open({ @@ -524,6 +709,118 @@ export default class DocsService { return this.sqliteDb; } + async getFavicon(startUrl: string) { + const db = await this.getOrCreateSqliteDb(); + const result = await db.get( + `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + startUrl, + ); + + if (!result) { + return; + } + return result.favicon; + } + + /* + Sync with no embeddings provider change + Ignores pre-indexed docs + */ + private async syncDocsOnConfigUpdate( + oldConfig: ContinueConfig | undefined, + newConfig: ContinueConfig, + ) { + try { + this.isSyncing = true; + + // Otherwise sync the index based on config changes + const oldConfigDocs = oldConfig?.docs || []; + const newConfigDocs = newConfig.docs || []; + const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl); + + const currentlyIndexedDocs = await this.listMetadata(); + const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl); + + // Anything found in sqlite but not in new config should be deleted if not preindexed + const deletedDocs = currentlyIndexedDocs.filter( + (doc) => + !preIndexedDocs[doc.startUrl] && + !newConfigStartUrls.includes(doc.startUrl), + ); + + // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed + // TODO if only favicon and title change, only update, don't embed + // Otherwise anything found in new config that isn't in sqlite should be added/indexed + const newDocs: SiteIndexingConfig[] = []; + const changedDocs: SiteIndexingConfig[] = []; + for (const doc of newConfigDocs) { + const currentIndexedDoc = currentStartUrls.includes(doc.startUrl); + + if (currentIndexedDoc) { + const oldConfigDoc = oldConfigDocs.find( + (d) => d.startUrl === doc.startUrl, + ); + if ( + oldConfigDoc && + (oldConfigDoc.maxDepth !== doc.maxDepth || + oldConfigDoc.title !== doc.title || + oldConfigDoc.faviconUrl !== doc.faviconUrl) + ) { + changedDocs.push(doc); + } else { + // if get's here, not changed, no update needed, mark as complete + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: this.config.embeddingsProvider.id, + isReindexing: false, + title: doc.title, + debugInfo: "Config sync: not changed", + icon: doc.faviconUrl, + url: doc.startUrl, + progress: 1, + description: "Complete", + status: "complete", + }); + } + } else { + newDocs.push(doc); + } + } + + // Sends "Pending" or current status for each + await this.initStatuses(); + + for (const doc of changedDocs) { + console.log(`Updating indexed doc: ${doc.startUrl}`); + await this.indexAndAdd(doc, true); + } + + for (const doc of newDocs) { + console.log(`Indexing new doc: ${doc.startUrl}`); + void Telemetry.capture("add_docs_config", { url: doc.startUrl }); + + await this.indexAndAdd(doc); + } + + for (const doc of deletedDocs) { + await this.deleteIndexes(doc.startUrl); + } + } catch (e) { + console.error("Error syncing docs index on config update", e); + } finally { + this.isSyncing = false; + } + } + + private hasDocsContextProvider() { + return !!this.config.contextProviders?.some( + (provider) => + provider.description.title === DocsContextProvider.description.title, + ); + } + + // Lance DB Initialization private async createLanceDocsTable( connection: Connection, initializationVector: number[], @@ -604,21 +901,7 @@ export default class DocsService { return table; } - private async isJetBrains() { - const ideInfo = await this.ide.getIdeInfo(); - return ideInfo.ideType === "jetbrains"; - } - - private async hasIndexedDoc(startUrl: string) { - const db = await this.getOrCreateSqliteDb(); - const docs = await db.all( - `SELECT startUrl FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, - startUrl, - ); - - return docs.length > 0; - } - + // Methods for adding individual docs private async addToLance({ chunks, siteIndexingConfig, @@ -626,6 +909,7 @@ export default class DocsService { }: AddParams) { const sampleVector = embeddings[0]; const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; + const table = await this.getOrCreateLanceTable({ isPreIndexedDoc, initializationVector: sampleVector, @@ -644,7 +928,7 @@ export default class DocsService { await table.add(rows); } - private async addToSqlite({ + private async addMetadataToSqlite({ siteIndexingConfig: { title, startUrl }, favicon, }: AddParams) { @@ -674,7 +958,7 @@ export default class DocsService { private async add(params: AddParams) { await this.addToLance(params); - await this.addToSqlite(params); + await this.addMetadataToSqlite(params); const isPreIndexedDoc = !!preIndexedDocs[params.siteIndexingConfig.startUrl]; @@ -684,7 +968,8 @@ export default class DocsService { } } - private async deleteFromLance(startUrl: string) { + // Delete methods + private async deleteEmbeddingsFromLance(startUrl: string) { for (const tableName of this.lanceTableNamesSet) { const conn = await lancedb.connect(getLanceDbPath()); const table = await conn.openTable(tableName); @@ -692,7 +977,7 @@ export default class DocsService { } } - private async deleteFromSqlite(startUrl: string) { + private async deleteMetadataFromSqlite(startUrl: string) { const db = await this.getOrCreateSqliteDb(); await db.run( `DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, @@ -700,81 +985,32 @@ export default class DocsService { ); } - deleteFromConfig(startUrl: string) { - editConfigJson((config) => ({ - ...config, - docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], - })); + private deleteFromConfig(startUrl: string) { + const doesDocExist = this.config.docs?.some( + (doc) => doc.startUrl === startUrl, + ); + if (doesDocExist) { + editConfigJson((config) => ({ + ...config, + docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], + })); + } } - private async fetchAndAddPreIndexedDocEmbeddings(title: string) { - const embeddingsProvider = await this.getEmbeddingsProvider(true); - - const data = await downloadFromS3( - S3Buckets.continueIndexedDocs, - getS3Filename(embeddingsProvider.id, title), - ); - - const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; - const startUrl = new URL(siteEmbeddings.url).toString(); - - const faviconUrl = preIndexedDocs[startUrl].faviconUrl; - const favicon = - typeof faviconUrl === "string" - ? await getFaviconBase64(faviconUrl) - : undefined; - - await this.add({ - favicon, - siteIndexingConfig: { - startUrl, - title: siteEmbeddings.title, - }, - chunks: siteEmbeddings.chunks, - embeddings: siteEmbeddings.chunks.map((c) => c.embedding), - }); + async deleteIndexes(startUrl: string) { + await this.deleteEmbeddingsFromLance(startUrl); + await this.deleteMetadataFromSqlite(startUrl); } - private async shouldReindexDocsOnNewEmbeddingsProvider( - curEmbeddingsProviderId: EmbeddingsProvider["id"], - ): Promise { - const isJetBrainsAndPreIndexedDocsProvider = - await this.isJetBrainsAndPreIndexedDocsProvider(); + async delete(startUrl: string) { + await this.deleteIndexes(startUrl); + this.deleteFromConfig(startUrl); - if (isJetBrainsAndPreIndexedDocsProvider) { - // A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider - // void this.ide.showToast( - // "error", - // "The 'transformers.js' embeddings provider currently cannot be used to index " + - // "documentation in JetBrains. To enable documentation indexing, you can use " + - // "any of the other providers described in the docs: " + - // "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", - // ); - - this.globalContext.update( - "curEmbeddingsProviderId", - curEmbeddingsProviderId, - ); - - return false; + const status = this.statuses.get(startUrl); + if (status) { + this.handleStatusUpdate({ ...status, status: "deleted" }); } - - const lastEmbeddingsProviderId = this.globalContext.get( - "curEmbeddingsProviderId", - ); - - if (!lastEmbeddingsProviderId) { - // If it's the first time we're setting the `curEmbeddingsProviderId` - // global state, we don't need to reindex docs - this.globalContext.update( - "curEmbeddingsProviderId", - curEmbeddingsProviderId, - ); - - return false; - } - - return lastEmbeddingsProviderId !== curEmbeddingsProviderId; + this.messenger?.send("refreshSubmenuItems", undefined); } /** @@ -782,27 +1018,21 @@ export default class DocsService { * A more optimal solution in the future will be to create * a per-embeddings-provider table for docs. */ - private async reindexDocsOnNewEmbeddingsProvider( - embeddingsProvider: EmbeddingsProvider, - ) { + private async reindexDocsOnNewEmbeddingsProvider() { // We use config as our source of truth here since it contains additional information // needed for re-crawling such as `faviconUrl` and `maxDepth`. - const { docs } = this.config; + const { docs, embeddingsProvider } = this.config; if (!docs || docs.length === 0) { return; } console.log( - `Reindexing docs with new embeddings provider: ${embeddingsProvider.id}`, + `Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.id}`, ); - + await this.initStatuses(); for (const doc of docs) { - await this.delete(doc.startUrl); - - const generator = this.indexAndAdd(doc); - - while (!(await generator.next()).done) {} + await this.indexAndAdd(doc, true); } // Important that this only is invoked after we have successfully @@ -810,8 +1040,6 @@ export default class DocsService { // invalid state. this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - console.log("Completed reindexing of all docs"); + console.log("Completed reindexing of all non-preindexed docs"); } } - -export const docsServiceSingleton = DocsService.getSingleton(); diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 01935af9e..99a8ddc8a 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -330,6 +330,12 @@ const preIndexedDocs: Record< startUrl: "https://llama-stack.readthedocs.io/", rootUrl: "https://llama-stack.readthedocs.io/", }, + "https://go.dev/doc": { + title: "Go", + startUrl: "https://go.dev/doc", + rootUrl: "https://go.dev", + faviconUrl: "https://go.dev/favicon.ico", + }, }; export default preIndexedDocs; diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index bebb8ead1..8e475d01e 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -117,6 +117,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [ "huggingface-inference-api", "huggingface-tgi", "mistral", + "moonshot", "free-trial", "replicate", "together", @@ -149,9 +150,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("chat-bison") || lower.includes("pplx") || lower.includes("gemini") || - lower.includes("grok") + lower.includes("grok")|| + lower.includes("moonshot") ) { - return undefined; + return undefined; } if (lower.includes("llama3")) { diff --git a/core/llm/index.ts b/core/llm/index.ts index d3148f833..1156120a6 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -372,10 +372,11 @@ export abstract class BaseLLM implements ILLM { `HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`, ); } else { - console.debug( - `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, - ); - + if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here + console.debug( + `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, + ); + } if ( e.code === "ECONNREFUSED" && e.message.includes("http://127.0.0.1:11434") @@ -424,6 +425,7 @@ export abstract class BaseLLM implements ILLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { throw new Error("Not implemented"); @@ -432,6 +434,7 @@ export abstract class BaseLLM implements ILLM { async *streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { const { completionOptions, log } = this._parseCompletionOptions(options); @@ -452,6 +455,7 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of this._streamFim( prefix, suffix, + signal, completionOptions, )) { completion += chunk; @@ -477,6 +481,7 @@ export abstract class BaseLLM implements ILLM { async *streamComplete( _prompt: string, + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ) { const { completionOptions, log, raw } = @@ -506,6 +511,7 @@ export abstract class BaseLLM implements ILLM { try { for await (const chunk of this._streamComplete( prompt, + signal, completionOptions, )) { completion += chunk; @@ -527,7 +533,7 @@ export abstract class BaseLLM implements ILLM { }; } - async complete(_prompt: string, options: LLMFullCompletionOptions = {}) { + async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) { const { completionOptions, log, raw } = this._parseCompletionOptions(options); @@ -551,7 +557,7 @@ export abstract class BaseLLM implements ILLM { } } - const completion = await this._complete(prompt, completionOptions); + const completion = await this._complete(prompt, signal, completionOptions); this._logTokensGenerated(completionOptions.model, prompt, completion); @@ -562,9 +568,9 @@ export abstract class BaseLLM implements ILLM { return completion; } - async chat(messages: ChatMessage[], options: LLMFullCompletionOptions = {}) { + async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) { let completion = ""; - for await (const chunk of this.streamChat(messages, options)) { + for await (const chunk of this.streamChat(messages, signal, options)) { completion += chunk.content; } return { role: "assistant" as ChatMessageRole, content: completion }; @@ -572,6 +578,7 @@ export abstract class BaseLLM implements ILLM { async *streamChat( _messages: ChatMessage[], + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { const { completionOptions, log, raw } = @@ -597,6 +604,7 @@ export abstract class BaseLLM implements ILLM { if (this.templateMessages) { for await (const chunk of this._streamComplete( prompt, + signal, completionOptions, )) { completion += chunk; @@ -605,6 +613,7 @@ export abstract class BaseLLM implements ILLM { } else { for await (const chunk of this._streamChat( messages, + signal, completionOptions, )) { completion += chunk.content; @@ -633,6 +642,7 @@ export abstract class BaseLLM implements ILLM { // biome-ignore lint/correctness/useYield: Purposefully not implemented protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { throw new Error("Not implemented"); @@ -640,6 +650,7 @@ export abstract class BaseLLM implements ILLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (!this.templateMessages) { @@ -650,15 +661,16 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of this._streamComplete( this.templateMessages(messages), + signal, options, )) { yield { role: "assistant", content: chunk }; } } - protected async _complete(prompt: string, options: CompletionOptions) { + protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) { let completion = ""; - for await (const chunk of this._streamComplete(prompt, options)) { + for await (const chunk of this._streamComplete(prompt, signal, options)) { completion += chunk; } return completion; diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 8db42eefa..5033658c7 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -37,7 +37,9 @@ class Anthropic extends BaseLLM { public convertMessages(msgs: ChatMessage[]): any[] { // should be public for use within VertexAI - const filteredmessages = msgs.filter((m) => m.role !== "system"); + const filteredmessages = msgs.filter( + (m) => m.role !== "system" && !!m.content, + ); const lastTwoUserMsgIndices = filteredmessages .map((msg, index) => (msg.role === "user" ? index : -1)) .filter((index) => index !== -1) @@ -95,16 +97,18 @@ class Anthropic extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const shouldCacheSystemMessage = @@ -137,6 +141,7 @@ class Anthropic extends BaseLLM { ] : systemMessage, }), + signal }); if (options.stream === false) { @@ -146,7 +151,9 @@ class Anthropic extends BaseLLM { } for await (const value of streamSse(response)) { - if (value.type == "message_start") {console.log(value);} + if (value.type == "message_start") { + console.log(value); + } if (value.delta?.text) { yield { role: "assistant", content: value.delta.text }; } diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 85fb19184..74b1ddc27 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -98,6 +98,7 @@ class Asksage extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions ): Promise { if (typeof prompt !== "string" || prompt.trim() === "") { @@ -126,14 +127,16 @@ class Asksage extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions ): AsyncGenerator { - const completion = await this._complete(prompt, options); + const completion = await this._complete(prompt, signal, options); yield completion; } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions ): AsyncGenerator { const args = this._convertArgs(options, messages); @@ -142,6 +145,7 @@ class Asksage extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify(args), + signal }); if (!response.ok) { diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index 0daec0850..d563ca78e 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -5,6 +5,10 @@ import OpenAI from "./OpenAI.js"; class Azure extends OpenAI { static providerName: ModelProvider = "azure"; + protected supportsPrediction(model: string): boolean { + return false; + } + static defaultOptions: Partial = { apiVersion: "2024-02-15-preview", apiType: "azure", diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 67d8a4167..c2f76d0a8 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,6 +14,11 @@ import { import { stripImages } from "../images.js"; import { BaseLLM } from "../index.js"; +/** + * Bedrock class implements AWS Bedrock LLM integration. + * It handles streaming completions and chat messages using AWS Bedrock runtime. + * Supports both text and image inputs through Claude 3 models. + */ class Bedrock extends BaseLLM { static providerName: ModelProvider = "bedrock"; static defaultOptions: Partial = { @@ -37,16 +42,18 @@ class Bedrock extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -84,7 +91,7 @@ class Bedrock extends BaseLLM { const input = this._generateConverseInput(messages, options); const command = new ConverseStreamCommand(input); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal}); if (response.stream) { for await (const chunk of response.stream) { @@ -120,7 +127,9 @@ class Bedrock extends BaseLLM { // TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback. // For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes), // providing meaningful error messages to improve the user experience. - stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4), + stopSequences: options.stop + ?.filter((stop) => stop.trim() !== "") + .slice(0, 4), }, }; } @@ -162,7 +171,7 @@ class Bedrock extends BaseLLM { try { return await fromIni({ profile: this.profile, - ignoreCache: true + ignoreCache: true, })(); } catch (e) { console.warn( diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts index 44a57205e..5726cd91e 100644 --- a/core/llm/llms/BedrockImport.ts +++ b/core/llm/llms/BedrockImport.ts @@ -37,6 +37,7 @@ class BedrockImport extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -51,7 +52,7 @@ class BedrockImport extends BaseLLM { const input = this._generateInvokeModelCommandInput(prompt, options); const command = new InvokeModelWithResponseStreamCommand(input); - const response = await client.send(command); + const response = await client.send(command, {abortSignal: signal}); if (response.body) { for await (const item of response.body) { diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 93b9c4433..07e2e427c 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -16,6 +16,7 @@ export default class Cloudflare extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -35,6 +36,7 @@ export default class Cloudflare extends BaseLLM { model: this.model, ...this._convertArgs(options), }), + signal }); for await (const value of streamSse(resp)) { @@ -46,10 +48,12 @@ export default class Cloudflare extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 83f255904..98135c7cc 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -46,16 +46,18 @@ class Cohere extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -73,6 +75,7 @@ class Cohere extends BaseLLM { chat_history: this._convertMessages(messages), preamble: this.systemMessage, }), + signal }); if (options.stream === false) { diff --git a/core/llm/llms/CustomLLM.ts b/core/llm/llms/CustomLLM.ts index d35dfabde..81d038f9d 100644 --- a/core/llm/llms/CustomLLM.ts +++ b/core/llm/llms/CustomLLM.ts @@ -13,12 +13,14 @@ class CustomLLMClass extends BaseLLM { private customStreamCompletion?: ( prompt: string, + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; private customStreamChat?: ( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; @@ -31,18 +33,20 @@ class CustomLLMClass extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.customStreamChat) { for await (const content of this.customStreamChat( messages, + signal, options, (...args) => this.fetch(...args), )) { yield { role: "assistant", content }; } } else { - for await (const update of super._streamChat(messages, options)) { + for await (const update of super._streamChat(messages, signal, options)) { yield update; } } @@ -50,11 +54,13 @@ class CustomLLMClass extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.customStreamCompletion) { for await (const content of this.customStreamCompletion( prompt, + signal, options, (...args) => this.fetch(...args), )) { @@ -63,6 +69,7 @@ class CustomLLMClass extends BaseLLM { } else if (this.customStreamChat) { for await (const content of this.customStreamChat( [{ role: "user", content: prompt }], + signal, options, (...args) => this.fetch(...args), )) { diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index cfba34e85..177ac7efa 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -23,6 +23,7 @@ class Deepseek extends OpenAI { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("beta/completions", this.apiBase); @@ -45,6 +46,7 @@ class Deepseek extends OpenAI { Accept: "application/json", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].text; diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index 0d9e617a0..ecca89d16 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -121,16 +121,18 @@ class Flowise extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const message: ChatMessage = { role: "user", content: prompt }; - for await (const chunk of this._streamChat([message], options)) { + for await (const chunk of this._streamChat([message], signal, options)) { yield stripImages(chunk.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const requestBody = this._getRequestBody(messages, options); @@ -139,6 +141,7 @@ class Flowise extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), + signal }).then((res) => res.json()); while (await socketInfo.hasNextToken()) { diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 9f307d125..8f80c7418 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -60,6 +60,7 @@ class FreeTrial extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -73,6 +74,7 @@ class FreeTrial extends BaseLLM { prompt, ...args, }), + signal }); let completion = ""; @@ -103,6 +105,7 @@ class FreeTrial extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -120,6 +123,7 @@ class FreeTrial extends BaseLLM { messages: messages.map(this._convertMessage), ...args, }), + signal }); let completion = ""; @@ -140,6 +144,7 @@ class FreeTrial extends BaseLLM { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -153,6 +158,7 @@ class FreeTrial extends BaseLLM { suffix, ...args, }), + signal }); let completion = ""; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 2e33968d5..ada603240 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -46,10 +46,12 @@ class Gemini extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const message of this._streamChat( [{ content: prompt, role: "user" }], + signal, options, )) { yield stripImages(message.content); @@ -72,6 +74,7 @@ class Gemini extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { // Ensure this.apiBase is used if available, otherwise use default @@ -89,6 +92,7 @@ class Gemini extends BaseLLM { if (options.model.includes("gemini")) { for await (const message of this.streamChatGemini( convertedMsgs, + signal, options, )) { yield message; @@ -96,6 +100,7 @@ class Gemini extends BaseLLM { } else { for await (const message of this.streamChatBison( convertedMsgs, + signal, options, )) { yield message; @@ -118,6 +123,7 @@ class Gemini extends BaseLLM { private async *streamChatGemini( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const apiURL = new URL( @@ -159,6 +165,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); let buffer = ""; @@ -211,6 +218,7 @@ class Gemini extends BaseLLM { } private async *streamChatBison( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const msgList = []; @@ -226,6 +234,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); const data = await response.json(); yield { role: "assistant", content: data.candidates[0].content }; diff --git a/core/llm/llms/HuggingFaceInferenceAPI.ts b/core/llm/llms/HuggingFaceInferenceAPI.ts index 21b607163..7e8d11c56 100644 --- a/core/llm/llms/HuggingFaceInferenceAPI.ts +++ b/core/llm/llms/HuggingFaceInferenceAPI.ts @@ -16,6 +16,7 @@ class HuggingFaceInferenceAPI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (!this.apiBase) { @@ -36,6 +37,7 @@ class HuggingFaceInferenceAPI extends BaseLLM { stream: true, parameters: this._convertArgs(options), }), + signal }); async function* stream() { diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index 9636dbc63..df84083dc 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -48,6 +48,7 @@ class HuggingFaceTGI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(options, prompt); @@ -60,6 +61,7 @@ class HuggingFaceTGI extends BaseLLM { "Content-Type": "application/json", }, body: JSON.stringify({ inputs: prompt, parameters: args }), + signal }, ); diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts index e37b445e6..80ada3fdf 100644 --- a/core/llm/llms/LlamaCpp.ts +++ b/core/llm/llms/LlamaCpp.ts @@ -26,6 +26,7 @@ class LlamaCpp extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -42,6 +43,7 @@ class LlamaCpp extends BaseLLM { stream: true, ...this._convertArgs(options, prompt), }), + signal }); for await (const value of streamSse(resp)) { diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index e6097a60d..5f3880e3c 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -7,6 +7,7 @@ class Mock extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { yield this.completion; @@ -14,6 +15,7 @@ class Mock extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for (const char of this.completion) { diff --git a/core/llm/llms/Moonshot.ts b/core/llm/llms/Moonshot.ts new file mode 100644 index 000000000..5a015dcca --- /dev/null +++ b/core/llm/llms/Moonshot.ts @@ -0,0 +1,61 @@ +import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; +import { streamSse } from "../stream.js"; +import { osModelsEditPrompt } from "../templates/edit.js"; + +import OpenAI from "./OpenAI.js"; + +class Moonshot extends OpenAI { + static providerName: ModelProvider = "moonshot"; + static defaultOptions: Partial = { + apiBase: "https://api.moonshot.cn/v1/", + model: "moonshot-v1-8k", + promptTemplates: { + edit: osModelsEditPrompt, + }, + useLegacyCompletionsEndpoint: false, + }; + maxStopWords: number | undefined = 16; + + supportsFim(): boolean { + return true; + } + + async *_streamFim( + prefix: string, + suffix: string, + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + const endpoint = new URL("v1/chat/completions", this.apiBase); + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + messages: [ + { + role: "user", + content: prefix + "[fill]" + suffix, + }, + ], + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + signal + }); + for await (const chunk of streamSse(resp)) { + yield chunk.choices[0].delta.content; + } + } +} + +export default Moonshot; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index a9ac7ab75..dcaa078ba 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -30,7 +30,7 @@ interface ModelFileParams { min_p?: number; // deprecated? num_thread?: number; - use_mmap?: boolean; + use_mmap?: boolean; num_gqa?: number; num_gpu?: number; } @@ -77,7 +77,6 @@ class Ollama extends BaseLLM { if (options.model === "AUTODETECT") { return; } - this.fetch(this.getEndpoint("api/show"), { method: "POST", headers: { @@ -262,6 +261,7 @@ class Ollama extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const response = await this.fetch(this.getEndpoint("api/generate"), { @@ -271,6 +271,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prompt)), + signal }); let buffer = ""; @@ -301,6 +302,7 @@ class Ollama extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const response = await this.fetch(this.getEndpoint("api/chat"), { @@ -310,6 +312,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getChatOptions(options, messages)), + signal }); let buffer = ""; @@ -348,8 +351,10 @@ class Ollama extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { + const response = await this.fetch(this.getEndpoint("api/generate"), { method: "POST", headers: { @@ -357,6 +362,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)), + signal }); let buffer = ""; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 168e0afff..36abb746d 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -95,11 +95,8 @@ class OpenAI extends BaseLLM { ); } - private supportsPrediction(model: string): boolean { - return [ - "gpt-4o-mini", - "gpt-4o" - ].includes(model); + protected supportsPrediction(model: string): boolean { + return ["gpt-4o-mini", "gpt-4o"].includes(model); } protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { @@ -120,9 +117,9 @@ class OpenAI extends BaseLLM { : url.host === "api.deepseek.com" ? options.stop?.slice(0, 16) : url.port === "1337" || - url.host === "api.openai.com" || - url.host === "api.groq.com" || - this.apiType === "azure" + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" ? options.stop?.slice(0, 4) : options.stop, }; @@ -143,10 +140,12 @@ class OpenAI extends BaseLLM { } if (options.prediction && this.supportsPrediction(options.model)) { - if (finalOptions.presence_penalty) { // prediction doesn't support > 0 + if (finalOptions.presence_penalty) { + // prediction doesn't support > 0 finalOptions.presence_penalty = undefined; } - if (finalOptions.frequency_penalty) { // prediction doesn't support > 0 + if (finalOptions.frequency_penalty) { + // prediction doesn't support > 0 finalOptions.frequency_penalty = undefined; } finalOptions.max_completion_tokens = undefined; @@ -167,11 +166,13 @@ class OpenAI extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { let completion = ""; for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { completion += chunk.content; @@ -200,10 +201,12 @@ class OpenAI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); @@ -212,6 +215,7 @@ class OpenAI extends BaseLLM { protected async *_legacystreamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args: any = this._convertArgs(options, []); @@ -225,6 +229,7 @@ class OpenAI extends BaseLLM { ...args, stream: true, }), + signal }); for await (const value of streamSse(response)) { @@ -236,6 +241,7 @@ class OpenAI extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if ( @@ -247,6 +253,7 @@ class OpenAI extends BaseLLM { ) { for await (const content of this._legacystreamComplete( stripImages(messages[messages.length - 1]?.content || ""), + signal, options, )) { yield { @@ -267,6 +274,7 @@ class OpenAI extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify(body), + signal }); // Handle non-streaming response @@ -286,6 +294,7 @@ class OpenAI extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("fim/completions", this.apiBase); @@ -309,6 +318,7 @@ class OpenAI extends BaseLLM { "x-api-key": this.apiKey ?? "", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].delta.content; diff --git a/core/llm/llms/Replicate.ts b/core/llm/llms/Replicate.ts index 414975ac4..59994cec1 100644 --- a/core/llm/llms/Replicate.ts +++ b/core/llm/llms/Replicate.ts @@ -41,11 +41,13 @@ class Replicate extends BaseLLM { private _convertArgs( options: CompletionOptions, prompt: string, - ): [`${string}/${string}:${string}`, { input: any }] { + signal: AbortSignal + ): [`${string}/${string}:${string}`, { input: any, signal: AbortSignal }] { return [ Replicate.MODEL_IDS[options.model] || (options.model as any), { input: { prompt, message: prompt }, + signal }, ]; } @@ -57,9 +59,10 @@ class Replicate extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { - const [model, args] = this._convertArgs(options, prompt); + const [model, args] = this._convertArgs(options, prompt, signal); const response = await this._replicate.run(model, args); return (response as any)[0]; @@ -67,9 +70,10 @@ class Replicate extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const [model, args] = this._convertArgs(options, prompt); + const [model, args] = this._convertArgs(options, prompt, signal); for await (const event of this._replicate.stream(model, args)) { if (event.event === "output") { yield event.data; diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index c88261941..edbda4d34 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -32,6 +32,7 @@ class SageMaker extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -45,7 +46,7 @@ class SageMaker extends BaseLLM { }); const toolkit = new CompletionAPIToolkit(this); const command = toolkit.generateCommand([], prompt, options); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal }); if (response.Body) { let buffer = ""; for await (const rawValue of response.Body) { @@ -82,6 +83,7 @@ class SageMaker extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -96,7 +98,7 @@ class SageMaker extends BaseLLM { const toolkit = new MessageAPIToolkit(this); const command = toolkit.generateCommand(messages, "", options); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal }); if (response.Body) { let buffer = ""; for await (const rawValue of response.Body) { diff --git a/core/llm/llms/Together.ts b/core/llm/llms/Together.ts index f5b5f0bac..b0044c4a8 100644 --- a/core/llm/llms/Together.ts +++ b/core/llm/llms/Together.ts @@ -41,9 +41,10 @@ class Together extends OpenAI { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - for await (const chunk of this._legacystreamComplete(prompt, options)) { + for await (const chunk of this._legacystreamComplete(prompt,signal, options)) { yield chunk; } } diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index e945831e6..c17aac90d 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -49,7 +49,7 @@ class VertexAI extends BaseLLM { "unknown"; this.anthropicInstance = new Anthropic(_options); this.geminiInstance = new Gemini(_options); - + } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -307,6 +307,7 @@ class VertexAI extends BaseLLM { protected async *StreamFimMistral( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const apiBase = this.apiBase!; @@ -329,6 +330,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); for await (const chunk of streamSse(response)) { @@ -342,6 +344,7 @@ class VertexAI extends BaseLLM { protected async *streamFimGecko( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase); @@ -363,6 +366,7 @@ class VertexAI extends BaseLLM { } }), + signal }); // Streaming is not supported by code-gecko // TODO: convert to non-streaming fim method when one exist in continue. @@ -373,6 +377,7 @@ class VertexAI extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const isV1API = this.apiBase.includes("/v1/"); @@ -396,10 +401,12 @@ class VertexAI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const message of this._streamChat( [{ content: prompt, role: "user" }], + signal, options, )) { yield stripImages(message.content); @@ -409,15 +416,16 @@ class VertexAI extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.model === "code-gecko") { - yield* this.streamFimGecko(prefix, suffix, options); + yield* this.streamFimGecko(prefix, suffix, signal, options); } else if (this.model.includes("codestral")) { - yield* this.StreamFimMistral(prefix, suffix, options); + yield* this.StreamFimMistral(prefix, suffix, signal, options); } else { throw new Error(`Unsupported model: ${this.model}`); } diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 89a2d13dc..808557692 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -140,11 +140,13 @@ class WatsonX extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { let completion = ""; for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { completion += chunk.content; @@ -155,10 +157,12 @@ class WatsonX extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); @@ -167,6 +171,7 @@ class WatsonX extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { var now = new Date().getTime() / 1000; @@ -219,6 +224,7 @@ class WatsonX extends BaseLLM { method: "POST", headers: headers, body: JSON.stringify(payload), + signal }); if (!response.ok || response.body === null) { diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 48088dc34..121f0f46d 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -31,6 +31,7 @@ import Llamafile from "./Llamafile"; import LMStudio from "./LMStudio"; import Mistral from "./Mistral"; import Mock from "./Mock"; +import Moonshot from "./Moonshot"; import Msty from "./Msty"; import Nebius from "./Nebius"; import Nvidia from "./Nvidia"; @@ -54,6 +55,7 @@ const LLMs = [ FreeTrial, Gemini, Llamafile, + Moonshot, Ollama, Replicate, TextGenWebUI, diff --git a/core/package-lock.json b/core/package-lock.json index e817a7c6f..09e22ce96 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -6827,9 +6827,9 @@ } }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index 4b77360fe..9e4f0c194 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -90,7 +90,7 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages)) { + for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 515578417..102c470f5 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -7,7 +7,9 @@ import type { ContextItemWithId, ContextSubmenuItem, DiffLine, + FileSymbolMap, IdeSettings, + IndexingStatusMap, LLMFullCompletionOptions, MessageContent, ModelDescription, @@ -77,6 +79,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ContextItemWithId[], ]; + "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap]; "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; "context/addDocs": [SiteIndexingConfig, void]; @@ -143,6 +146,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { { model: string; promptTokens: number; generatedTokens: number }[], ]; "tts/kill": [undefined, void]; + + // Codebase indexing "index/setPaused": [boolean, void]; "index/forceReIndex": [ undefined | { dirs?: string[]; shouldClearIndexes?: boolean }, @@ -156,6 +161,13 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + + // Docs etc. Indexing. TODO move codebase to this + "indexing/reindex": [{ type: string; id: string }, void]; + "indexing/abort": [{ type: string; id: string }, void]; + "indexing/setPaused": [{ type: string; id: string; paused: boolean }, void]; + "indexing/initStatuses": [undefined, void]; + addAutocompleteModel: [{ model: ModelDescription }, void]; "profiles/switch": [{ id: string }, undefined]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index e3f507464..1d18e1a6f 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -27,6 +27,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { }, void, ]; + overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; toggleDevTools: [undefined, void]; @@ -39,8 +40,8 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { "jetbrains/isOSREnabled": [undefined, void]; "vscode/openMoveRightMarkdown": [undefined, void]; setGitHubAuthToken: [{ token: string }, void]; - acceptDiff: [{ filepath: string }, void]; - rejectDiff: [{ filepath: string }, void]; + acceptDiff: [{ filepath: string; streamId?: string }, void]; + rejectDiff: [{ filepath: string; streamId?: string }, void]; "edit/sendPrompt": [ { prompt: MessageContent; range: RangeInFileWithContents }, void, @@ -63,11 +64,17 @@ export type EditStatus = | "accepting:full-diff" | "done"; +export type ApplyStateStatus = + | "streaming" // Changes are being applied to the file + | "done" // All changes have been applied, awaiting user to accept/reject + | "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed" + export interface ApplyState { streamId: string; - status?: "streaming" | "done" | "closed"; + status?: ApplyStateStatus; numDiffs?: number; filepath?: string; + fileContent?: string; } export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 3ade98cf4..052e91264 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -24,6 +24,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/listProfiles", "config/openLocalConfigFile", "context/getContextItems", + "context/getSymbolsForFiles", "context/loadSubmenuItems", "context/addDocs", "context/removeDocs", @@ -41,10 +42,17 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "chatDescriber/describe", "stats/getTokensPerDay", "stats/getTokensPerModel", + // Codebase "index/setPaused", "index/forceReIndex", "index/forceReIndexFiles", "index/indexingProgressBarInitialized", + // Docs, etc. + "indexing/initStatuses", + "indexing/reindex", + "indexing/abort", + "indexing/setPaused", + // "completeOnboarding", "addAutocompleteModel", "profiles/switch", @@ -56,7 +64,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", "getDefaultModelTitle", - "indexProgress", + "indexProgress", // Codebase + "indexing/statusUpdate", // Docs, etc. "addContextItem", "refreshSubmenuItems", "isContinueInputFocused", diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 8d8da683b..5790ae863 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,13 +1,18 @@ import { ConfigValidationError } from "../config/validation.js"; -import type { ContextItemWithId, IndexingProgressUpdate } from "../index.js"; +import type { + ContextItemWithId, + IndexingProgressUpdate, + IndexingStatus, +} from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { configUpdate: [undefined, void]; configError: [ConfigValidationError[] | undefined, void]; openSelectedConfigProfile: [undefined, void]; getDefaultModelTitle: [undefined, string]; - indexProgress: [IndexingProgressUpdate, void]; + indexProgress: [IndexingProgressUpdate, void]; // Codebase + "indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc. refreshSubmenuItems: [undefined, void]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 5f3d1bdc1..b8ca609a2 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -52,6 +52,7 @@ export class ChatDescriber { content: ChatDescriber.prompt + message, }, ], + new AbortController().signal, completionOptions, ); diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 7a94abc03..269f3489e 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -11,8 +11,8 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { multilineCompletions: "auto", slidingWindowPrefixPercentage: 0.75, slidingWindowSize: 500, - maxSnippetPercentage: 0.6, - recentlyEditedSimilarityThreshold: 0.0, // Effectively no threshold. + maxSnippetPercentage: 0.5, + maxDiffPercentage: 0.5, useCache: true, onlyMyCode: true, useOtherFiles: true, diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 9118b80ee..22a59e85c 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -2,6 +2,7 @@ import fs from "node:fs"; import * as path from "node:path"; import Parser, { Language } from "web-tree-sitter"; +import { FileSymbolMap, IDE, SymbolWithRange } from ".."; export enum LanguageName { CPP = "cpp", @@ -205,3 +206,93 @@ async function loadLanguageForFileExt( ); return await Parser.Language.load(wasmPath); } + +// See https://tree-sitter.github.io/tree-sitter/using-parsers +const GET_SYMBOLS_FOR_NODE_TYPES: Parser.SyntaxNode["type"][] = [ + "class_declaration", + "class_definition", + "function_item", // function name = first "identifier" child + "function_definition", + "method_declaration", // method name = first "identifier" child + "method_definition", + "generator_function_declaration", + // property_identifier + // field_declaration + // "arrow_function", +]; + +export async function getSymbolsForFile( + filepath: string, + contents: string, +): Promise { + const parser = await getParserForFile(filepath); + + if (!parser) { + return; + } + + const tree = parser.parse(contents); + // console.log(`file: ${filepath}`); + + // Function to recursively find all named nodes (classes and functions) + const symbols: SymbolWithRange[] = []; + function findNamedNodesRecursive(node: Parser.SyntaxNode) { + // console.log(`node: ${node.type}, ${node.text}`); + if (GET_SYMBOLS_FOR_NODE_TYPES.includes(node.type)) { + // console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`); + // node.children.forEach((child) => { + // console.log(`child: ${child.type}, ${child.text}`); + // }); + + // Empirically, the actual name is the last identifier in the node + // Especially with languages where return type is declared before the name + // TODO use findLast in newer version of node target + let identifier: Parser.SyntaxNode | undefined = undefined; + for (let i = node.children.length - 1; i >= 0; i--) { + if ( + node.children[i].type === "identifier" || + node.children[i].type === "property_identifier" + ) { + identifier = node.children[i]; + break; + } + } + + if (identifier?.text) { + symbols.push({ + filepath, + type: node.type, + name: identifier.text, + range: { + start: { + character: node.startPosition.column, + line: node.startPosition.row, + }, + end: { + character: node.endPosition.column + 1, + line: node.endPosition.row + 1, + }, + }, + }); + } + } + node.children.forEach(findNamedNodesRecursive); + } + findNamedNodesRecursive(tree.rootNode); + + return symbols; +} + +export async function getSymbolsForManyFiles( + uris: string[], + ide: IDE, +): Promise { + const filesAndSymbols = await Promise.all( + uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => { + const contents = await ide.readFile(uri); + const symbols = await getSymbolsForFile(uri, contents); + return [uri, symbols ?? []]; + }), + ); + return Object.fromEntries(filesAndSymbols); +} diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index e582beb1b..a423ff4dc 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -291,7 +291,7 @@ Reference the conversation in a Jira issue. "name": "jira", "params": { "domain": "company.atlassian.net", - "token ": "ATATT..." + "token": "ATATT..." } } ] diff --git a/docs/docs/customize/model-providers/moonshot.md b/docs/docs/customize/model-providers/moonshot.md new file mode 100644 index 000000000..64017d1bd --- /dev/null +++ b/docs/docs/customize/model-providers/moonshot.md @@ -0,0 +1,60 @@ +# Moonshot + +[Moonshot AI](https://platform.moonshot.cn/) provides high-quality large language model services with competitive pricing and excellent performance. + +## Configuration + +To use Moonshot AI models, you need to: + +1. Get an API key from [Moonshot AI Platform](https://platform.moonshot.cn/) +2. Add the following configuration to your `config.json`: + +```json +{ + "models": [ + { + "title": "Moonshot", + "provider": "moonshot", + "model": "moonshot-v1-8k", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +## Available Models + +Moonshot AI currently provides the following models: + +- `moonshot-v1-8k`: Base model with 8K context window +- `moonshot-v1-32k`: Base model with 32K context window +- `moonshot-v1-128k`: Base model with 128K context window + +## Configuration Options + +| Option | Description | Default | +|--------|-------------|---------| +| `apiKey` | Moonshot API key | Required | +| `apiBase` | API base URL | `https://api.moonshot.cn/v1/` | +| `model` | Model name to use | `moonshot-v1-8k` | + +## Example + +Here's a complete configuration example: + +```json +{ + "models": [ + { + "title": "Moonshot-8K", + "provider": "moonshot", + "model": "moonshot-v1-8k", + "apiKey": "YOUR_API_KEY", + "completionOptions": { + "temperature": 0.7, + "topP": 0.95, + "maxTokens": 2048 + } + } + ] +} diff --git a/docs/docs/customize/model-providers/top-level/vertexai.md b/docs/docs/customize/model-providers/top-level/vertexai.md index 1778ce3c6..50958cae0 100644 --- a/docs/docs/customize/model-providers/top-level/vertexai.md +++ b/docs/docs/customize/model-providers/top-level/vertexai.md @@ -27,7 +27,6 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. } ``` - ## Autocomplete model We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. @@ -43,6 +42,7 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo } } ``` + ## Embeddings model We recommend configuring **text-embedding-004** as your embeddings model. diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 09dd150a6..f39e68998 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -1,5 +1,5 @@ --- -title: Reference +title: config.json Reference description: Reference for the Continue _config.json_ configuration file keywords: [config, config_schema.json, json] --- diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md index 940fedc65..095d75918 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md @@ -7,7 +7,7 @@ sidebar_position: 5 ## 内置的斜杠命令 -Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../customize/config.mdx) 并添加它们到 `slashCommands` 列表中。 +Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../reference.md) 并添加它们到 `slashCommands` 列表中。 ## 定制斜杠命令 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md index 5e7b8fad2..aa2a04d5f 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md @@ -5,7 +5,7 @@ keywords: [定制] sidebar_position: 5 --- -Continue 在 [`config.json`](../customize/config.mdx) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: +Continue 在 [`config.json`](../reference.md) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: ```json title="config.json" "tabAutocompleteOptions": { diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx index fe24f18fb..b95d976f1 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx @@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; :::info -这个页面推荐聊天的模型和提供者。在 [这里](../customize/config.mdx) 了解更多关于如何设置你的 `config.json` 。 +这个页面推荐聊天的模型和提供者。在 [这里](../reference.md) 了解更多关于如何设置你的 `config.json` 。 ::: ## 最好的总体体验 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md index ea07525ee..b85cfe323 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md @@ -44,7 +44,7 @@ ollama run starcoder2:3b } ``` -如果你对可用选项不熟悉,你可以在 [这里](../config.mdx) 查找完整的参考。 +如果你对可用选项不熟悉,你可以在 [这里](../../reference.md) 查找完整的参考。 ## 配置选项 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md new file mode 100644 index 000000000..049ff7754 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md @@ -0,0 +1,52 @@ +--- +title: NVIDIA +--- + +:::info + +[View the docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) to learn how to get an API key. + +::: + +## Chat model + +We recommend configuring **Nemotron-4-340B-Instruct** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Nemotron-4-340B-Instruct", + "provider": "nvidia", + "model": "nvidia-nemotron-4-340b-instruct", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +NVIDIA currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "nvidia", + "model": "nvidia/nv-embedqa-mistral-7b-v2", + "apiKey": "[API_KEY]" + } +} +``` + +## Reranking model + +NVIDIA currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md new file mode 100644 index 000000000..daf966d9e --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md @@ -0,0 +1,65 @@ +--- +title: Vertex AI +slug: ../vertexai +--- + +:::info + +You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc). + +::: + +## Chat model + +We recommend configuring **Claude 3.5 Sonnet** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "vertexai", + "model": "claude-3-5-sonnet-20240620", + "projectId": "[PROJECT_ID]", + "region": "us-east5" + } + ] +} +``` + +## Autocomplete model + +We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Codestral (Vertex AI)", + "provider": "vertexai", + "model": "codestral", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } +} +``` + +## Embeddings model + +We recommend configuring **text-embedding-004** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "vertexai", + "model": "text-embedding-004", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } +} +``` + +## Reranking model + + diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md new file mode 100644 index 000000000..fbdfa83ad --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md @@ -0,0 +1,53 @@ +--- +title: xAI +slug: ../xai +--- + +:::info + +You can get an API key from the [xAI console](https://console.x.ai/) + +::: + +## Chat model + +We recommend configuring **grok-beta** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Grok Beta", + "provider": "xAI", + "model": "grok-beta", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +xAI currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +xAI currently does not offer any embeddings models. + +[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. + +## Reranking model + +xAI currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. + +## Legacy Completions + +To force usage of `chat/completions` instead of `completions` endpoint you can set + +```json +"useLegacyCompletionsEndpoint": false +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md index 784c0bd59..f95574dae 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md @@ -8,13 +8,13 @@ Continue 可以深度定制。这个主要通过编辑位于 `~/.continue/config ## 开始 -要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](./config.mdx) 。 +要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](../reference.md) 。 当你保存 `config.json` 时, Continue 会自动地刷新,应用你的变更。 ## 每个工作区的配置 -如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](./config.mdx) ,会自动地应用到本地 `config.json` 之上。 +如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](../reference.md) ,会自动地应用到本地 `config.json` 之上。 ## 可编程的配置 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md index f96a8fe6d..07a0a6c65 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md @@ -5,6 +5,6 @@ description: 如何设置一个编辑模型 keywords: [编辑, cmd l, 模型] --- -默认情况下,编辑使用 [与聊天相同的模型](chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 +默认情况下,编辑使用 [与聊天相同的模型](../chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 -你可以通过更新你的 [`config.json`](../customize/config.mdx) 为编辑配置一个不同的模型。 +你可以通过更新你的 [`config.json`](../reference.md) 为编辑配置一个不同的模型。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md new file mode 100644 index 000000000..09dd150a6 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md @@ -0,0 +1,446 @@ +--- +title: Reference +description: Reference for the Continue _config.json_ configuration file +keywords: [config, config_schema.json, json] +--- + +Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). + +**All properties at all levels are optional unless explicitly marked required** + +### `models` + +Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Actions](./actions/how-to-use-it.md). +Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. + +**Properties:** + +- `title` (**required**): The title to assign to your model, shown in dropdowns, etc. +- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, etc., see intelliJ suggestions. +- `model` (**required**): The name of the model, used for prompt template auto-detection. +- `apiKey`: API key required by providers like OpenAI, Anthropic, and Cohere. +- `apiBase`: The base URL of the LLM API. +- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048). +- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. +- `template`: Chat template to format messages. Auto-detected for most models but can be overridden. See intelliJ suggestions. +- `promptTemplates`: A mapping of prompt template names (e.g., `edit`) to template strings. [Customization Guide](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt). +- `completionOptions`: Model-specific completion options, same format as top-level [`completionOptions`](#completionoptions), which they override. +- `systemMessage`: A system message that will precede responses from the LLM. +- `requestOptions`: Model-specific HTTP request options, same format as top-level [`requestOptions`](#requestoptions), which they override. +- `apiType`: Specifies the type of API (`openai` or `azure`). +- `apiVersion`: Azure API version (e.g., `2023-07-01-preview`). +- `engine`: Engine for Azure OpenAI requests. +- `capabilities`: Override auto-detected capabilities: + - `uploadImage`: Boolean indicating if the model supports image uploads. + +_(AWS Only)_ + +- `profile`: AWS security profile for authorization. +- `modelArn`: AWS ARN for imported models (e.g., for `bedrockimport` provider). +- `region`: Region where the model is hosted (e.g., `us-east-1`, `eu-central-1`). + +Example: + +```json title="config.json" +{ + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "AUTODETECT" + }, + { + "model": "gpt-4o", + "contextLength": 128000, + "title": "GPT-4o", + "provider": "openai", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +### `tabAutocompleteModel` + +Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model. + +Example + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "My Starcoder", + "provider": "ollama", + "model": "starcoder2:3b" + } +} +``` + +### `tabAutocompleteOptions` + +Specifies options for tab autocompletion behavior. + +**Properties:** + +- `disable`: If `true`, disables tab autocomplete (default: `false`). +- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt. +- `useFileSuffix`: If `true`, includes file suffix in the prompt. +- `maxPromptTokens`: Maximum number of tokens for the prompt. +- `debounceDelay`: Delay (in ms) before triggering autocomplete. +- `maxSuffixPercentage`: Maximum percentage of prompt for suffix. +- `prefixPercentage`: Percentage of input for prefix. +- `template`: Template string for autocomplete, using Mustache templating. +- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). +- `useCache`: If `true`, caches completions. +- `onlyMyCode`: If `true`, only includes code within the repository. +- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`). +- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. + +Example + +```json title="config.json" +{ + "tabAutocompleteOptions": { + "debounceDelay": 500, + "maxPromptTokens": 1500, + "disableInFiles": ["*.md"] + } +} +``` + +### `embeddingsProvider` + +Embeddings model settings - the model used for @Codebase and @docs. + +**Properties:** + +- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `free-trial`, `gemini`, etc +- `model`: Model name for embeddings. +- `apiKey`: API key for the provider. +- `apiBase`: Base URL for API requests. +- `requestOptions`: Additional HTTP request settings specific to the embeddings provider. +- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. +- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. + +(AWS ONLY) + +- `region`: Specifies the region hosting the model. +- `profile`: AWS security profile. + +Example: + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "openai", + "model": "text-embedding-ada-002", + "apiKey": "", + "maxChunkSize": 256, + "maxBatchSize": 5 + } +} +``` + +### `completionOptions` + +Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_. + +**Properties:** + +- `stream`: Whether to stream the LLM response. Currently only respected by the `anthropic` and `ollama` providers; other providers will always stream (default: `true`). +- `temperature`: Controls the randomness of the completion. Higher values result in more diverse outputs. +- `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass. +- `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability. +- `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output. +- `frequencePenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. +- `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0). +- `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions. +- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). +- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`. +- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). +- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. + +Example + +```json title="config.json" +{ + "completionOptions": { + "stream": false, + "temperature": 0.5 + } +} +``` + +### `requestOptions` + +Default HTTP request options that apply to all models and context providers, unless overridden at the model level. + +**Properties:** + +- `timeout`: Timeout for each request to the LLM (default: 7200 seconds). +- `verifySsl`: Whether to verify SSL certificates for requests. +- `caBundlePath`: Path to a custom CA bundle for HTTP requests - path to `.pem` file (or array of paths) +- `proxy`: Proxy URL to use for HTTP requests. +- `headers`: Custom headers for HTTP requests. +- `extraBodyProperties`: Additional properties to merge with the HTTP request body. +- `noProxy`: List of hostnames that should bypass the specified proxy. +- `clientCertificate`: Client certificate for HTTP requests. + + - `cert`: Path to the client certificate file. + - `key`: Path to the client certificate key file. + - `passphrase`: Optional passphrase for the client certificate key file. + +Example + +```json title="config.json" +{ + "requestOptions": { + "headers": { + "X-Auth-Token": "xxx" + } + } +} +``` + +### `reranker` + +Configuration for the reranker model used in response ranking. + +**Properties:** + +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei` +- `params`: + - `model`: Model name + - `apiKey`: Api key + +Example + +```json title="config.json" +{ + "reranker": { + "name": "voyage", + "params": { + "model": "rerank-2", + "apiKey": "" + } + } +} +``` + +### `docs` + +List of documentation sites to index. + +**Properties:** + +- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. +- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs +- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL +- `maxDepth`: Maximum depth for crawling. Default `3` +- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). + +Example + +```json title="config.json" +"docs": [ + { + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "rootUrl": "https://docs.continue.dev", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + } +] +``` + +### `analytics` + +Configuration for analytics tracking. + +**Properties:** + +- `provider`: Analytics provider (`"posthog"` or `"logstash"`). +- `url`: URL for analytics data. +- `clientKey`: Client key for analytics. + +### `slashCommands` + +Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined. + +**Properties:** + +- `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review". +- `description`: Brief description of the command. +- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. +- `params`: Additional parameters to configure command behavior (command-specific - see code for command) + +Example: + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "commit", + "description": "Generate a commit message" + }, + { + "name": "share", + "description": "Export this session as markdown" + }, + { + "name": "cmd", + "description": "Generate a shell command" + } + ] +} +``` + +### `customCommands` + +User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. + +**Properties:** + +- `name`: The name of the custom command. +- `prompt`: Text prompt for the command. +- `description`: Brief description explaining the command's function. + +Example: + +```json title="config.json" +{ + "customCommands": [ + { + "name": "test", + "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", + "description": "Write unit tests for highlighted code" + } + ] +} +``` + +### `contextProviders` + +List of the pre-defined context providers that will show up as options while typing in the chat, and their customization with `params`. + +**Properties:** + +- `name`: Name of the context provider, e.g. `docs` or `web` +- `params`: A context-provider-specific record of params to configure the context behavior + +Example + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "code", + "params": {} + }, + { + "name": "docs", + "params": {} + }, + { + "name": "diff", + "params": {} + }, + { + "name": "open", + "params": {} + } + ] +} +``` + +### `disableSessionTitles` + +Prevents generating summary titles for each chat session when set to `true`. + +### `ui` + +Customizable UI settings to control interface appearance and behavior. + +**Properties:** + +- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`. +- `fontSize`: Specifies font size for UI elements. +- `displayRawMarkdown`: If `true`, shows raw markdown in responses. +- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. + +Example: + +```json title="config.json" +{ + "ui": { + "codeBlockToolbarPosition": "bottom", + "fontSize": 14, + "displayRawMarkdown": false + } +} +``` + +### `allowAnonymousTelemetry` + +When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`. + +### `userToken` + +An optional token that identifies the user, primarily for authenticated services. + +### `systemMessage` + +Defines a system message that appears before every response from the language model, providing guidance or context. + +### `disableIndexing` + +Prevents indexing of the codebase, useful primarily for debugging purposes. + +### `experimental` + +Several experimental config parameters are available, as described below: + +`experimental`: + +- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.= +- `modelRoles`: + - `inlineEdit`: Model title for inline edits. + - `applyCodeBlock`: Model title for applying code blocks. + - `repoMapFileSelection`: Model title for repo map selections. +- `readResponseTTS`: If `true`, reads LLM responses aloud with TTS. Default is `true`. +- `promptPath`: Change the path to custom prompt files from the default ".prompts" +- `quickActions`: Array of custom quick actions + - `title` (**required**): Display title for the quick action. + - `prompt` (**required**): Prompt for quick action. + - `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`. +- `contextMenuPrompts`: + - `comment`: Prompt for commenting code. + - `docstring`: Prompt for adding docstrings. + - `fix`: Prompt for fixing code. + - `optimize`: Prompt for optimizing code. + - `fixGrammar`: Prompt for fixing grammar or spelling. +- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.. + +Example + +```json title="config.json" +{ + "experimental": { + "modelRoles": { + "inlineEdit": "Edit Model" + }, + "promptPath": "custom/.prompts", + "quickActions": [ + { + "title": "Tags", + "prompt": "Return a list of any function and class names from the included code block", + "sendToChat": true + } + ], + "contextMenuPrompts": { + "fixGrammar": "Fix grammar in the above but allow for typos." + }, + "readResponseTTS": false, + "useChromiumForDocsCrawling": true + } +} +``` diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index eb75d1f90..7edceced4 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -205,7 +205,8 @@ "nebius", "vertexai", "xAI", - "kindo" + "kindo", + "moonshot" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -242,7 +243,8 @@ "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)", "### xAI offers a world class developer tool set to build scalable applications powered by Grok. To get started, obtain an API key from [the x Console](https://console.x.ai/), and see the [docs](https://docs.x.ai/docs/)", - "### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)" + "### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)", + "### Moonshot\nTo get started with Moonshot AI, obtain your API key from [Moonshot AI](https://platform.moonshot.cn/). Moonshot AI provides high-quality large language models with competitive pricing.\n> [Reference](https://platform.moonshot.cn/docs/api)" ], "type": "string" }, @@ -1147,6 +1149,35 @@ "required": ["projectId", "region"] } }, + { + "if": { + "properties": { + "provider": { + "enum": ["moonshot"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": [ + "moonshot-v1-8k", + "moonshot-v1-32k", + "moonshot-v1-128k", + "AUTODETECT" + ] + }, + { + "type": "string" + } + ] + } + } + } + }, { "if": { "properties": { @@ -2325,7 +2356,7 @@ "type": "integer", "description": "The maximum depth to crawl the documentation site" }, - "favicon": { + "faviconUrl": { "type": "string", "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" } diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 356d38601..872d68bb6 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.231", + "version": "0.9.232", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -390,11 +390,6 @@ "mac": "alt+cmd+n", "key": "alt+ctrl+n" }, - { - "command": "continue.quickEdit", - "mac": "cmd+shift+i", - "key": "ctrl+shift+i" - }, { "command": "continue.edit", "mac": "cmd+i", @@ -437,9 +432,6 @@ ], "menus": { "commandPalette": [ - { - "command": "continue.quickEdit" - }, { "command": "continue.focusContinueInput" }, diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index bf29f665f..0add86dae 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -271,7 +271,10 @@ const commandsMap: ( } return { - "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + "continue.acceptDiff": async ( + newFilepath?: string | vscode.Uri, + streamId?: string, + ) => { captureCommandTelemetry("acceptDiff"); let fullPath = newFilepath; @@ -290,8 +293,23 @@ const commandsMap: ( void sidebar.webviewProtocol.request("setEditStatus", { status: "done", }); + + if (streamId && fullPath) { + const fileContent = await ide.readFile(fullPath); + + await sidebar.webviewProtocol.request("updateApplyState", { + fileContent, + filepath: fullPath, + streamId: streamId, + status: "closed", + numDiffs: 0, + }); + } }, - "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + "continue.rejectDiff": async ( + newFilepath?: string | vscode.Uri, + streamId?: string, + ) => { captureCommandTelemetry("rejectDiff"); let fullPath = newFilepath; @@ -309,6 +327,18 @@ const commandsMap: ( void sidebar.webviewProtocol.request("setEditStatus", { status: "done", }); + + if (streamId && fullPath) { + const fileContent = await ide.readFile(fullPath); + + await sidebar.webviewProtocol.request("updateApplyState", { + fileContent, + filepath: fullPath, + streamId: streamId, + status: "closed", + numDiffs: 0, + }); + } }, "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { captureCommandTelemetry("acceptVerticalDiffBlock"); @@ -735,7 +765,7 @@ const commandsMap: ( !selected || !autocompleteModels.some((model) => model.title === selected) ) { - selected = autocompleteModels[0].title; + selected = autocompleteModels[0]?.title; } // Toggle between Disabled, Paused, and Enabled diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index f2bf20ef6..3286749a6 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -18,6 +18,7 @@ export interface VerticalDiffHandlerOptions { onStatusUpdate: ( status?: ApplyState["status"], numDiffs?: ApplyState["numDiffs"], + fileContent?: ApplyState["fileContent"], ) => void; } @@ -271,6 +272,7 @@ export class VerticalDiffHandler implements vscode.Disposable { this.options.onStatusUpdate( "closed", this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0, + this.editor.document.getText(), ); this.cancelled = true; @@ -362,6 +364,7 @@ export class VerticalDiffHandler implements vscode.Disposable { this.options.onStatusUpdate( "done", this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0, + this.editor.document.getText(), ); // Reject on user typing @@ -416,7 +419,11 @@ export class VerticalDiffHandler implements vscode.Disposable { this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0; const status = numDiffs === 0 ? "closed" : undefined; - this.options.onStatusUpdate(status, numDiffs); + this.options.onStatusUpdate( + status, + numDiffs, + this.editor.document.getText(), + ); } private shiftCodeLensObjects(startLine: number, offset: number) { diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 4595ca013..3342c5341 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -217,11 +217,13 @@ export class VerticalDiffManager { endLine, { instant, - onStatusUpdate: (status, numDiffs) => + onStatusUpdate: (status, numDiffs, fileContent) => void this.webviewProtocol.request("updateApplyState", { streamId, status, numDiffs, + fileContent, + filepath, }), }, ); @@ -336,12 +338,14 @@ export class VerticalDiffManager { endLine, { input, - onStatusUpdate: (status, numDiffs) => + onStatusUpdate: (status, numDiffs, fileContent) => streamId && void this.webviewProtocol.request("updateApplyState", { streamId, status, numDiffs, + fileContent, + filepath, }), }, ); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 862fe5452..1267d5781 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -147,15 +147,35 @@ export class VsCodeMessenger { ); }); - webviewProtocol.on("acceptDiff", async ({ data: { filepath } }) => { - void vscode.commands.executeCommand("continue.acceptDiff", filepath); - }); + webviewProtocol.on( + "acceptDiff", + async ({ data: { filepath, streamId } }) => { + await vscode.commands.executeCommand( + "continue.acceptDiff", + filepath, + streamId, + ); + }, + ); - webviewProtocol.on("rejectDiff", async ({ data: { filepath } }) => { - void vscode.commands.executeCommand("continue.rejectDiff", filepath); - }); + webviewProtocol.on( + "rejectDiff", + async ({ data: { filepath, streamId } }) => { + await vscode.commands.executeCommand( + "continue.rejectDiff", + filepath, + streamId, + ); + }, + ); this.onWebview("applyToFile", async ({ data }) => { + webviewProtocol.request("updateApplyState", { + streamId: data.streamId, + status: "streaming", + fileContent: data.text, + }); + let filepath = data.filepath; // If there is a filepath, verify it exists and then open the file @@ -168,18 +188,10 @@ export class VsCodeMessenger { const fileExists = await this.ide.fileExists(fullPath); - // If it's a new file, no need to apply, just write directly + // If there is no existing file at the path, create it if (!fileExists) { - await this.ide.writeFile(fullPath, data.text); + await this.ide.writeFile(fullPath, ""); await this.ide.openFile(fullPath); - - void webviewProtocol.request("updateApplyState", { - streamId: data.streamId, - status: "done", - numDiffs: 0, - }); - - return; } await this.ide.openFile(fullPath); @@ -198,11 +210,14 @@ export class VsCodeMessenger { editor.edit((builder) => builder.insert(new vscode.Position(0, 0), data.text), ); + void webviewProtocol.request("updateApplyState", { streamId: data.streamId, - status: "done", + status: "closed", numDiffs: 0, + fileContent: data.text, }); + return; } @@ -290,6 +305,37 @@ export class VsCodeMessenger { this.onWebview("openUrl", (msg) => { vscode.env.openExternal(vscode.Uri.parse(msg.data)); }); + + this.onWebview( + "overwriteFile", + async ({ data: { prevFileContent, filepath } }) => { + if (prevFileContent === null) { + // TODO: Delete the file + return; + } + + await this.ide.openFile(filepath); + + // Get active text editor + const editor = vscode.window.activeTextEditor; + + if (!editor) { + vscode.window.showErrorMessage("No active editor to apply edits to"); + return; + } + + editor.edit((builder) => + builder.replace( + new vscode.Range( + editor.document.positionAt(0), + editor.document.positionAt(editor.document.getText().length), + ), + prevFileContent, + ), + ); + }, + ); + this.onWebview("insertAtCursor", async (msg) => { const editor = vscode.window.activeTextEditor; if (editor === undefined || !editor.selection) { diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 60fc6b72d..2ce332f02 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -21,7 +21,6 @@ import { uriFromFilePath, } from "./vscode"; - import type { FileEdit, RangeInFile, Thread } from "core"; const util = require("node:util"); @@ -181,7 +180,8 @@ export class VsCodeIdeUtils { vscode.workspace .openTextDocument( vscode.Uri.parse( - `${VsCodeExtension.continueVirtualDocumentScheme + `${ + VsCodeExtension.continueVirtualDocumentScheme }:${encodeURIComponent(name)}?${encodeURIComponent(contents)}`, ), ) @@ -305,8 +305,8 @@ export class VsCodeIdeUtils { return `${lines .slice(range.start.line, range.end.line) .join("\n")}\n${lines[ - range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 - ].slice(0, range.end.character)}`; + range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 + ].slice(0, range.end.character)}`; } async getTerminalContents(commands = -1): Promise { @@ -572,7 +572,6 @@ export class VsCodeIdeUtils { async getDiff(includeUnstaged: boolean): Promise { let diffs: string[] = []; - let repos = []; for (const dir of this.getWorkspaceDirectories()) { const repo = await this.getRepo(vscode.Uri.file(dir)); @@ -580,20 +579,16 @@ export class VsCodeIdeUtils { continue; } - repos.push(repo.state.HEAD?.name); - const staged = await repo.diff(true); - diffs.push(`${staged}`); + diffs.push(staged); if (includeUnstaged) { const unstaged = await repo.diff(false); - diffs.push(`\n${unstaged}`); + diffs.push(unstaged); } } const fullDiff = diffs.join("\n\n"); - if (fullDiff.trim() === "") { - console.log(`Diff empty for repos: ${repos}`); - } + return fullDiff; } diff --git a/gui/public/logos/moonshot.png b/gui/public/logos/moonshot.png new file mode 100644 index 000000000..f51df62eb Binary files /dev/null and b/gui/public/logos/moonshot.png differ diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 26107c199..695389c29 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,11 +1,12 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionInfo } from "core"; import React, { useState } from "react"; -import { useDispatch } from "react-redux"; +import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; import useHistory from "../../hooks/useHistory"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { RootState } from "../../redux/store"; function lastPartOfPath(path: string): string { const sep = path.includes("/") ? "/" : "\\"; @@ -29,6 +30,9 @@ export function HistoryTableRow({ const [sessionTitleEditValue, setSessionTitleEditValue] = useState( session.title, ); + const currentSessionId = useSelector( + (state: RootState) => state.state.sessionId, + ); const { saveSession, deleteSession, loadSession, getSession, updateSession } = useHistory(dispatch); @@ -59,8 +63,11 @@ export function HistoryTableRow({ className="hover:bg-vsc-editor-background relative box-border flex max-w-full cursor-pointer overflow-hidden rounded-lg p-3" onClick={async () => { // Save current session - await saveSession(); - await loadSession(session.sessionId); + if (session.sessionId !== currentSessionId) { + await saveSession(); + await loadSession(session.sessionId); + } + navigate("/"); }} > diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 3b7dc51e1..fbd774f35 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -12,11 +12,11 @@ import { setEditStatus, startEditMode, } from "../redux/slices/editModeState"; +import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice"; import { - setDialogMessage, - setShowDialog, updateApplyState, -} from "../redux/slices/uiStateSlice"; + updateCurCheckpoint, +} from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getFontSize, isMetaEquivalentKeyPressed } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; @@ -171,6 +171,12 @@ const Layout = () => { useWebviewListener( "updateApplyState", async (state) => { + dispatch( + updateCurCheckpoint({ + filepath: state.filepath, + content: state.fileContent, + }), + ); dispatch(updateApplyState(state)); }, [], diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx new file mode 100644 index 000000000..a1e7b28f6 --- /dev/null +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -0,0 +1,46 @@ +import { useContext } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { ApplyState } from "core/protocol/ideWebview"; + +export interface AcceptRejectAllButtonsProps { + pendingApplyStates: ApplyState[]; +} + +export default function AcceptRejectAllButtons({ + pendingApplyStates, +}: AcceptRejectAllButtonsProps) { + const ideMessenger = useContext(IdeMessengerContext); + + async function handleAcceptOrReject(status: "acceptDiff" | "rejectDiff") { + for (const { filepath, streamId } of pendingApplyStates) { + ideMessenger.post(status, { + filepath, + streamId, + }); + } + } + + return ( +
+ + +
+ ); +} diff --git a/gui/src/components/StepContainer/FeedbackButtons.tsx b/gui/src/components/StepContainer/FeedbackButtons.tsx new file mode 100644 index 000000000..55e870991 --- /dev/null +++ b/gui/src/components/StepContainer/FeedbackButtons.tsx @@ -0,0 +1,55 @@ +import { + HandThumbUpIcon, + HandThumbDownIcon, +} from "@heroicons/react/24/outline"; +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { ChatHistoryItem } from "core"; +import { useState, useContext } from "react"; +import { useSelector } from "react-redux"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { RootState } from "../../redux/store"; + +export interface FeedbackButtonsProps { + item: ChatHistoryItem; +} + +export default function FeedbackButtons({ item }: FeedbackButtonsProps) { + const [feedback, setFeedback] = useState(undefined); + const ideMessenger = useContext(IdeMessengerContext); + const sessionId = useSelector((store: RootState) => store.state.sessionId); + + const sendFeedback = (feedback: boolean) => { + setFeedback(feedback); + if (item.promptLogs?.length) { + for (const promptLog of item.promptLogs) { + ideMessenger.post("devdata/log", { + tableName: "chat", + data: { ...promptLog, feedback, sessionId }, + }); + } + } + }; + + return ( + <> + sendFeedback(true)} + > + + + sendFeedback(false)} + > + + {" "} + + ); +} diff --git a/gui/src/components/StepContainer/MultifileEditActions.tsx b/gui/src/components/StepContainer/MultifileEditActions.tsx new file mode 100644 index 000000000..5fb7122df --- /dev/null +++ b/gui/src/components/StepContainer/MultifileEditActions.tsx @@ -0,0 +1,65 @@ +import { useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; +import FeedbackButtons from "./FeedbackButtons"; +import UndoAndRedoButtons from "./UndoAndRedoButtons"; +import { ChatHistoryItem } from "core"; +import { stripImages } from "core/llm/images"; +import { CopyIconButton } from "../gui/CopyIconButton"; + +export interface MultifileEditActionsProps { + index: number; + item: ChatHistoryItem; +} + +export default function MultifileEditActions({ + index, + item, +}: MultifileEditActionsProps) { + const curCheckpointIndex = useSelector( + (store: RootState) => store.state.curCheckpointIndex, + ); + + const applyStates = useSelector( + (state: RootState) => state.state.applyStates, + ); + + const pendingApplyStates = applyStates.filter( + (state) => state.status === "done", + ); + + const hasClosedAllStreams = applyStates.every( + (state) => state.status === "closed", + ); + + const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; + const hasPendingApplies = pendingApplyStates.length > 0; + + return ( +
+
+ + {isCurCheckpoint && ( +
+ {hasPendingApplies && ( + + )} + {hasClosedAllStreams && } +
+ )} + +
+ + + +
+
+ ); +} diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx new file mode 100644 index 000000000..66d62575c --- /dev/null +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -0,0 +1,65 @@ +import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; +import { stripImages } from "core/llm/images"; +import { CopyIconButton } from "../gui/CopyIconButton"; +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import { ChatHistoryItem } from "core"; +import FeedbackButtons from "./FeedbackButtons"; +import MultifileEditActions from "./MultifileEditActions"; + +export interface ResponseActionsProps { + isTruncated: boolean; + onContinueGeneration: () => void; + index: number; + onDelete: () => void; + item: ChatHistoryItem; +} + +export default function ResponseActions({ + onContinueGeneration, + index, + item, + isTruncated, + onDelete, +}: ResponseActionsProps) { + const isInMultifileEdit = useSelector( + (store: RootState) => store.state.isMultifileEdit, + ); + + // Only render delete button if there is more than one message + const shouldRenderDelete = index !== 1; + + if (isInMultifileEdit) { + return ; + } + + return ( +
+ {isTruncated && ( + + + + )} + + {shouldRenderDelete && ( + + + + )} + + + + +
+ ); +} diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx new file mode 100644 index 000000000..4fdd6eda2 --- /dev/null +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -0,0 +1,116 @@ +import { ChatHistoryItem } from "core"; +import { stripImages } from "core/llm/images"; +import { useEffect, useState } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import styled from "styled-components"; +import { vscBackground } from ".."; +import useUIConfig from "../../hooks/useUIConfig"; +import { RootState } from "../../redux/store"; +import { getFontSize } from "../../util"; +import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import ResponseActions from "./ResponseActions"; +import { deleteMessage } from "../../redux/slices/stateSlice"; + +interface StepContainerProps { + item: ChatHistoryItem; + index: number; + isLast: boolean; +} + +const ContentDiv = styled.div<{ fontSize?: number }>` + padding-top: 4px; + background-color: ${vscBackground}; + font-size: ${getFontSize()}px; + overflow: hidden; +`; + +export default function StepContainer(props: StepContainerProps) { + const dispatch = useDispatch(); + const [isTruncated, setIsTruncated] = useState(false); + const active = useSelector((store: RootState) => store.state.active); + const curCheckpointIndex = useSelector( + (store: RootState) => store.state.curCheckpointIndex, + ); + const isMultifileEdit = useSelector( + (store: RootState) => store.state.isMultifileEdit, + ); + const uiConfig = useUIConfig(); + const shouldHideActions = active && props.isLast; + const isStepAheadOfCurCheckpoint = + isMultifileEdit && Math.floor(props.index / 2) > curCheckpointIndex; + + useEffect(() => { + if (!active) { + const content = stripImages(props.item.message.content).trim(); + const endingPunctuation = [".", "?", "!", "```"]; + + // If not ending in punctuation or emoji, we assume the response got truncated + if ( + !( + endingPunctuation.some((p) => content.endsWith(p)) || + /\p{Emoji}/u.test(content.slice(-2)) + ) + ) { + setIsTruncated(true); + } else { + setIsTruncated(false); + } + } + }, [props.item.message.content, active]); + + function onDelete() { + dispatch(deleteMessage(props.index)); + } + + function onContinueGeneration() { + window.postMessage( + { + messageType: "userInput", + data: { + input: "Continue your response exactly where you left off:", + }, + }, + "*", + ); + } + + return ( +
+ + {uiConfig?.displayRawMarkdown ? ( +
+            {stripImages(props.item.message.content)}
+          
+ ) : ( + + )} +
+ {/* We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on */} +
+ {!shouldHideActions && ( + + )} +
+
+ ); +} diff --git a/gui/src/components/StepContainer/UndoAndRedoButtons.tsx b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx new file mode 100644 index 000000000..2ee69a11a --- /dev/null +++ b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx @@ -0,0 +1,61 @@ +import { useDispatch, useSelector } from "react-redux"; +import { RootState } from "../../redux/store"; +import { + ArrowUturnLeftIcon, + ArrowUturnRightIcon, +} from "@heroicons/react/24/outline"; +import { setCurCheckpointIndex } from "../../redux/slices/stateSlice"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; + +export default function UndoAndRedoButtons() { + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + const checkpoints = useSelector( + (store: RootState) => store.state.checkpoints, + ); + + const curCheckpointIndex = useSelector( + (store: RootState) => store.state.curCheckpointIndex, + ); + + const shouldRenderRedo = curCheckpointIndex !== checkpoints.length - 1; + + async function handleUndoOrRedo(type: "undo" | "redo") { + const checkpointIndex = Math.max( + 0, + type === "undo" ? curCheckpointIndex - 1 : curCheckpointIndex + 1, + ); + + const checkpoint = checkpoints[checkpointIndex]; + + for (const [filepath, prevFileContent] of Object.entries(checkpoint)) { + ideMessenger.post("overwriteFile", { filepath, prevFileContent }); + } + + dispatch(setCurCheckpointIndex(checkpointIndex)); + } + + return ( +
+ + + {shouldRenderRedo && ( + + )} +
+ ); +} diff --git a/gui/src/components/StepContainer/index.ts b/gui/src/components/StepContainer/index.ts new file mode 100644 index 000000000..41d4fa945 --- /dev/null +++ b/gui/src/components/StepContainer/index.ts @@ -0,0 +1 @@ +export { default } from "./StepContainer"; diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 3c97e09e6..098194886 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -1,11 +1,20 @@ -import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline"; +import { + CheckCircleIcon, + ChevronDownIcon, + ChevronUpIcon, +} from "@heroicons/react/24/outline"; import { SiteIndexingConfig } from "core"; import { usePostHog } from "posthog-js/react"; import { useContext, useLayoutEffect, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; -import { Button, HelperText, Input, lightGray } from ".."; +import { useDispatch, useSelector } from "react-redux"; +import { Button, HelperText, Input, lightGray, SecondaryButton } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setShowDialog } from "../../redux/slices/uiStateSlice"; +import { + setDialogMessage, + setShowDialog, +} from "../../redux/slices/uiStateSlice"; +import { RootState } from "../../redux/store"; +import IndexingStatusViewer from "../indexing/IndexingStatus"; function AddDocsDialog() { const posthog = usePostHog(); @@ -18,7 +27,12 @@ function AddDocsDialog() { const [faviconUrl, setFaviconUrl] = useState(""); const [isOpen, setIsOpen] = useState(false); + const [submittedConfig, setSubmittedConfig] = useState(); + const ideMessenger = useContext(IdeMessengerContext); + const indexingStatuses = useSelector( + (store: RootState) => store.state.indexing.statuses, + ); const isFormValid = startUrl && title; @@ -41,15 +55,66 @@ function AddDocsDialog() { ideMessenger.post("context/addDocs", siteIndexingConfig); + setSubmittedConfig(siteIndexingConfig); setTitle(""); setStartUrl(""); setFaviconUrl(""); - dispatch(setShowDialog(false)); - posthog.capture("add_docs_gui", { url: startUrl }); } + if (submittedConfig) { + const status = indexingStatuses[submittedConfig.startUrl]; + return ( +
+
+ +

{`Docs added`}

+
+
+

Title: {submittedConfig.title}

+

Start URL: {submittedConfig.startUrl}

+ {submittedConfig.rootUrl && ( +

Root URL: {submittedConfig.rootUrl}

+ )} + {submittedConfig.maxDepth && ( +

Max depth: {submittedConfig.maxDepth}

+ )} + {submittedConfig.faviconUrl && ( +

Favicon URL: {submittedConfig.faviconUrl}

+ )} +
+ {!!status && ( +
+

{`Type "@docs" and select ${submittedConfig.title} to reference these docs once indexing is complete. Check indexing status from the "More" page.`}

+
+ +
+
+ )} +
+ { + setSubmittedConfig(undefined); + }} + > + Add another + + +
+
+ ); + } + return (
diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 33214fdfb..7685109ba 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -34,7 +34,6 @@ const DialogContainer = styled.div` top: 50%; left: 50%; transform: translate(-50%, -50%); - width: 75%; `; const Dialog = styled.div` @@ -72,6 +71,7 @@ const TextDialog = (props: TextDialogProps) => { return (