diff --git a/.github/workflows/dev_pr.yaml b/.github/workflows/dev_pr.yaml new file mode 100644 index 000000000..d909a279a --- /dev/null +++ b/.github/workflows/dev_pr.yaml @@ -0,0 +1,92 @@ +name: Dev PR checks + +on: + pull_request: + branches: + - dev + +jobs: + tsc-check: + runs-on: ubuntu-latest + + steps: + # 1. Check-out repository + - name: Check-out repository + uses: actions/checkout@v4 + + # 2. Install npm dependencies + - name: Use Node.js from .nvmrc + uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - name: Cache extension node_modules + uses: actions/cache@v3 + with: + path: extensions/vscode/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} + + - name: Cache core node_modules + uses: actions/cache@v3 + with: + path: core/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} + + - name: Cache gui node_modules + uses: actions/cache@v3 + with: + path: gui/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} + + - name: Cache binary node_modules + uses: actions/cache@v3 + with: + path: binary/node_modules + key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }} + + - name: extensions/vscode install + run: | + cd extensions/vscode + npm ci + env: + # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} + + - name: core install + run: | + cd core + npm ci + + - name: gui install + run: | + cd gui + npm ci + + - name: binary install + run: | + cd binary + npm ci + + - name: extensions/vscode checks + run: | + cd extensions/vscode + npx tsc --noEmit + + - name: core checks + run: | + cd core + npm ci + npx tsc --noEmit + npm run lint + env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + + - name: gui checks + run: | + cd gui + npx tsc --noEmit + + - name: binary checks + run: | + cd binary + npx tsc --noEmit diff --git a/.github/workflows/ts-check.yaml b/.github/workflows/ts-check.yaml index 193988990..f73016fa5 100644 --- a/.github/workflows/ts-check.yaml +++ b/.github/workflows/ts-check.yaml @@ -5,7 +5,6 @@ on: branches: - main - preview - - dev jobs: tsc-check: diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 1c67b146c..8ba241323 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -8,7 +8,7 @@ "plugins": ["@typescript-eslint", "import"], "rules": { "quotes": ["warn", "double", {}], - "@typescript-eslint/naming-convention": "warn", + "@typescript-eslint/naming-convention": "off", "@typescript-eslint/semi": "warn", "curly": "warn", "eqeqeq": "warn", diff --git a/core/.gitignore b/core/.gitignore index ad1c54334..7d8f1fa53 100644 --- a/core/.gitignore +++ b/core/.gitignore @@ -4,4 +4,5 @@ target npm-debug.log* .env .continue-test -testDir \ No newline at end of file +testDir +coverage \ No newline at end of file diff --git a/core/autocomplete/brackets.ts b/core/autocomplete/brackets.ts index 63afdfd10..3734df2be 100644 --- a/core/autocomplete/brackets.ts +++ b/core/autocomplete/brackets.ts @@ -84,9 +84,9 @@ export class BracketMatchingService { // Add corresponding open brackets from suffix to stack // because we overwrite them and the diff is displayed, and this allows something to be edited after that for (let i = 0; i < suffix.length; i++) { - if (suffix[i] === " ") continue; + if (suffix[i] === " ") {continue;} const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]]; - if (!openBracket) break; + if (!openBracket) {break;} stack.unshift(openBracket); } diff --git a/core/test/streamTransforms/stopAtStopTokens.test.ts b/core/autocomplete/charStream.test.ts similarity index 98% rename from core/test/streamTransforms/stopAtStopTokens.test.ts rename to core/autocomplete/charStream.test.ts index cdb507dd7..7ab8923fc 100644 --- a/core/test/streamTransforms/stopAtStopTokens.test.ts +++ b/core/autocomplete/charStream.test.ts @@ -1,4 +1,4 @@ -import { stopAtStopTokens } from "../../autocomplete/charStream.js"; +import { stopAtStopTokens } from "./charStream"; describe("stopAtStopTokens", () => { async function* createMockStream(chunks: string[]): AsyncGenerator { diff --git a/core/autocomplete/charStream.ts b/core/autocomplete/charStream.ts index 0ce49e418..79fc33a0d 100644 --- a/core/autocomplete/charStream.ts +++ b/core/autocomplete/charStream.ts @@ -1,12 +1,24 @@ +/** + * Asynchronous generator that yields characters from the input stream until it encounters + * an end-of-line character followed by a non-whitespace character. + * + * @param {AsyncGenerator} stream - The input stream of characters. + * @param {string[]} endOfLine - An array of characters considered as end-of-line markers. + * @param {() => void} fullStop - A function to be called when the generator stops. + * @yields {string} Characters from the input stream. + * @returns {AsyncGenerator} An async generator that yields characters. + */ export async function* onlyWhitespaceAfterEndOfLine( stream: AsyncGenerator, endOfLine: string[], fullStop: () => void, ): AsyncGenerator { let pending = ""; + for await (let chunk of stream) { chunk = pending + chunk; pending = ""; + for (let i = 0; i < chunk.length - 1; i++) { if ( endOfLine.includes(chunk[i]) && @@ -17,6 +29,7 @@ export async function* onlyWhitespaceAfterEndOfLine( return; } } + if (endOfLine.includes(chunk[chunk.length - 1])) { pending = chunk[chunk.length - 1]; yield chunk.slice(0, chunk.length - 1); @@ -27,6 +40,11 @@ export async function* onlyWhitespaceAfterEndOfLine( yield pending; } +/** + * Yields characters from the stream, stopping if the first character is a newline. + * @param {AsyncGenerator} stream - The input character stream. + * @yields {string} Characters from the stream. + */ export async function* noFirstCharNewline(stream: AsyncGenerator) { let first = true; for await (const char of stream) { @@ -40,6 +58,20 @@ export async function* noFirstCharNewline(stream: AsyncGenerator) { } } +/** + * Asynchronously yields characters from the input stream, stopping if a stop token is encountered. + * + * @param {AsyncGenerator} stream - The input stream of characters. + * @param {string[]} stopTokens - Array of tokens that signal when to stop yielding. + * @yields {string} Characters from the input stream. + * @returns {AsyncGenerator} An async generator that yields characters until a stop condition is met. + * @description + * 1. If no stop tokens are provided, yields all characters from the stream. + * 2. Otherwise, buffers incoming chunks and checks for stop tokens. + * 3. Yields characters one by one if no stop token is found at the start of the buffer. + * 4. Stops yielding and returns if a stop token is encountered. + * 5. After the stream ends, yields any remaining buffered characters. + */ export async function* stopAtStopTokens( stream: AsyncGenerator, stopTokens: string[], diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index c67ce1f0a..39d2d1e73 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -37,7 +37,7 @@ import { import { isOnlyPunctuationAndWhitespace } from "./filter.js"; import { AutocompleteLanguageInfo } from "./languages.js"; import { - avoidPathLine, + avoidPathLineAndEmptyComments, noTopLevelKeywordsMidline, skipPrefixes, stopAtLines, @@ -478,9 +478,9 @@ export class CompletionProvider { const lines = fullPrefix.split("\n"); fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ lang.singleLineComment - } ${input.injectDetails.split("\n").join(`\n${lang.singleLineComment} `)}\n${ - lines[lines.length - 1] - }`; + } ${input.injectDetails + .split("\n") + .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; } const fullSuffix = getRangeInString(fileContents, { @@ -581,7 +581,10 @@ export class CompletionProvider { 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}`; + prefix = `${lang.singleLineComment} ${getLastNPathParts( + filepath, + 2, + )}\n${prefix}`; } prompt = compiledTemplate({ @@ -689,7 +692,10 @@ export class CompletionProvider { let lineGenerator = streamLines(charGenerator); lineGenerator = stopAtLines(lineGenerator, fullStop); lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment); + lineGenerator = avoidPathLineAndEmptyComments( + lineGenerator, + lang.singleLineComment, + ); lineGenerator = skipPrefixes(lineGenerator); lineGenerator = noTopLevelKeywordsMidline( lineGenerator, diff --git a/core/autocomplete/languages.ts b/core/autocomplete/languages.ts index 19ab65f71..f5b4cffb0 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/languages.ts @@ -26,7 +26,7 @@ export const Python = { name: "Python", // """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks. // This stops the model from trying to complete the start of a new markdown block - topLevelKeywords: ["def", "class", '"""#'], + topLevelKeywords: ["def", "class", "\"\"\"#"], singleLineComment: "#", endOfLine: [], }; diff --git a/core/autocomplete/lineStream.test.ts b/core/autocomplete/lineStream.test.ts new file mode 100644 index 000000000..df8cd1263 --- /dev/null +++ b/core/autocomplete/lineStream.test.ts @@ -0,0 +1,421 @@ +import { jest } from "@jest/globals"; +import * as lineStream from "./lineStream"; + +describe("lineStream", () => { + let mockFullStop: jest.Mock; + + async function getLineGenerator(lines: any) { + return (async function* () { + for (const line of lines) { + yield line; + } + })(); + } + + async function getFilteredLines(results: any) { + const output = []; + + for await (const line of results) { + output.push(line); + } + + return output; + } + + beforeEach(() => { + mockFullStop = jest.fn(); + }); + + describe("noTopLevelKeywordsMidline", () => { + it.todo("Need some sample inputs to properly test this"); + }); + + describe("avoidPathLine", () => { + it("should filter out path lines and empty comments", async () => { + const linesGenerator = await getLineGenerator([ + "// Path: src/index.ts", + "const x = 5;", + "//", + "console.log(x);", + ]); + + const result = lineStream.avoidPathLineAndEmptyComments( + linesGenerator, + "//", + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "console.log(x);"]); + }); + }); + + describe("streamWithNewLines", () => { + it("should add newlines between lines", async () => { + const linesGenerator = await getLineGenerator([ + "line1", + "line2", + "line3", + ]); + + const result = lineStream.streamWithNewLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]); + }); + }); + + describe("lineIsRepeated", () => { + it("should return true for similar lines", () => { + expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe( + true, + ); + }); + + it("should return false for different lines", () => { + expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe( + false, + ); + }); + + it("should return false for short lines", () => { + expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false); + }); + }); + + describe("stopAtSimilarLine", () => { + it("should stop at the exact same line", async () => { + const lineToTest = "const x = 6;"; + const linesGenerator = await getLineGenerator([ + "console.log();", + "const y = () => {};", + lineToTest, + ]); + + const result = lineStream.stopAtSimilarLine( + linesGenerator, + lineToTest, + mockFullStop, + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + + it("should stop at a similar line", async () => { + const lineToTest = "const x = 6;"; + const linesGenerator = await getLineGenerator([ + "console.log();", + "const y = () => {};", + lineToTest, + ]); + + const result = lineStream.stopAtSimilarLine( + linesGenerator, + "a" + lineToTest, + mockFullStop, + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + + it("should continue on bracket ending lines", async () => { + const linesGenerator = await getLineGenerator([ + " if (x > 0) {", + " console.log(x);", + " }", + ]); + + const result = lineStream.stopAtSimilarLine( + linesGenerator, + "}", + mockFullStop, + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + " if (x > 0) {", + " console.log(x);", + " }", + ]); + expect(mockFullStop).toHaveBeenCalledTimes(0); + }); + }); + + describe("stopAtLines", () => { + it("should stop at specified lines", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + lineStream.LINES_TO_STOP_AT[0], + "const z = 15;", + ]); + + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + }); + + describe("skipPrefixes", () => { + it("should skip specified prefixes", async () => { + const linesGenerator = await getLineGenerator([ + `${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`, + "let y = 10;", + ]); + + const result = lineStream.skipPrefixes(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + }); + }); + + describe("skipLines", () => { + it("should skip specified lines", async () => { + const linesGenerator = await getLineGenerator([ + `${lineStream.LINES_TO_SKIP[0]}const x = 5;`, + "let y = 10;", + ]); + + const result = lineStream.skipLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["let y = 10;"]); + }); + }); + + describe("filterCodeBlockLines", () => { + it("should remove lines before the first valid line", async () => { + const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it.todo("Need some sample inputs to properly test this"); + }); + + describe("filterEnglishLinesAtStart", () => { + it("should skip initial empty line", async () => { + const linesGenerator = await getLineGenerator([ + "", + "const x = 5;", + "let y = 10;", + ]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + }); + + it("should filter out English first line", async () => { + const linesGenerator = await getLineGenerator([ + lineStream.ENGLISH_START_PHRASES[0], + "let y = 10;", + ]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["let y = 10;"]); + }); + + it("should not filter out non-English first line", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + ]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + }); + + it("should filter out empty newline after first line english word", async () => { + const linesGenerator = await getLineGenerator([ + lineStream.ENGLISH_START_PHRASES[0], + "", + "const x = 5;", + ]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should filter out sentences ending in a semi-colon that are not code keywords", async () => { + const linesGenerator = await getLineGenerator([ + "a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":", + "const x = 5;", + ]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should not filter out sentences ending in a semi-colon that are code keywords", async () => { + const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":"; + + const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]); + + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([keyword, "const x = 5;"]); + }); + }); + + describe("filterEnglishLinesAtEnd", () => { + it("should stop at English explanation after code block", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "```", + lineStream.ENGLISH_POST_PHRASES[0], + ]); + + const result = lineStream.filterEnglishLinesAtEnd(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "```"]); + }); + }); + + describe("fixCodeLlamaFirstLineIndentation", () => { + it("should fix indentation of the first line", async () => { + const linesGenerator = await getLineGenerator([ + " const x = 5;", + "let y = 10;", + ]); + + const result = + lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + }); + }); + + describe("filterLeadingAndTrailingNewLineInsertion", () => { + it("should ignore 'useless' new first lines", async () => { + const linesGenerator = await getLineGenerator([ + { type: "new", line: lineStream.USELESS_LINES[0] }, + { type: "new", line: "const x = 5;" }, + ]); + + const result = + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]); + }); + + it("should handle preserve newlines chars in old lines", async () => { + const linesGenerator = await getLineGenerator([ + { type: "new", line: "const x = 5;" }, + { type: "old", line: "let y = 10;" }, + { type: "old", line: "" }, + { type: "new", line: "const z = 15;" }, + ]); + + const result = + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + { type: "new", line: "const x = 5;" }, + { type: "old", line: "let y = 10;" }, + { type: "old", line: "" }, + { type: "new", line: "const z = 15;" }, + ]); + }); + + it("should filter leading and trailing new line insertions", async () => { + const linesGenerator = await getLineGenerator([ + { type: "new", line: "" }, + { type: "new", line: "const x = 5;" }, + { type: "new", line: "let y = 10;" }, + { type: "new", line: "" }, + ]); + + const result = + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + { type: "new", line: "const x = 5;" }, + { type: "new", line: "let y = 10;" }, + ]); + }); + + it("should buffer newline chars and then render them if we encounter another non-empty line", async () => { + const linesGenerator = await getLineGenerator([ + { type: "new", line: "const x = 5;" }, + { type: "new", line: "" }, + { type: "new", line: "let y = 10;" }, + ]); + + const result = + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + { type: "new", line: "const x = 5;" }, + { type: "new", line: "" }, + { type: "new", line: "let y = 10;" }, + ]); + }); + }); + + describe("stopAtRepeatingLines", () => { + it("should handle non-repeating lines correctly", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + "const z = 15;", + ]); + + const result = lineStream.stopAtRepeatingLines( + linesGenerator, + mockFullStop, + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual([ + "const x = 5;", + "let y = 10;", + "const z = 15;", + ]); + }); + + it("should stop at repeating lines", async () => { + const linesGenerator = await getLineGenerator([ + "const x = 5;", + "let y = 10;", + "let y = 10;", + "let y = 10;", + "const z = 15;", + ]); + + const result = lineStream.stopAtRepeatingLines( + linesGenerator, + mockFullStop, + ); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); + expect(mockFullStop).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index 674f0d46e..e7d3493bd 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -1,12 +1,107 @@ import { distance } from "fastest-levenshtein"; -import { LineStream } from "../diff/util.js"; -import { DiffLine } from "../index.js"; +import { LineStream } from "../diff/util"; +import { DiffLine } from "../"; export type LineFilter = (args: { lines: LineStream; fullStop: () => void; }) => LineStream; +function isBracketEnding(line: string): boolean { + return line + .trim() + .split("") + .some((char) => BRACKET_ENDING_CHARS.includes(char)); +} + +function commonPrefixLength(a: string, b: string): number { + let i = 0; + while (i < a.length && i < b.length && a[i] === b[i]) { + i++; + } + return i; +} + +function isEnglishFirstLine(line: string) { + line = line.trim().toLowerCase(); + + if ( + line.endsWith(":") && + !CODE_KEYWORDS_ENDING_IN_SEMICOLON.some((keyword) => + line.startsWith(keyword), + ) + ) { + return true; + } + + return ENGLISH_START_PHRASES.some((phrase) => line.startsWith(phrase)); +} + +function isEnglishPostExplanation(line: string): boolean { + const lower = line.toLowerCase(); + return ENGLISH_POST_PHRASES.some((phrase) => lower.startsWith(phrase)); +} + +function shouldRemoveLineBeforeStart(line: string): boolean { + return ( + line.trimStart().startsWith("```") || + LINES_TO_REMOVE_BEFORE_START.some((l) => line.trim() === l) + ); +} + +function shouldChangeLineAndStop(line: string): string | undefined { + if (line.trimStart() === "```") { + return line; + } + + if (line.includes(CODE_START_BLOCK)) { + return line.split(CODE_START_BLOCK)[0].trimEnd(); + } + + return undefined; +} + +function isUselessLine(line: string): boolean { + const trimmed = line.trim().toLowerCase(); + const hasUselessLine = USELESS_LINES.some( + (uselessLine) => trimmed === uselessLine, + ); + + return hasUselessLine || trimmed.startsWith("// end"); +} + +export const USELESS_LINES = ["", "```"]; +export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"]; +export const CODE_START_BLOCK = "[/CODE]"; +export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"]; +export const PREFIXES_TO_SKIP = [""]; +export const LINES_TO_STOP_AT = ["# End of file.", ""]; +export const LINES_TO_REMOVE_BEFORE_START = [ + "", + "[CODE]", + "", +]; + +export const ENGLISH_START_PHRASES = [ + "here is", + "here's", + "sure, here", + "sure thing", + "sure!", + "to fill", + "certainly", + "of course", + "the code should", +]; + +export const ENGLISH_POST_PHRASES = [ + "explanation:", + "here is", + "here's how", + "the above", +]; + export async function* noTopLevelKeywordsMidline( lines: LineStream, topLevelKeywords: string[], @@ -15,6 +110,7 @@ export async function* noTopLevelKeywordsMidline( for await (const line of lines) { for (const keyword of topLevelKeywords) { const indexOf = line.indexOf(`${keyword} `); + // TODO: What is this second clause for? if (indexOf >= 0 && line.slice(indexOf - 1, indexOf).trim() !== "") { yield line.slice(0, indexOf); fullStop(); @@ -25,7 +121,14 @@ export async function* noTopLevelKeywordsMidline( } } -export async function* avoidPathLine( +/** + * Filters out unwanted lines from a LineStream, specifically those starting with '// Path: ' or empty comments. + * + * @param {LineStream} stream - The input stream of lines to filter. + * @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments). + * @yields {string} The filtered lines, excluding unwanted path lines and empty comments. + */ +export async function* avoidPathLineAndEmptyComments( stream: LineStream, comment: string, ): LineStream { @@ -40,6 +143,12 @@ export async function* avoidPathLine( } } +/** + * Transforms a LineStream by adding newline characters between lines. + * + * @param {LineStream} stream - The input stream of lines. + * @yields {string} The lines from the input stream with newline characters added between them. + */ export async function* streamWithNewLines(stream: LineStream): LineStream { let firstLine = true; for await (const nextLine of stream) { @@ -51,22 +160,19 @@ export async function* streamWithNewLines(stream: LineStream): LineStream { } } -const bracketEnding = [")", "]", "}", ";"]; -function isBracketEnding(line: string): boolean { - return line - .trim() - .split("") - .some((char) => bracketEnding.includes(char)); -} - -function commonPrefixLength(a: string, b: string): number { - let i = 0; - while (i < a.length && i < b.length && a[i] === b[i]) { - i++; - } - return i; -} - +/** + * Determines if two lines of text are considered repeated or very similar. + * + * @param {string} a - The first line of text to compare. + * @param {string} b - The second line of text to compare. + * @returns {boolean} True if the lines are considered repeated, false otherwise. + * + * @description + * This function checks if two lines are repeated or very similar based on two criteria: + * 1. They have a common prefix longer than 12 characters. + * 2. The Levenshtein distance between them is less than 10% of the length of the second line. + * Lines shorter than 5 characters are never considered repeated. + */ export function lineIsRepeated(a: string, b: string): boolean { if (a.length <= 4 || b.length <= 4) { return false; @@ -80,6 +186,21 @@ export function lineIsRepeated(a: string, b: string): boolean { ); } +/** + * Filters a LineStream, stopping when a line similar to the provided one is encountered. + * + * @param {LineStream} stream - The input stream of lines to filter. + * @param {string} line - The line to compare against for similarity. + * @param {() => void} fullStop - Function to call when stopping the stream. + * @yields {string} Filtered lines until a similar line is encountered. + * + * @description + * This generator function processes the input stream, yielding lines until it encounters: + * 1. An exact match to the provided line. + * 2. A line that is considered repeated or very similar to the provided line. + * 3. For lines ending with brackets, it allows exact matches of trimmed content. + * When any of these conditions are met, it calls the fullStop function and stops yielding. + */ export async function* stopAtSimilarLine( stream: LineStream, line: string, @@ -87,6 +208,7 @@ export async function* stopAtSimilarLine( ): AsyncGenerator { const trimmedLine = line.trim(); const lineIsBracketEnding = isBracketEnding(trimmedLine); + for await (const nextLine of stream) { if (nextLine === line) { fullStop(); @@ -102,12 +224,17 @@ export async function* stopAtSimilarLine( fullStop(); break; } + yield nextLine; } } -const LINES_TO_STOP_AT = ["# End of file.", " void} fullStop - Function to call when stopping. + * @yields {string} Filtered lines until a stop phrase is encountered. + */ export async function* stopAtLines( stream: LineStream, fullStop: () => void, @@ -121,7 +248,11 @@ export async function* stopAtLines( } } -const PREFIXES_TO_SKIP = [""]; +/** + * Filters a LineStream, skipping specified prefixes on the first line. + * @param {LineStream} lines - The input stream of lines. + * @yields {string} Filtered lines with prefixes removed from the first line if applicable. + */ export async function* skipPrefixes(lines: LineStream): LineStream { let isFirstLine = true; for await (const line of lines) { @@ -137,8 +268,11 @@ export async function* skipPrefixes(lines: LineStream): LineStream { } } -const LINES_TO_SKIP = [""]; - +/** + * Filters out lines starting with specified prefixes from a LineStream. + * @param {LineStream} stream - The input stream of lines. + * @yields {string} Filtered lines that don't start with any of the LINES_TO_SKIP prefixes. + */ export async function* skipLines(stream: LineStream): LineStream { for await (const line of stream) { if (!LINES_TO_SKIP.some((skipAt) => line.startsWith(skipAt))) { @@ -147,34 +281,21 @@ export async function* skipLines(stream: LineStream): LineStream { } } -const LINES_TO_REMOVE_BEFORE_START = [ - "", - "[CODE]", - "", -]; - -function shouldRemoveLineBeforeStart(line: string): boolean { - return ( - line.trimStart().startsWith("```") || - LINES_TO_REMOVE_BEFORE_START.some((l) => line.trim() === l) - ); -} - -function shouldChangeLineAndStop(line: string): string | undefined { - if (line.trimStart() === "```") { - return line; - } - - if (line.includes("[/CODE]")) { - return line.split("[/CODE]")[0].trimEnd(); - } - - return undefined; -} - +/** + * Filters and processes lines from a code block, removing unnecessary markers and handling edge cases. + * + * @param {LineStream} rawLines - The input stream of lines to filter. + * @yields {string} Filtered and processed lines from the code block. + * + * @description + * This generator function performs the following tasks: + * 1. Removes initial lines that should be removed before the actual code starts. + * 2. Filters out ending code block markers (```) unless they are the last line. + * 3. Handles special cases where lines should be changed and the stream should stop. + * 4. Yields processed lines that are part of the actual code block content. + */ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { let seenValidLine = false; - let waitingToSeeIfLineIsLast = undefined; for await (const line of rawLines) { @@ -206,28 +327,19 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream { } } -function isEnglishFirstLine(line: string) { - line = line.trim().toLowerCase(); - if (line.endsWith(":") && !line.trimStart().startsWith("def")) { - return true; - } - if ( - line.startsWith("here is") || - line.startsWith("here's") || - line.startsWith("sure, here") || - line.startsWith("sure thing") || - line.startsWith("sure!") || - line.startsWith("to fill") || - line.startsWith("certainly") || - line.startsWith("of course") || - line.startsWith("the code should") - ) { - return true; - } - - return false; -} - +/** + * Filters out English explanations at the start of a code block. + * + * @param {LineStream} lines - The input stream of lines. + * @yields {string} Filtered lines with English explanations removed from the start. + * + * @description + * This generator function performs the following tasks: + * 1. Skips initial blank lines. + * 2. Removes the first line if it's identified as an English explanation. + * 3. Removes a subsequent blank line if the first line was an English explanation. + * 4. Yields all remaining lines. + */ export async function* filterEnglishLinesAtStart(lines: LineStream) { let i = 0; let wasEnglishFirstLine = false; @@ -235,6 +347,7 @@ export async function* filterEnglishLinesAtStart(lines: LineStream) { if (i === 0 && line.trim() === "") { continue; } + if (i === 0) { if (isEnglishFirstLine(line)) { wasEnglishFirstLine = true; @@ -250,18 +363,14 @@ export async function* filterEnglishLinesAtStart(lines: LineStream) { } } -function isEnglishPostExplanation(line: string): boolean { - const lower = line.toLowerCase(); - return ( - lower.startsWith("explanation:") || - lower.startsWith("here is") || - lower.startsWith("here's how") || - lower.startsWith("the above") - ); -} - +/** + * Filters out English explanations at the end of a code block. + * @param {LineStream} lines - The input stream of lines. + * @yields {string} Lines up to the end of the code block or start of English explanation. + */ export async function* filterEnglishLinesAtEnd(lines: LineStream) { let finishedCodeBlock = false; + for await (const line of lines) { if (line.trim() === "```") { finishedCodeBlock = true; @@ -273,8 +382,14 @@ export async function* filterEnglishLinesAtEnd(lines: LineStream) { } } +/** + * Removes leading indentation from the first line of a CodeLlama output. + * @param {LineStream} lines - The input stream of lines. + * @yields {string} Lines with the first line's indentation fixed if necessary. + */ export async function* fixCodeLlamaFirstLineIndentation(lines: LineStream) { let isFirstLine = true; + for await (const line of lines) { if (isFirstLine && line.startsWith(" ")) { yield line.slice(2); @@ -285,23 +400,36 @@ export async function* fixCodeLlamaFirstLineIndentation(lines: LineStream) { } } -function isUselessLine(line: string): boolean { - const trimmed = line.trim().toLowerCase(); - return trimmed === "" || trimmed === "```" || trimmed.startsWith("// end"); -} - +/** + * Filters leading and trailing blank line insertions from a stream of diff lines. + * + * @param {AsyncGenerator} diffLines - An async generator that yields DiffLine objects. + * @yields {DiffLine} Filtered DiffLine objects, with leading and trailing blank line insertions removed. + * + * @description + * This generator function processes a stream of diff lines, removing leading and trailing + * blank line insertions. It performs the following tasks: + * 1. Skips the first blank line insertion if it occurs at the beginning. + * 2. Buffers subsequent blank line insertions. + * 3. Yields buffered blank lines when a non-blank insertion is encountered. + * 4. Clears the buffer when an old line is encountered. + * 5. Yields all non-blank insertions and old lines. + */ export async function* filterLeadingAndTrailingNewLineInsertion( diffLines: AsyncGenerator, ): AsyncGenerator { let isFirst = true; let buffer: DiffLine[] = []; + for await (const diffLine of diffLines) { const isBlankLineInsertion = diffLine.type === "new" && isUselessLine(diffLine.line); + if (isFirst && isBlankLineInsertion) { isFirst = false; continue; } + isFirst = false; if (isBlankLineInsertion) { @@ -319,31 +447,38 @@ export async function* filterLeadingAndTrailingNewLineInsertion( } } +/** + * Filters a LineStream, stopping when a line repeats more than a specified number of times. + * + * @param {LineStream} lines - The input stream of lines to filter. + * @param {() => void} fullStop - Function to call when stopping the stream. + * @yields {string} Filtered lines until excessive repetition is detected. + * + * @description + * This function yields lines from the input stream until a line is repeated + * for a maximum of 3 consecutive times. When this limit is reached, it calls + * the fullStop function and stops yielding. Only the first of the repeating + * lines is yieled. + */ export async function* stopAtRepeatingLines( lines: LineStream, fullStop: () => void, ): LineStream { - const repeatedLines: string[] = []; + let previousLine: string | undefined; + let repeatCount = 0; + const MAX_REPEATS = 3; + for await (const line of lines) { - if (repeatedLines.length === 0) { - repeatedLines.push(line); - } else if (repeatedLines.length < 3) { - if (repeatedLines[repeatedLines.length - 1] === line) { - repeatedLines.push(line); - } else { - while (repeatedLines.length > 0) { - yield repeatedLines.shift()!; - } - yield line; + if (line === previousLine) { + repeatCount++; + if (repeatCount === MAX_REPEATS) { + fullStop(); + return; } } else { - yield repeatedLines[0]; - fullStop(); - return; + yield line; + repeatCount = 1; } - } - - while (repeatedLines.length > 0) { - yield repeatedLines.shift()!; + previousLine = line; } } diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/retrieval.ts index 635f52012..422b377bd 100644 --- a/core/autocomplete/retrieval.ts +++ b/core/autocomplete/retrieval.ts @@ -1,5 +1,5 @@ import { BranchAndDir, Chunk } from "../index.js"; -import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch.js"; +import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearchCodebaseIndex.js"; export async function fullTextRetrieve( prefix: string, diff --git a/core/autocomplete/templates.ts b/core/autocomplete/templates.ts index 53aa034a9..c0e5c132a 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/templates.ts @@ -70,7 +70,9 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`) .join("\n\n"); return [ - `${otherFiles}\n\n+++++ ${relativePaths[relativePaths.length - 1]}\n${prefix}`, + `${otherFiles}\n\n+++++ ${ + relativePaths[relativePaths.length - 1] + }\n${prefix}`, suffix, ]; }, @@ -172,8 +174,10 @@ const codegeexFimTemplate: AutocompleteTemplate = { ...snippets.map((snippet) => snippet.filepath), filepath, ]); - const baseTemplate = `###PATH:${relativePaths[relativePaths.length - 1]}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`; - if (snippets.length == 0) { + const baseTemplate = `###PATH:${ + relativePaths[relativePaths.length - 1] + }\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`; + if (snippets.length === 0) { return `<|user|>\n${baseTemplate}<|assistant|>\n`; } const references = `###REFERENCE:\n${snippets diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index ed5fa4dec..a7738a041 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/naming-convention */ import { IDE, SlashCommand } from "../.."; import * as fs from "fs/promises"; import * as path from "path"; diff --git a/core/test/config/ConfigHandler.skip.ts b/core/config/ConfigHandler.test.ts similarity index 83% rename from core/test/config/ConfigHandler.skip.ts rename to core/config/ConfigHandler.test.ts index ef35789cb..ef4e1814d 100644 --- a/core/test/config/ConfigHandler.skip.ts +++ b/core/config/ConfigHandler.test.ts @@ -1,11 +1,11 @@ import fs from "node:fs"; import path from "node:path"; -import { defaultConfig } from "../../config/default"; -import { getConfigTsPath } from "../../util/paths"; -import { testConfigHandler } from "../fixtures"; -import { TEST_DIR } from "../testUtils/testDir"; +import { defaultConfig } from "./default"; +import { getConfigTsPath } from "../util/paths"; +import { testConfigHandler } from "../test/util/fixtures"; +import { TEST_DIR } from "../test/util/testDir"; -describe("Test the ConfigHandler and E2E config loading", () => { +describe.skip("Test the ConfigHandler and E2E config loading", () => { test("should show only local profile", () => { const profiles = testConfigHandler.listProfiles(); expect(profiles.length).toBe(1); diff --git a/core/context/providers/PostgresContextProvider.ts b/core/context/providers/PostgresContextProvider.ts index 494a3bc33..55c00ae3c 100644 --- a/core/context/providers/PostgresContextProvider.ts +++ b/core/context/providers/PostgresContextProvider.ts @@ -37,7 +37,7 @@ class PostgresContextProvider extends BaseContextProvider { let tablesInfoQuery = ` SELECT table_schema, table_name FROM information_schema.tables`; - if (schema != null) { + if (schema !== null) { tablesInfoQuery += ` WHERE table_schema = '${schema}'`; } const { rows: tablesInfo } = await pool.query(tablesInfoQuery); diff --git a/core/context/rerankers/tei.ts b/core/context/rerankers/tei.ts index 667181ae3..61f38b98b 100644 --- a/core/context/rerankers/tei.ts +++ b/core/context/rerankers/tei.ts @@ -26,7 +26,7 @@ export class HuggingFaceTEIReranker implements Reranker { const resp = await fetch(new URL("rerank", apiBase), { method: "POST", - headers: { 'Content-Type': 'application/json' }, + headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: query, return_text: false, diff --git a/core/context/retrieval/fullTextSearch.ts b/core/context/retrieval/fullTextSearch.ts index 3e22db302..9c52bd6b6 100644 --- a/core/context/retrieval/fullTextSearch.ts +++ b/core/context/retrieval/fullTextSearch.ts @@ -1,5 +1,5 @@ import { BranchAndDir, Chunk } from "../../index.js"; -import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearch.js"; +import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js"; export async function retrieveFts( query: string, diff --git a/core/control-plane/analytics/LogStashAnalyticsProvider.ts b/core/control-plane/analytics/LogStashAnalyticsProvider.ts index 59d72432a..aa35af43e 100644 --- a/core/control-plane/analytics/LogStashAnalyticsProvider.ts +++ b/core/control-plane/analytics/LogStashAnalyticsProvider.ts @@ -30,7 +30,8 @@ export default class LogStashAnalyticsProvider implements IAnalyticsProvider { async setup(config: Analytics, uniqueId: string): Promise { if (!config.url) { - throw new Error("Missing url in analytics config"); + console.warn("LogStashAnalyticsProvider is missing a URL"); + return; } const url = new URL(config.url); this.host = url.hostname; diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 53e62d247..bee6061b2 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -74,7 +74,7 @@ export class ControlPlaneClient { } try { - const resp = await this.request(`/workspaces`, { + const resp = await this.request("/workspaces", { method: "GET", }); return (await resp.json()) as any; diff --git a/core/test/streamDiff.test.ts b/core/diff/streamDiff.test.ts similarity index 100% rename from core/test/streamDiff.test.ts rename to core/diff/streamDiff.test.ts diff --git a/core/index.d.ts b/core/index.d.ts index 8ce83c6f7..1dc806f88 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -58,6 +58,7 @@ export interface ILLM extends LLMOptions { title?: string; systemMessage?: string; contextLength: number; + maxStopWords?: number; completionOptions: CompletionOptions; requestOptions?: RequestOptions; promptTemplates?: Record; @@ -321,6 +322,7 @@ export interface LLMOptions { uniqueId?: string; systemMessage?: string; contextLength?: number; + maxStopWords?: number; completionOptions?: CompletionOptions; requestOptions?: RequestOptions; template?: TemplateType; @@ -608,7 +610,8 @@ type ModelProvider = | "azure" | "openai-aiohttp" | "msty" - | "watsonx"; + | "watsonx" + | "openrouter"; export type ModelName = | "AUTODETECT" @@ -747,6 +750,7 @@ export interface ModelDescription { apiKey?: string; apiBase?: string; contextLength?: number; + maxStopWords?: number; template?: TemplateType; completionOptions?: BaseCompletionOptions; systemMessage?: string; diff --git a/core/indexing/CodeSnippetsIndex.test.ts b/core/indexing/CodeSnippetsIndex.test.ts new file mode 100644 index 000000000..a80ffe7bd --- /dev/null +++ b/core/indexing/CodeSnippetsIndex.test.ts @@ -0,0 +1,83 @@ +import { jest } from "@jest/globals"; +import { testIde } from "../test/util/fixtures"; +import { + insertMockChunks, + updateIndexAndAwaitGenerator, + mockPathAndCacheKey, +} from "../test/util/indexing"; +import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { IndexResultType } from "./types"; + +describe("CodeSnippetsCodebaseIndex", () => { + let index: CodeSnippetsCodebaseIndex; + let db: DatabaseConnection; + + async function getAllSnippets() { + return await db.all("SELECT * FROM code_snippets"); + } + + async function getAllSnippetTags() { + return await db.all("SELECT * FROM code_snippets_tags"); + } + + beforeAll(async () => { + db = await SqliteDb.get(); + index = new CodeSnippetsCodebaseIndex(testIde); + }); + + it("should update the index and maintain expected database state", async () => { + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + const mockSnippet = { + title: "", + content: "", + startLine: 0, + endLine: 1, + }; + + // We mock this fn since currently in testing the directory structure to access the tree-sitter + // binaries does not match what is in the release environment. + jest + .spyOn(CodeSnippetsCodebaseIndex.prototype, "getSnippetsInFile") + .mockResolvedValue([mockSnippet]); + + await insertMockChunks(); + + // Compute test + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + expect((await getAllSnippetTags()).length).toBe(1); + expect((await getAllSnippets()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // RemoveTag test + await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); + expect((await getAllSnippetTags()).length).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + + // AddTag test + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + expect((await getAllSnippetTags()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + expect((await getAllSnippetTags()).length).toBe(0); + expect((await getAllSnippets()).length).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + }); +}); diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index e431dfdf8..4dd56e4c2 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -17,6 +17,7 @@ import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { IndexResultType, MarkCompleteCallback, + PathAndCacheKey, RefreshIndexResults, type CodebaseIndex, } from "./types.js"; @@ -100,26 +101,30 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { contents: string, ): Promise<(ChunkWithoutID & { title: string })[]> { const parser = await getParserForFile(filepath); + if (!parser) { return []; } + const ast = parser.parse(contents); const query = await getQueryForFile(filepath, TSQueryType.CodeSnippets); const matches = query?.matches(ast.rootNode); - return ( - matches?.flatMap((match) => { - const node = match.captures[0].node; - const title = match.captures[1].node.text; - const results = { - title, - content: node.text, - startLine: node.startPosition.row, - endLine: node.endPosition.row, - }; - return results; - }) ?? [] - ); + if (!matches) { + return []; + } + + return matches.flatMap((match) => { + const node = match.captures[0].node; + const title = match.captures[1].node.text; + const results = { + title, + content: node.text, + startLine: node.startPosition.row, + endLine: node.endPosition.row, + }; + return results; + }); } async *update( @@ -132,6 +137,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { await CodeSnippetsCodebaseIndex._createTables(db); const tagString = tagToString(tag); + // Compute for (let i = 0; i < results.compute.length; i++) { const compute = results.compute[i]; @@ -174,52 +180,46 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { markComplete([compute], IndexResultType.Compute); } + // Delete for (let i = 0; i < results.del.length; i++) { const del = results.del[i]; - const deleted = await db.run( - "DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?", + + const snippetToDelete = await db.get( + "SELECT id FROM code_snippets WHERE path = ? AND cacheKey = ?", [del.path, del.cacheKey], ); - await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [ - deleted.lastID, + + await db.run("DELETE FROM code_snippets WHERE id = ?", [ + snippetToDelete.id, ]); + + await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [ + snippetToDelete.id, + ]); + markComplete([del], IndexResultType.Delete); } + // Add tag for (let i = 0; i < results.addTag.length; i++) { const addTag = results.addTag[i]; - let snippets: (ChunkWithoutID & { title: string })[] = []; - try { - snippets = await this.getSnippetsInFile( - addTag.path, - await this.ide.readFile(addTag.path), - ); - } catch (e) { - // If can't parse, assume malformatted code - console.error(`Error parsing ${addTag.path}:`, e); - } - for (const snippet of snippets) { - const { lastID } = await db.run( - "REPLACE INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)", - [ - addTag.path, - addTag.cacheKey, - snippet.content, - snippet.title, - snippet.startLine, - snippet.endLine, - ], - ); - await db.run( - "REPLACE INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", - [lastID, tagString], - ); - } + await db.run( + ` + REPLACE INTO code_snippets_tags (tag, snippetId) + SELECT ?, ( + SELECT id + FROM code_snippets + WHERE cacheKey = ? AND path = ? + ) + `, + [tagString, addTag.cacheKey, addTag.path], + ); markComplete([results.addTag[i]], IndexResultType.AddTag); } + // Remove tag for (let i = 0; i < results.removeTag.length; i++) { const item = results.removeTag[i]; await db.run( diff --git a/core/test/indexing/CodebaseIndexer.skip.ts b/core/indexing/CodebaseIndexer.test.ts similarity index 89% rename from core/test/indexing/CodebaseIndexer.skip.ts rename to core/indexing/CodebaseIndexer.test.ts index 6d7d73c8d..221035737 100644 --- a/core/test/indexing/CodebaseIndexer.skip.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -2,20 +2,20 @@ import { jest } from "@jest/globals"; import { execSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; -import { ContinueServerClient } from "../../continueServer/stubs/client.js"; -import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js"; -import { getComputeDeleteAddRemove } from "../../indexing/refreshIndex.js"; -import { TestCodebaseIndex } from "../../indexing/TestCodebaseIndex.js"; -import { CodebaseIndex } from "../../indexing/types.js"; -import { walkDir } from "../../indexing/walkDir.js"; -import { getIndexSqlitePath } from "../../util/paths.js"; -import { testConfigHandler, testIde } from "../fixtures.js"; +import { ContinueServerClient } from "../continueServer/stubs/client.js"; +import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; +import { getComputeDeleteAddRemove } from "./refreshIndex.js"; +import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; +import { CodebaseIndex } from "./types.js"; +import { walkDir } from "./walkDir.js"; +import { getIndexSqlitePath } from "../util/paths.js"; +import { testConfigHandler, testIde } from "../test/util/fixtures.js"; import { addToTestDir, setUpTestDir, tearDownTestDir, TEST_DIR, -} from "../testUtils/testDir.js"; +} from "../test/util/testDir.js"; jest.useFakeTimers(); @@ -57,7 +57,7 @@ class TestCodebaseIndexer extends CodebaseIndexer { // These are more like integration tests, whereas we should separately test // the individual CodebaseIndex classes -describe("CodebaseIndexer", () => { +describe.skip("CodebaseIndexer", () => { const pauseToken = new PauseToken(false); const continueServerClient = new ContinueServerClient(undefined, undefined); const codebaseIndexer = new TestCodebaseIndexer( diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 293129627..da06bb0d9 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -6,7 +6,7 @@ import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceIn import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; -import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js"; +import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; import { LanceDbIndex } from "./LanceDbIndex.js"; import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { diff --git a/core/indexing/FullTextSearchCodebaseIndex.test.ts b/core/indexing/FullTextSearchCodebaseIndex.test.ts new file mode 100644 index 000000000..eaa614aff --- /dev/null +++ b/core/indexing/FullTextSearchCodebaseIndex.test.ts @@ -0,0 +1,67 @@ +import { jest } from "@jest/globals"; +import { + insertMockChunks, + updateIndexAndAwaitGenerator, + mockPathAndCacheKey, +} from "../test/util/indexing"; +import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { IndexResultType } from "./types"; + +describe("FullTextSearchCodebaseIndex", () => { + let index: FullTextSearchCodebaseIndex; + let db: DatabaseConnection; + + async function getFts() { + return await db.all("SELECT * FROM fts"); + } + + async function getFtsMetadata() { + return await db.all("SELECT * FROM fts_metadata"); + } + + beforeEach(async () => { + db = await SqliteDb.get(); + index = new FullTextSearchCodebaseIndex(); + }); + + it("should update the index and maintain expected database state", async () => { + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + await insertMockChunks(); + + // Compute test + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + expect((await getFts()).length).toBe(1); + expect((await getFtsMetadata()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // RemoveTag test - currently, we don't do anything other than mark complete + await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + + // AddTag test - currently, we don't do anything other than mark complete + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + expect((await getFts()).length).toBe(0); + expect((await getFtsMetadata()).length).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + }); +}); diff --git a/core/indexing/FullTextSearch.ts b/core/indexing/FullTextSearchCodebaseIndex.ts similarity index 87% rename from core/indexing/FullTextSearch.ts rename to core/indexing/FullTextSearchCodebaseIndex.ts index c640eae20..7a571bc13 100644 --- a/core/indexing/FullTextSearch.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -1,23 +1,19 @@ -import { - BranchAndDir, - Chunk, - IndexTag, - IndexingProgressUpdate, -} from "../index.js"; -import { getBasename } from "../util/index.js"; -import { RETRIEVAL_PARAMS } from "../util/parameters.js"; -import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; +import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../"; +import { getBasename } from "../util/index"; +import { RETRIEVAL_PARAMS } from "../util/parameters"; +import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { IndexResultType, MarkCompleteCallback, RefreshIndexResults, type CodebaseIndex, -} from "./types.js"; +} from "./types"; export class FullTextSearchCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 0.2; - artifactId = "sqliteFts"; + static artifactId = "sqliteFts"; + artifactId: string = ChunkCodebaseIndex.artifactId; private async _createTables(db: DatabaseConnection) { await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5( @@ -90,11 +86,12 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { // Delete for (const item of results.del) { - const { lastID } = await db.run( - "DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", - [item.path, item.cacheKey], - ); - await db.run("DELETE FROM fts WHERE rowid = ?", [lastID]); + await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [ + item.path, + item.cacheKey, + ]); + + await db.run("DELETE FROM fts WHERE path = ?", [item.path]); markComplete([item], IndexResultType.Delete); } diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts new file mode 100644 index 000000000..a8ba2173a --- /dev/null +++ b/core/indexing/LanceDbIndex.test.ts @@ -0,0 +1,115 @@ +import { jest } from "@jest/globals"; +import lance from "vectordb"; +import { testIde, testConfigHandler } from "../test/util/fixtures"; +import { + testContinueServerClient, + mockTag, + updateIndexAndAwaitGenerator, + mockPathAndCacheKey, +} from "../test/util/indexing"; +import { getLanceDbPath } from "../util/paths"; +import { LanceDbIndex } from "./LanceDbIndex"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { IndexResultType } from "./types"; + +jest.useFakeTimers(); + +describe("ChunkCodebaseIndex", () => { + let index: LanceDbIndex; + let sqliteDb: DatabaseConnection; + let lanceDb: lance.Connection; + + async function getAllSqliteLanceDbCache() { + return await sqliteDb.all("SELECT * FROM lance_db_cache"); + } + + beforeAll(async () => { + const pathSep = await testIde.pathSep(); + const mockConfig = await testConfigHandler.loadConfig(); + + index = new LanceDbIndex( + mockConfig.embeddingsProvider, + testIde.readFile.bind(testIde), + pathSep, + testContinueServerClient, + ); + + sqliteDb = await SqliteDb.get(); + lanceDb = await lance.connect(getLanceDbPath()); + }); + + /** + * Some notes on quirks of this test: + * - Currently, it appears that there is a race condition in LanceDB that + * requires us to re-open the table connection each time we want to read + * from it. Attempting to follow these docs did not resolve the issue: + * https://lancedb.github.io/lancedb/guides/tables/#consistency + * + * - We cannot open either the 'dev' or 'main' tag tables ubtil after we + * can assume they've been created through `updateIndexAndAwaitGenerator` + */ + it("should update the index and maintain expected database state", async () => { + const mainTag = mockTag; + const mainTagTableName = index.tableNameForTag(mainTag); + + const devTag = { ...mockTag, branch: "dev" }; + const devTagTableName = index.tableNameForTag(devTag); + + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + // Compute test - inserts into both LanceDB and Sqlite + await updateIndexAndAwaitGenerator( + index, + "compute", + mockMarkComplete, + mainTag, + ); + let mainTagTable = await lanceDb.openTable(mainTagTableName); + expect(await mainTagTable.countRows()).toBe(1); + expect((await getAllSqliteLanceDbCache()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // AddTag test - only inserts into Lance DB + await updateIndexAndAwaitGenerator( + index, + "addTag", + mockMarkComplete, + devTag, + ); + let devTagTable = await lanceDb.openTable(devTagTableName); + expect(await devTagTable.countRows()).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // RemoveTag - only removes from Lance DB + await updateIndexAndAwaitGenerator( + index, + "removeTag", + mockMarkComplete, + devTag, + ); + devTagTable = await lanceDb.openTable(devTagTableName); + expect(await devTagTable.countRows()).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + + // Delete test - removes from LanceDB and Sqlite + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete, mainTag); + mainTagTable = await lanceDb.openTable(mainTagTableName); + expect(await mainTagTable.countRows()).toBe(0); + expect((await getAllSqliteLanceDbCache()).length).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + }); +}); diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 12f8b1668..69e138ddc 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -21,6 +21,7 @@ import { PathAndCacheKey, RefreshIndexResults, } from "./types.js"; +import lance from "vectordb"; // LanceDB converts to lowercase, so names must all be lowercase interface LanceDbRow { @@ -48,7 +49,7 @@ export class LanceDbIndex implements CodebaseIndex { private readonly continueServerClient?: IContinueServerClient, ) {} - private tableNameForTag(tag: IndexTag) { + tableNameForTag(tag: IndexTag) { return tagToString(tag).replace(/[^\w-_.]/g, ""); } @@ -203,40 +204,39 @@ export class LanceDbIndex implements CodebaseIndex { markComplete: MarkCompleteCallback, repoName: string | undefined, ): AsyncGenerator { - const lancedb = await import("vectordb"); - const tableName = this.tableNameForTag(tag); - const db = await lancedb.connect(getLanceDbPath()); + const sqliteDb = await SqliteDb.get(); + await this.createSqliteCacheTable(sqliteDb); - const sqlite = await SqliteDb.get(); - await this.createSqliteCacheTable(sqlite); + const lanceTableName = this.tableNameForTag(tag); + const lanceDb = await lance.connect(getLanceDbPath()); + const existingLanceTables = await lanceDb.tableNames(); + + let lanceTable: Table | undefined = undefined; + let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName); // Compute - let table: Table | undefined = undefined; - const existingTables = await db.tableNames(); - let needToCreateTable = !existingTables.includes(tableName); - const addComputedLanceDbRows = async ( - pathAndCacheKey: PathAndCacheKey, + pathAndCacheKeys: PathAndCacheKey[], computedRows: LanceDbRow[], ) => { // Create table if needed, add computed rows - if (table) { + if (lanceTable) { if (computedRows.length > 0) { - await table.add(computedRows); + await lanceTable.add(computedRows); } - } else if (existingTables.includes(tableName)) { - table = await db.openTable(tableName); - needToCreateTable = false; + } else if (existingLanceTables.includes(lanceTableName)) { + lanceTable = await lanceDb.openTable(lanceTableName); + needToCreateLanceTable = false; if (computedRows.length > 0) { - await table.add(computedRows); + await lanceTable.add(computedRows); } } else if (computedRows.length > 0) { - table = await db.createTable(tableName, computedRows); - needToCreateTable = false; + lanceTable = await lanceDb.createTable(lanceTableName, computedRows); + needToCreateLanceTable = false; } // Mark item complete - await markComplete([pathAndCacheKey], IndexResultType.Compute); + await markComplete(pathAndCacheKeys, IndexResultType.Compute); }; // Check remote cache @@ -272,7 +272,7 @@ export class LanceDbIndex implements CodebaseIndex { }; rows.push(row); - await sqlite.run( + await sqliteDb.run( "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", row.uuid, row.cachekey, @@ -285,7 +285,7 @@ export class LanceDbIndex implements CodebaseIndex { ); } - await addComputedLanceDbRows({ cacheKey, path }, rows); + await addComputedLanceDbRows([{ cacheKey, path }], rows); } // Remove items that don't need to be recomputed @@ -306,24 +306,13 @@ export class LanceDbIndex implements CodebaseIndex { }; const dbRows = await this.computeRows(results.compute); - await this.insertRows(sqlite, dbRows); - await Promise.all( - results.compute.map((result) => { - addComputedLanceDbRows( - result, - dbRows.filter( - (row) => - row.path === result.path && row.cachekey === result.cacheKey, - ), - ); - }), - ); - await markComplete(results.compute, IndexResultType.Compute); + await this.insertRows(sqliteDb, dbRows); + await addComputedLanceDbRows(results.compute, dbRows); let accumulatedProgress = 0; // Add tag - retrieve the computed info from lance sqlite cache for (const { path, cacheKey } of results.addTag) { - const stmt = await sqlite.prepare( + const stmt = await sqliteDb.prepare( "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", cacheKey, path, @@ -331,25 +320,28 @@ export class LanceDbIndex implements CodebaseIndex { ); const cachedItems = await stmt.all(); - const lanceRows: LanceDbRow[] = cachedItems.map((item) => { - return { + const lanceRows: LanceDbRow[] = cachedItems.map( + ({ uuid, vector, startLine, endLine, contents }) => ({ path, + uuid, + startLine, + endLine, + contents, cachekey: cacheKey, - uuid: item.uuid, - vector: JSON.parse(item.vector), - }; - }); + vector: JSON.parse(vector), + }), + ); if (lanceRows.length > 0) { - if (needToCreateTable) { - table = await db.createTable(tableName, lanceRows); - needToCreateTable = false; - } else if (!table) { - table = await db.openTable(tableName); - needToCreateTable = false; - await table.add(lanceRows); + if (needToCreateLanceTable) { + lanceTable = await lanceDb.createTable(lanceTableName, lanceRows); + needToCreateLanceTable = false; + } else if (!lanceTable) { + lanceTable = await lanceDb.openTable(lanceTableName); + needToCreateLanceTable = false; + await lanceTable.add(lanceRows); } else { - await table?.add(lanceRows); + await lanceTable?.add(lanceRows); } } @@ -363,11 +355,18 @@ export class LanceDbIndex implements CodebaseIndex { } // Delete or remove tag - remove from lance table) - if (!needToCreateTable) { + if (!needToCreateLanceTable) { const toDel = [...results.removeTag, ...results.del]; + + if (!lanceTable) { + lanceTable = await lanceDb.openTable(lanceTableName); + } + for (const { path, cacheKey } of toDel) { // This is where the aforementioned lowercase conversion problem shows - await table?.delete(`cachekey = '${cacheKey}' AND path = '${path}'`); + await lanceTable.delete( + `cachekey = '${cacheKey}' AND path = '${path}'`, + ); accumulatedProgress += 1 / toDel.length / 3; yield { @@ -377,11 +376,12 @@ export class LanceDbIndex implements CodebaseIndex { }; } } + await markComplete(results.removeTag, IndexResultType.RemoveTag); // Delete - also remove from sqlite cache for (const { path, cacheKey } of results.del) { - await sqlite.run( + await sqliteDb.run( "DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", cacheKey, path, @@ -396,6 +396,7 @@ export class LanceDbIndex implements CodebaseIndex { } await markComplete(results.del, IndexResultType.Delete); + yield { progress: 1, desc: "Completed Calculating Embeddings", @@ -417,8 +418,7 @@ export class LanceDbIndex implements CodebaseIndex { return []; } - const table = await db.openTable(tableName); - let query = table.search(vector); + let query = db.search(vector); if (directory) { // seems like lancedb is only post-filtering, so have to return a bunch of results and slice after query = query.where(`path LIKE '${directory}%'`).limit(300); @@ -435,12 +435,8 @@ export class LanceDbIndex implements CodebaseIndex { tags: BranchAndDir[], filterDirectory: string | undefined, ): Promise { - const lancedb = await import("vectordb"); - if (!lancedb.connect) { - throw new Error("LanceDB failed to load a native module"); - } const [vector] = await this.embeddingsProvider.embed([query]); - const db = await lancedb.connect(getLanceDbPath()); + const db = await lance.connect(getLanceDbPath()); let allResults = []; for (const tag of tags) { diff --git a/core/indexing/README.md b/core/indexing/README.md index b0f8d408a..2a7375f00 100644 --- a/core/indexing/README.md +++ b/core/indexing/README.md @@ -23,8 +23,8 @@ All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./ `CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file `FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5 `ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex` -`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite +`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB. -## Known problems: +## Known problems - `FullTextSearchCodebaseIndex` doesn't differentiate between tags (branch, repo), so results may come from any branch/repo. LanceDB does this by creating separate tables for each tag (see `tableNameForTag`). The chunk index does this with a second table diff --git a/core/indexing/TestCodebaseIndex.ts b/core/indexing/TestCodebaseIndex.ts index 234bcbc3e..7031fd992 100644 --- a/core/indexing/TestCodebaseIndex.ts +++ b/core/indexing/TestCodebaseIndex.ts @@ -35,14 +35,14 @@ export class TestCodebaseIndex implements CodebaseIndex { for (const item of [...results.compute, ...results.addTag]) { await db.run( - `INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)`, + "INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)", [item.path, tag.branch, tag.directory], ); } for (const item of [...results.del, ...results.removeTag]) { await db.run( - `DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?`, + "DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?", [item.path, tag.branch, tag.directory], ); } diff --git a/core/indexing/chunk/ChunkCodebaseIndex.test.ts b/core/indexing/chunk/ChunkCodebaseIndex.test.ts new file mode 100644 index 000000000..ac98d0094 --- /dev/null +++ b/core/indexing/chunk/ChunkCodebaseIndex.test.ts @@ -0,0 +1,83 @@ +import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex"; +import { DatabaseConnection, SqliteDb } from "../refreshIndex"; +import { IndexResultType } from "../types"; +import { testIde } from "../../test/util/fixtures"; +import { addToTestDir } from "../../test/util/testDir"; +import { jest } from "@jest/globals"; +import { + mockFileContents, + mockFilename, + mockPathAndCacheKey, + testContinueServerClient, + updateIndexAndAwaitGenerator, +} from "../../test/util/indexing"; + +jest.useFakeTimers(); + +describe("ChunkCodebaseIndex", () => { + let index: ChunkCodebaseIndex; + let db: DatabaseConnection; + + async function getAllChunks() { + return await db.all("SELECT * FROM chunks"); + } + + async function getAllChunkTags() { + return await db.all("SELECT * FROM chunk_tags"); + } + + beforeAll(async () => { + const pathSep = await testIde.pathSep(); + + index = new ChunkCodebaseIndex( + testIde.readFile.bind(testIde), + pathSep, + testContinueServerClient, + 1000, + ); + + addToTestDir([[mockFilename, mockFileContents]]); + + db = await SqliteDb.get(); + }); + + it("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => { + const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + + // Compute test + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + expect((await getAllChunks()).length).toBe(1); + expect((await getAllChunkTags()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Compute, + ); + + // RemoveTag test + await updateIndexAndAwaitGenerator(index, "removeTag", mockMarkComplete); + expect((await getAllChunkTags()).length).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.RemoveTag, + ); + + // AddTag test + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); + expect((await getAllChunkTags()).length).toBe(1); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.AddTag, + ); + + // Delete test + await updateIndexAndAwaitGenerator(index, "del", mockMarkComplete); + expect((await getAllChunks()).length).toBe(0); + expect((await getAllChunkTags()).length).toBe(0); + expect(mockMarkComplete).toHaveBeenCalledWith( + [mockPathAndCacheKey], + IndexResultType.Delete, + ); + }); +}); diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index 498e5144e..b7e239eea 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -117,13 +117,16 @@ export class ChunkCodebaseIndex implements CodebaseIndex { // Delete for (const item of results.del) { - const deleted = await db.run("DELETE FROM chunks WHERE cacheKey = ?", [ - item.cacheKey, - ]); + const chunkToDelete = await db.get( + "SELECT id FROM chunks WHERE cacheKey = ?", + [item.cacheKey], + ); + + await db.run("DELETE FROM chunks WHERE id = ?", [chunkToDelete.id]); // Delete from chunk_tags await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [ - deleted.lastID, + chunkToDelete.id, ]); await markComplete([item], IndexResultType.Delete); @@ -238,8 +241,4 @@ export class ChunkCodebaseIndex implements CodebaseIndex { }); }); } - - private formatListPlurality(word: string, length: number): string { - return length <= 1 ? word : `${word}s`; - } } diff --git a/core/test/indexing/chunk/chunk.test.ts b/core/indexing/chunk/chunk.test.ts similarity index 94% rename from core/test/indexing/chunk/chunk.test.ts rename to core/indexing/chunk/chunk.test.ts index e45c11c79..a9559ca27 100644 --- a/core/test/indexing/chunk/chunk.test.ts +++ b/core/indexing/chunk/chunk.test.ts @@ -1,5 +1,5 @@ import path from "path"; -import { shouldChunk } from "../../../indexing/chunk/chunk"; +import { shouldChunk } from "./chunk"; describe("shouldChunk", () => { test("should chunk a typescript file", () => { diff --git a/core/test/indexing/chunk/code.test.ts b/core/indexing/chunk/code.test.ts similarity index 85% rename from core/test/indexing/chunk/code.test.ts rename to core/indexing/chunk/code.test.ts index 00615d124..c852ecafd 100644 --- a/core/test/indexing/chunk/code.test.ts +++ b/core/indexing/chunk/code.test.ts @@ -1,5 +1,5 @@ -import { ChunkWithoutID } from "../../../index.js"; -import { codeChunker } from "../../../indexing/chunk/code.js"; +import { ChunkWithoutID } from "../.."; +import { codeChunker } from "./code"; async function genToArr(generator: AsyncGenerator): Promise { const result: T[] = []; @@ -29,7 +29,7 @@ describe.skip("codeChunker", () => { test("should capture small class and function from large python file", async () => { const extraLine = "# This is a comment"; const myClass = "class MyClass:\n def __init__(self):\n pass"; - const myFunction = 'def my_function():\n return "Hello, World!"'; + const myFunction = "def my_function():\n return \"Hello, World!\""; const file = Array(100).fill(extraLine).join("\n") + @@ -66,7 +66,7 @@ describe.skip("codeChunker", () => { chunks[0].startsWith("class MyClass:\n def method1():\n ..."), ).toBe(true); // The extra spaces seem to be a bug with tree-sitter-python - expect(chunks).toContain('def method1():\n return "Hello, 1!"'); - expect(chunks).toContain('def method20():\n return "Hello, 20!"'); + expect(chunks).toContain("def method1():\n return \"Hello, 1!\""); + expect(chunks).toContain("def method20():\n return \"Hello, 20!\""); }); }); diff --git a/core/test/indexing/DocsService.skip.ts b/core/indexing/docs/DocsService.test.ts similarity index 87% rename from core/test/indexing/DocsService.skip.ts rename to core/indexing/docs/DocsService.test.ts index da688dbe1..f1fb6295b 100644 --- a/core/test/indexing/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -1,16 +1,14 @@ /** * @jest-environment jsdom */ -import * as fs from "fs"; -import * as path from "path"; import { ConfigHandler } from "../../config/ConfigHandler.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { SiteIndexingConfig } from "../../index.js"; -import DocsService from "../../indexing/docs/DocsService.js"; -import preIndexedDocs from "../../indexing/docs/preIndexedDocs.js"; -import FreeTrialEmbeddingsProvider from "../../indexing/embeddings/FreeTrialEmbeddingsProvider.js"; +import DocsService from "./DocsService.js"; +import preIndexedDocs from "./preIndexedDocs.js"; +import FreeTrialEmbeddingsProvider from "../embeddings/FreeTrialEmbeddingsProvider.js"; import FileSystemIde from "../../util/filesystem.js"; -import { editConfigJson, getConfigJsonPath } from "../../util/paths.js"; +import { editConfigJson } from "../../util/paths.js"; describe.skip("DocsService Integration Tests", () => { let ide: FileSystemIde; @@ -23,13 +21,6 @@ describe.skip("DocsService Integration Tests", () => { faviconUrl: "https://github.com/favicon.ico", }; - async function clearConfigDir() { - const configFolder = path.dirname(getConfigJsonPath()); - if (fs.existsSync(configFolder)) { - fs.rmSync(configFolder, { recursive: true, force: true }); - } - } - /** * We need to reload config explicitly to handle the scenario where the * config file update listeners are not called before we attempt to @@ -43,8 +34,6 @@ describe.skip("DocsService Integration Tests", () => { } beforeEach(async () => { - await clearConfigDir(); - ide = new FileSystemIde(process.cwd()); configHandler = new ConfigHandler( @@ -75,10 +64,6 @@ describe.skip("DocsService Integration Tests", () => { await docsService.isInitialized; }); - afterAll(async () => { - await clearConfigDir(); - }); - test("Indexing, retrieval, and deletion of a new documentation site", async () => { const generator = docsService.indexAndAdd(mockSiteConfig); while (!(await generator.next()).done) {} diff --git a/core/test/indexing/crawl.test.ts b/core/indexing/docs/crawl.test.ts similarity index 100% rename from core/test/indexing/crawl.test.ts rename to core/indexing/docs/crawl.test.ts diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 1cb34ba6f..877002322 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/naming-convention */ import { SiteIndexingConfig } from "../../index.js"; const preIndexedDocs: Record< diff --git a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts index 1bb7af75a..d3c22f3f0 100644 --- a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts +++ b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts @@ -37,9 +37,7 @@ class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider { requests, }), headers: { - // eslint-disable-next-line @typescript-eslint/naming-convention "x-goog-api-key": this.options.apiKey, - // eslint-disable-next-line @typescript-eslint/naming-convention "Content-Type": "application/json", }, }), diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index f39dee4fa..acf3d81e8 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -19,13 +19,10 @@ export const allEmbeddingsProviders: Record< EmbeddingsProviderConstructor > = { ollama: OllamaEmbeddingsProvider, - // eslint-disable-next-line @typescript-eslint/naming-convention "transformers.js": TransformersJsEmbeddingsProvider, openai: OpenAIEmbeddingsProvider, cohere: CohereEmbeddingsProvider, - // eslint-disable-next-line @typescript-eslint/naming-convention "free-trial": FreeTrialEmbeddingsProvider, - // eslint-disable-next-line @typescript-eslint/naming-convention "huggingface-tei": HuggingFaceTEIEmbeddingsProvider, gemini: GeminiEmbeddingsProvider, "continue-proxy": ContinueProxyEmbeddingsProvider, diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 10fe55605..c60a1a4d3 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -113,11 +113,6 @@ async function getSavedItemsForTag( return rows; } -interface PathAndOptionalCacheKey { - path: string; - cacheKey?: string; -} - enum AddRemoveResultType { Add = "add", Remove = "remove", @@ -409,7 +404,7 @@ export async function getComputeDeleteAddRemove( for await (const _ of globalCacheIndex.update( tag, results, - async () => { }, + async () => {}, repoName, )) { } diff --git a/core/test/walkDir.test.ts b/core/indexing/walkDir.test.ts similarity index 94% rename from core/test/walkDir.test.ts rename to core/indexing/walkDir.test.ts index 87f643f4e..7fa5ed00c 100644 --- a/core/test/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -1,12 +1,12 @@ import path from "path"; -import { walkDir, WalkerOptions } from "../indexing/walkDir.js"; -import FileSystemIde from "../util/filesystem.js"; +import { walkDir, WalkerOptions } from "../indexing/walkDir"; +import FileSystemIde from "../util/filesystem"; import { - addToTestDir, + TEST_DIR, setUpTestDir, tearDownTestDir, - TEST_DIR, -} from "./testUtils/testDir.js"; + addToTestDir, +} from "../test/util/testDir"; const ide = new FileSystemIde(TEST_DIR); @@ -191,6 +191,22 @@ describe("walkDir", () => { await expectPaths(["a.txt"], ["ignored_dir/b.txt", "ignored_dir/c/d.py"]); }); + test("gitignore in sub directory should only apply to subdirectory", async () => { + const files = [ + [".gitignore", "abc"], + "a.txt", + "abc", + "xyz/", + ["xyz/.gitignore", "xyz"], + "xyz/b.txt", + "xyz/c/", + "xyz/c/d.py", + "xyz/xyz", + ]; + addToTestDir(files); + await expectPaths(["a.txt", "xyz/b.txt", "xyz/c/d.py"], ["abc", "xyz/xyz"]); + }); + test("should handle complex patterns in .gitignore", async () => { const files = [ [".gitignore", "*.what\n!important.what\ntemp/\n/root_only.txt"], diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 014753daf..eeeb064d0 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -29,7 +29,12 @@ type WalkableEntry = { // helper struct used for the DFS walk type WalkContext = { walkableEntry: WalkableEntry; + ignoreContexts: IgnoreContext[]; +}; + +type IgnoreContext = { ignore: Ignore; + dirname: string; }; class DFSWalker { @@ -51,30 +56,22 @@ class DFSWalker { this.options.returnRelativePaths ? "" : this.path, this.ide, ); - const root: WalkContext = { - walkableEntry: { - relPath: "", - absPath: this.path, - type: 2 as FileType.Directory, - entry: ["", 2 as FileType.Directory], - }, - ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile), - }; + const root = this.newRootWalkContext(); const stack = [root]; for (let cur = stack.pop(); cur; cur = stack.pop()) { const walkableEntries = await this.listDirForWalking(cur.walkableEntry); - const ignore = await this.getIgnoreToApplyInDir( - cur.ignore, + const ignoreContexts = await this.getIgnoreToApplyInDir( + cur, walkableEntries, ); for (const w of walkableEntries) { - if (!this.shouldInclude(w, ignore)) { + if (!this.shouldInclude(w, ignoreContexts)) { continue; } if (this.entryIsDirectory(w.entry)) { stack.push({ walkableEntry: w, - ignore: ignore, + ignoreContexts: ignoreContexts, }); if (this.options.onlyDirs) { // when onlyDirs is enabled the walker will only return directory names @@ -87,6 +84,23 @@ class DFSWalker { } } + private newRootWalkContext(): WalkContext { + return { + walkableEntry: { + relPath: "", + absPath: this.path, + type: 2 as FileType.Directory, + entry: ["", 2 as FileType.Directory], + }, + ignoreContexts: [ + { + ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile), + dirname: "", + }, + ], + }; + } + private async listDirForWalking( walkableEntry: WalkableEntry, ): Promise { @@ -102,15 +116,22 @@ class DFSWalker { } private async getIgnoreToApplyInDir( - parentIgnore: Ignore, - walkableEntries: WalkableEntry[], - ): Promise { - const ignoreFilesInDir = await this.loadIgnoreFiles(walkableEntries); + curDir: WalkContext, + entriesInDir: WalkableEntry[], + ): Promise { + const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir); if (ignoreFilesInDir.length === 0) { - return parentIgnore; + return curDir.ignoreContexts; } const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat(); - return ignore().add(parentIgnore).add(patterns); + const newIgnoreContext = { + ignore: ignore().add(patterns), + dirname: curDir.walkableEntry.relPath, + }; + return [ + ...curDir.ignoreContexts, + newIgnoreContext + ]; } private async loadIgnoreFiles(entries: WalkableEntry[]): Promise { @@ -126,7 +147,7 @@ class DFSWalker { return this.ignoreFileNames.has(p); } - private shouldInclude(walkableEntry: WalkableEntry, ignore: Ignore) { + private shouldInclude(walkableEntry: WalkableEntry, ignoreContexts: IgnoreContext[]) { if (this.entryIsSymlink(walkableEntry.entry)) { // If called from the root, a symlink either links to a real file in this repository, // and therefore will be walked OR it linksto something outside of the repository and @@ -141,7 +162,17 @@ class DFSWalker { return false; } } - return !ignore.ignores(relPath); + for (const ig of ignoreContexts) { + // remove the directory name and path seperator from the match path, unless this an ignore file + // in the root directory + const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; + // The ignore library expects a path relative to the ignore file location + const matchPath = relPath.substring(prefixLength); + if (ig.ignore.ignores(matchPath)) { + return false; + } + } + return true; } private entryIsDirectory(entry: Entry) { diff --git a/core/jest.global-setup.ts b/core/jest.global-setup.ts index cf374a702..ee9cddde4 100644 --- a/core/jest.global-setup.ts +++ b/core/jest.global-setup.ts @@ -1,9 +1,5 @@ -import fs from "fs"; import path from "path"; export default async function () { process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test"); - if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) { - fs.rmSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true }); - } } diff --git a/core/jest.setup-after-env.ts b/core/jest.setup-after-env.ts index d4b86824a..a89c28ff0 100644 --- a/core/jest.setup-after-env.ts +++ b/core/jest.setup-after-env.ts @@ -2,6 +2,7 @@ import { TextEncoder, TextDecoder } from "util"; import fetch, { Request, Response } from "node-fetch"; import { jest } from "@jest/globals"; +import fs from "fs"; if (process.env.DEBUG === "jest") { jest.setTimeout(5 * 60 * 1000); @@ -14,3 +15,17 @@ globalThis.Request = Request; globalThis.Response = Response; globalThis.TextEncoder = TextEncoder; globalThis.TextDecoder = TextDecoder; + +globalThis.beforeAll(() => { + // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` + if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { + fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); + } +}); + +globalThis.afterAll(() => { + // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` + if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { + fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); + } +}); diff --git a/core/llm/asyncEncoder.test.ts b/core/llm/asyncEncoder.test.ts new file mode 100644 index 000000000..9ed5eb80a --- /dev/null +++ b/core/llm/asyncEncoder.test.ts @@ -0,0 +1,45 @@ +import { LlamaAsyncEncoder, GPTAsyncEncoder } from "./asyncEncoder"; + +describe("llama encoder", () => { + var tokenizer: LlamaAsyncEncoder; + + beforeAll(() => { + tokenizer = new LlamaAsyncEncoder(); + }); + + afterAll(() => { + tokenizer.close(); + }); + + test("hello world", async () => { + const input = "the quick brown fox jumped over the lazy dog"; + const output = await tokenizer.encode(input); + expect(output).toEqual([ + 1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203, + ]); + const decoded = await tokenizer.decode(output); + expect(decoded).toBe(input); + }); +}); + +describe("tiktoken encoder", () => { + var tokenizer: GPTAsyncEncoder; + + beforeAll(() => { + tokenizer = new GPTAsyncEncoder(); + }); + + afterAll(() => { + tokenizer.close(); + }); + + test("hello world", async () => { + const input = "the quick brown fox jumped over the lazy dog"; + const output = await tokenizer.encode(input); + expect(output).toEqual([ + 1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679, + ]); + const decoded = await tokenizer.decode(output); + expect(decoded).toBe(input); + }); +}); diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index e1d184b80..1696bd674 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -80,7 +80,7 @@ function modelSupportsImages( title: string | undefined, capabilities: ModelCapability | undefined ): boolean { - if (capabilities?.uploadImage !== undefined) return capabilities.uploadImage + if (capabilities?.uploadImage !== undefined) {return capabilities.uploadImage;} if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) { return false; } diff --git a/core/test/baseLLM.test.ts b/core/llm/index.test.ts similarity index 97% rename from core/test/baseLLM.test.ts rename to core/llm/index.test.ts index b49c9ac39..926b61209 100644 --- a/core/test/baseLLM.test.ts +++ b/core/llm/index.test.ts @@ -1,5 +1,5 @@ -import { ChatMessage, LLMOptions, ModelProvider } from "../index.js"; -import { BaseLLM } from "../llm/index.js"; +import { ChatMessage, LLMOptions, ModelProvider } from ".."; +import { BaseLLM } from "."; class DummyLLM extends BaseLLM { static providerName: ModelProvider = "openai"; diff --git a/core/llm/index.ts b/core/llm/index.ts index ca3c032a6..73a0151e9 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -91,6 +91,7 @@ export abstract class BaseLLM implements ILLM { title?: string; systemMessage?: string; contextLength: number; + maxStopWords?: number | undefined; completionOptions: CompletionOptions; requestOptions?: RequestOptions; template?: TemplateType; @@ -143,6 +144,7 @@ export abstract class BaseLLM implements ILLM { this.systemMessage = options.systemMessage; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; + this.maxStopWords = options.maxStopWords ?? this.maxStopWords; this.completionOptions = { ...options.completionOptions, model: options.model || "gpt-4", diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index e8342b546..105a2e20c 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -13,7 +13,7 @@ class Deepseek extends OpenAI { }, useLegacyCompletionsEndpoint: false, }; - protected maxStopWords: number | undefined = 16; + maxStopWords: number | undefined = 16; supportsFim(): boolean { return true; diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index e4c1674e6..9fc59313b 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -31,7 +31,7 @@ class FreeTrial extends BaseLLM { private async _countTokens(prompt: string, model: string, isPrompt: boolean) { if (!Telemetry.client) { throw new Error( - 'In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set "allowAnonymousTelemetry": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.', + "In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set \"allowAnonymousTelemetry\": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.", ); } const event = isPrompt diff --git a/core/llm/llms/Groq.ts b/core/llm/llms/Groq.ts index 27c51e1e3..7115bcc32 100644 --- a/core/llm/llms/Groq.ts +++ b/core/llm/llms/Groq.ts @@ -6,7 +6,7 @@ class Groq extends OpenAI { static defaultOptions: Partial = { apiBase: "https://api.groq.com/openai/v1/", }; - protected maxStopWords: number | undefined = 4; + maxStopWords: number | undefined = 4; private static modelConversion: { [key: string]: string } = { "llama2-70b": "llama2-70b-4096", diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index fcce902c8..f830b7f0f 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -61,7 +61,7 @@ class Ollama extends BaseLLM { this.completionOptions.stop.push(JSON.parse(value)); } catch (e) { console.warn( - 'Error parsing stop parameter value "{value}: ${e}', + "Error parsing stop parameter value \"{value}: ${e}", ); } break; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index cea8ec524..4a7477102 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -42,7 +42,7 @@ const CHAT_ONLY_MODELS = [ class OpenAI extends BaseLLM { public useLegacyCompletionsEndpoint: boolean | undefined = undefined; - protected maxStopWords: number | undefined = undefined; + maxStopWords: number | undefined = undefined; constructor(options: LLMOptions) { super(options); @@ -104,13 +104,13 @@ class OpenAI extends BaseLLM { this.maxStopWords !== undefined ? options.stop?.slice(0, this.maxStopWords) : 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" - ? options.stop?.slice(0, 4) - : options.stop, + ? options.stop?.slice(0, 16) + : url.port === "1337" || + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" + ? options.stop?.slice(0, 4) + : options.stop, }; return finalOptions; diff --git a/core/llm/llms/OpenRouter.ts b/core/llm/llms/OpenRouter.ts new file mode 100644 index 000000000..d01a19ec5 --- /dev/null +++ b/core/llm/llms/OpenRouter.ts @@ -0,0 +1,17 @@ +import { LLMOptions, ModelProvider } from "../../index.js"; +import { osModelsEditPrompt } from "../templates/edit.js"; +import OpenAI from "./OpenAI.js"; + +class OpenRouter extends OpenAI { + static providerName: ModelProvider = "openrouter"; + static defaultOptions: Partial = { + apiBase: "https://openrouter.ai/api/v1/", + model: "gpt-4o-mini", + promptTemplates: { + edit: osModelsEditPrompt, + }, + useLegacyCompletionsEndpoint: false, + }; +} + +export default OpenRouter; diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index 6a5890e67..a59de352c 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -55,7 +55,7 @@ class SageMaker extends BaseLLM { let position; while ((position = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, position); - const data = JSON.parse(line.replace(/^data:/, '')); + const data = JSON.parse(line.replace(/^data:/, "")); if ("choices" in data) { yield data.choices[0].delta.content; } @@ -94,7 +94,7 @@ class SageMaker extends BaseLLM { let position; while ((position = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, position); - const data = JSON.parse(line.replace(/^data:/, '')); + const data = JSON.parse(line.replace(/^data:/, "")); if ("choices" in data) { yield { role: "assistant", content: data.choices[0].delta.content }; } @@ -143,7 +143,7 @@ class MessageAPIToolkit implements SageMakerModelToolkit { let prompt = jinja.compile(this.sagemaker.completionOptions.chat_template).render( { messages: messages, add_generation_prompt: true }, { autoEscape: false } - ) + ); const payload = { inputs: prompt, parameters: this.sagemaker.completionOptions, diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 747a10c6a..5a18ab932 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -13,13 +13,16 @@ const watsonxConfig = { }, }; class WatsonX extends BaseLLM { - protected maxStopWords: number | undefined = undefined; + maxStopWords: number | undefined = undefined; constructor(options: LLMOptions) { super(options); } async getBearerToken(): Promise<{ token: string; expiration: number }> { - if (this.watsonxUrl != null && this.watsonxUrl.includes("cloud.ibm.com")) { + if ( + this.watsonxUrl !== null && + this.watsonxUrl!.includes("cloud.ibm.com") + ) { // watsonx SaaS const wxToken = await ( await fetch( @@ -125,7 +128,9 @@ class WatsonX extends BaseLLM { protected _getHeaders() { return { "Content-Type": "application/json", - Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"} ${watsonxConfig.accessToken.token}`, + Authorization: `${ + watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxConfig.accessToken.token}`, }; } @@ -169,21 +174,27 @@ class WatsonX extends BaseLLM { watsonxConfig.accessToken = await this.getBearerToken(); } else { console.log( - `Reusing token (expires in ${(watsonxConfig.accessToken.expiration - now) / 60} mins)`, + `Reusing token (expires in ${ + (watsonxConfig.accessToken.expiration - now) / 60 + } mins)`, ); } if (watsonxConfig.accessToken.token === undefined) { - throw new Error(`Something went wrong. Check your credentials, please.`); + throw new Error("Something went wrong. Check your credentials, please."); } - const stopToken = this.watsonxStopToken ?? (options.model.includes("granite") ? "<|im_end|>" : undefined); + const stopToken = + this.watsonxStopToken ?? + (options.model.includes("granite") ? "<|im_end|>" : undefined); var streamResponse = await fetch( `${this.watsonxUrl}/ml/v1/text/generation_stream?version=2023-05-29`, { method: "POST", headers: { "Content-Type": "application/json", - Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"} ${watsonxConfig.accessToken.token}`, + Authorization: `${ + watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxConfig.accessToken.token}`, }, body: JSON.stringify({ input: messages[messages.length - 1].content, diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index cd084207e..56ff2dff4 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -29,6 +29,7 @@ import Mistral from "./Mistral"; import Msty from "./Msty"; import Ollama from "./Ollama"; import OpenAI from "./OpenAI"; +import OpenRouter from "./OpenRouter"; import Replicate from "./Replicate"; import SageMaker from "./SageMaker"; import TextGenWebUI from "./TextGenWebUI"; @@ -64,6 +65,7 @@ const LLMs = [ Msty, Azure, WatsonX, + OpenRouter, ]; export async function llmFromDescription( diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index fd288a48e..00a05ac72 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -74,7 +74,7 @@ const osModelsEditPrompt: PromptTemplate = (history, otherData) => { !firstCharOfFirstLine; const suffixTag = isSuffix ? "" : ""; const suffixExplanation = isSuffix - ? ' When you get to "", end your response.' + ? " When you get to \"\", end your response." : ""; // If neither prefilling nor /v1/completions are supported, we have to use a chat prompt without putting words in the model's mouth diff --git a/core/package.json b/core/package.json index 39c8246ef..5e4e2652d 100644 --- a/core/package.json +++ b/core/package.json @@ -3,7 +3,7 @@ "version": "1.0.13", "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js", "scripts": { - "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", + "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand --silent", "build:npm": "tsc -p ./tsconfig.npm.json", "lint": "eslint . --ext ts", "lint:fix": "eslint . --ext ts --fix" diff --git a/core/protocol/core.ts b/core/protocol/core.ts index fb3f7c684..918ba6e66 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,6 +1,5 @@ -/* eslint-disable @typescript-eslint/naming-convention */ -import type { AutocompleteInput } from "../autocomplete/completionProvider.js"; -import { ProfileDescription } from "../config/ConfigHandler.js"; +import type { AutocompleteInput } from "../autocomplete/completionProvider"; +import { ProfileDescription } from "../config/ConfigHandler"; import type { BrowserSerializedContinueConfig, ChatMessage, @@ -16,7 +15,7 @@ import type { SerializedContinueConfig, SessionInfo, SiteIndexingConfig, -} from "../index.js"; +} from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ done?: boolean; diff --git a/core/test/context/providers/index.skip.ts b/core/test/context/providers/index.test.ts similarity index 94% rename from core/test/context/providers/index.skip.ts rename to core/test/context/providers/index.test.ts index a31d10e46..ae16ccb87 100644 --- a/core/test/context/providers/index.skip.ts +++ b/core/test/context/providers/index.test.ts @@ -8,7 +8,7 @@ import { ConfigHandler } from "../../../config/ConfigHandler"; import { contextProviderClassFromName } from "../../../context/providers"; import { ControlPlaneClient } from "../../../control-plane/client"; import FileSystemIde from "../../../util/filesystem"; -import { TEST_DIR } from "../../testUtils/testDir"; +import { TEST_DIR } from "../../util/testDir"; const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [ { name: "diff", params: {} }, @@ -46,7 +46,7 @@ async function getContextProviderExtras( }; } -describe("Should successfully run all context providers", () => { +describe.skip("Should successfully run all context providers", () => { const extrasPromise = getContextProviderExtras("Test"); CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => { diff --git a/core/test/context/retrieval/RetrievalPipeline.test.ts b/core/test/context/retrieval/RetrievalPipeline.test.ts deleted file mode 100644 index d6bfdbb3d..000000000 --- a/core/test/context/retrieval/RetrievalPipeline.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { IRetrievalPipeline } from "../../../context/retrieval/pipelines/BaseRetrievalPipeline.js"; - -function testRetrievalPipeline(pipeline: IRetrievalPipeline) { - test("should successfully run"); -} - -describe.skip("RetrievalPipeline", () => { - test.todo("should successfully run"); -}); - -// describe("Retrieval Pipelines", () => { -// const ide = new FileSystemIde(); -// const options: RetrievalPipelineOptions; - -// test("NoRerankerRetrievalPipeline", () => { -// const pipeline = new NoRerankerRetrievalPipeline(options); -// testRetrievalPipeline(pipeline); -// }); - -// test("NoRerankerRetrievalPipeline", () => { -// const pipeline = new NoRerankerRetrievalPipeline(options); -// testRetrievalPipeline(pipeline); -// }); -// }); diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts deleted file mode 100644 index 97c1815b0..000000000 --- a/core/test/fixtures.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { ConfigHandler } from "../config/ConfigHandler"; -import { ControlPlaneClient } from "../control-plane/client"; -import FileSystemIde from "../util/filesystem"; -import { TEST_DIR } from "./testUtils/testDir"; - -export const testIde = new FileSystemIde(TEST_DIR); -export const ideSettingsPromise = testIde.getIdeSettings(); -export const testConfigHandler = new ConfigHandler( - testIde, - ideSettingsPromise, - async (text) => {}, - new ControlPlaneClient(Promise.resolve(undefined)), -); diff --git a/core/test/llm.test.ts b/core/test/llm.test.ts index e3f427731..7b9b861b8 100644 --- a/core/test/llm.test.ts +++ b/core/test/llm.test.ts @@ -1,8 +1,8 @@ import * as dotenv from "dotenv"; -import { CompletionOptions } from "../index.js"; -import { BaseLLM } from "../llm/index.js"; -import OpenAI from "../llm/llms/OpenAI.js"; +import { CompletionOptions } from "../"; +import { BaseLLM } from "../llm/"; +import OpenAI from "../llm/llms/OpenAI"; // jest.setTimeout(100_000); diff --git a/core/test/llm/asyncEncoder.test.ts b/core/test/llm/asyncEncoder.test.ts deleted file mode 100644 index f181a05ca..000000000 --- a/core/test/llm/asyncEncoder.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { GPTAsyncEncoder, LlamaAsyncEncoder } from "../../llm/asyncEncoder"; - -describe("llama encoder", () => { - var tokenizer: LlamaAsyncEncoder; - - beforeAll(() => { - tokenizer = new LlamaAsyncEncoder(); - }); - - afterAll(() => { - tokenizer.close(); - }); - - test("hello world", async () => { - const input = "the quick brown fox jumped over the lazy dog"; - const output = await tokenizer.encode(input); - expect(output).toEqual([1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203]); - const decoded = await tokenizer.decode(output); - expect(decoded).toBe(input); - }); -}); - -describe("tiktoken encoder", () => { - var tokenizer: GPTAsyncEncoder; - - beforeAll(() => { - tokenizer = new GPTAsyncEncoder(); - }); - - afterAll(() => { - tokenizer.close(); - }); - - test("hello world", async () => { - const input = "the quick brown fox jumped over the lazy dog"; - const output = await tokenizer.encode(input); - expect(output).toEqual([1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679]); - const decoded = await tokenizer.decode(output); - expect(decoded).toBe(input); - }); -}); \ No newline at end of file diff --git a/core/test/util/dedentAndGetCommonWhitespace.test.ts b/core/test/util/dedentAndGetCommonWhitespace.test.ts deleted file mode 100644 index d96ccbe8f..000000000 --- a/core/test/util/dedentAndGetCommonWhitespace.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -// File generated by Continue -import { dedentAndGetCommonWhitespace } from "../../util/index.js"; - -describe("dedentAndGetCommonWhitespace", () => { - let originalString: string; - - beforeEach(() => { - // Setup any global variables or states if needed - originalString = " line1\n line2\n line3"; - }); - - afterEach(() => { - // Tear down any changes to global variables or states if needed - originalString = ""; - }); - - test("should dedent and return common whitespace for a simple case", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", " "]); - }); - - test("should handle empty string", () => { - const input = ""; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["", ""]); - }); - - test("should handle string with only whitespace", () => { - const input = " "; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["", ""]); - }); - - test("should handle string with mixed whitespace and content", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([" line1\nline2\n line3", " "]); - }); - - test("should handle string with no common leading whitespace", () => { - const input = "line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([input, ""]); - }); - - test("should handle string with empty lines", () => { - const input = " line1\n\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\n\nline3", " "]); - }); - - test("should handle string with only empty lines", () => { - const input = "\n\n"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["\n\n", ""]); - }); - - test("should handle string with tabs as whitespace", () => { - const input = "\tline1\n\tline2\n\tline3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", "\t"]); - }); - - test("should handle string with mixed tabs and spaces", () => { - const input = "\t line1\n\t line2\n\t line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", "\t "]); - }); - - test("should handle string with different leading whitespace lengths", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([" line1\nline2\n line3", " "]); - }); -}); diff --git a/core/test/util/deduplicateArray.test.ts b/core/test/util/deduplicateArray.test.ts deleted file mode 100644 index f4277916b..000000000 --- a/core/test/util/deduplicateArray.test.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { deduplicateArray } from "../../util/index.js"; - -describe("deduplicateArray", () => { - it("should return an empty array when given an empty array", () => { - const result = deduplicateArray([], (a, b) => a === b); - expect(result).toEqual([]); - }); - - it("should return the same array when there are no duplicates", () => { - const input = [1, 2, 3, 4, 5]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual(input); - }); - - it("should remove duplicates based on the equality function", () => { - const input = [1, 2, 2, 3, 4, 4, 5]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual([1, 2, 3, 4, 5]); - }); - - it("should work with objects using custom equality function", () => { - const input = [ - { id: 1, name: "Alice" }, - { id: 2, name: "Bob" }, - { id: 1, name: "Alice" }, - { id: 3, name: "Charlie" }, - ]; - const result = deduplicateArray(input, (a, b) => a.id === b.id); - expect(result).toEqual([ - { id: 1, name: "Alice" }, - { id: 2, name: "Bob" }, - { id: 3, name: "Charlie" }, - ]); - }); - - it("should preserve the order of items", () => { - const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual([3, 1, 4, 5, 9, 2, 6]); - }); - - it("should work with strings", () => { - const input = ["apple", "banana", "apple", "cherry", "banana", "date"]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual(["apple", "banana", "cherry", "date"]); - }); - - it("should handle arrays with all duplicate elements", () => { - const input = [1, 1, 1, 1, 1]; - const result = deduplicateArray(input, (a, b) => a === b); - expect(result).toEqual([1]); - }); - - it("should work with custom equality function for complex objects", () => { - const input = [ - { x: 1, y: 2 }, - { x: 2, y: 1 }, - { x: 1, y: 2 }, - { x: 3, y: 4 }, - ]; - const result = deduplicateArray( - input, - (a, b) => a.x === b.x && a.y === b.y, - ); - expect(result).toEqual([ - { x: 1, y: 2 }, - { x: 2, y: 1 }, - { x: 3, y: 4 }, - ]); - }); - - it("should handle large arrays efficiently", () => { - const input = Array(10000) - .fill(0) - .map((_, i) => i % 100); - const start = performance.now(); - const result = deduplicateArray(input, (a, b) => a === b); - const end = performance.now(); - expect(result).toHaveLength(100); - expect(end - start).toBeLessThan(1000); // Ensure it completes in less than 1 second - }); -}); diff --git a/core/test/util/fixtures.ts b/core/test/util/fixtures.ts new file mode 100644 index 000000000..89c1c0b3b --- /dev/null +++ b/core/test/util/fixtures.ts @@ -0,0 +1,19 @@ +import { ConfigHandler } from "../../config/ConfigHandler"; +import { ControlPlaneClient } from "../../control-plane/client"; +import FileSystemIde from "../../util/filesystem"; +import { TEST_DIR } from "./testDir"; + +export const testIde = new FileSystemIde(TEST_DIR); + +export const ideSettingsPromise = testIde.getIdeSettings(); + +export const testControlPlaneClient = new ControlPlaneClient( + Promise.resolve(undefined), +); + +export const testConfigHandler = new ConfigHandler( + testIde, + ideSettingsPromise, + async (text) => {}, + testControlPlaneClient, +); diff --git a/core/test/util/getLastNPathParts.test.ts b/core/test/util/getLastNPathParts.test.ts deleted file mode 100644 index 926218fe2..000000000 --- a/core/test/util/getLastNPathParts.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -// File generated by Continue -import { getLastNPathParts } from "../../util/index.js"; - -describe("getLastNPathParts", () => { - const SEP_REGEX = /[\\/]+/; - - beforeAll(() => { - // Setup code if needed - }); - - afterAll(() => { - // Teardown code if needed - }); - - test("returns the last N parts of a filepath with forward slashes", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt"); - }); - - test("returns the last N parts of a filepath with backward slashes", () => { - const filepath = "C:\\home\\user\\documents\\project\\file.txt"; - expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); - }); - - test("returns the last part if N is 1", () => { - const filepath = "/home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 1)).toBe("file.txt"); - }); - - test("returns the entire path if N is greater than the number of parts", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 10)).toBe( - "home/user/documents/project/file.txt", - ); - }); - - test("returns an empty string if N is 0", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 0)).toBe(""); - }); - - test("handles paths with mixed forward and backward slashes", () => { - const filepath = "home\\user/documents\\project/file.txt"; - expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); - }); - - test("handles edge case with empty filepath", () => { - const filepath = ""; - expect(getLastNPathParts(filepath, 2)).toBe(""); - }); -}); diff --git a/core/test/util/indexing.ts b/core/test/util/indexing.ts new file mode 100644 index 000000000..650cc5b56 --- /dev/null +++ b/core/test/util/indexing.ts @@ -0,0 +1,88 @@ +import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; +import { IContinueServerClient } from "../../continueServer/interface"; +import { testIde } from "./fixtures"; +import { addToTestDir, TEST_DIR } from "./testDir"; +import { IndexTag } from "../.."; +import { + CodebaseIndex, + PathAndCacheKey, + RefreshIndexResults, +} from "../../indexing/types"; +import { jest } from "@jest/globals"; +import { tagToString } from "../../indexing/refreshIndex"; + +export const mockFilename = "test.py"; +export const mockPathAndCacheKey = { + path: `${TEST_DIR}/${mockFilename}`, + cacheKey: "abc123", +}; + +export const mockFileContents = `\ +def main(): + print("Hello, world!") + +class Foo: + def __init__(self, bar: str): + self.bar = bar +`; + +export const mockTag: IndexTag = { + branch: "main", + directory: "/", + artifactId: "artifactId", +}; + +export const mockTagString = tagToString(mockTag); + +export const testContinueServerClient = { + connected: false, + getFromIndexCache: jest.fn(), +} as unknown as IContinueServerClient; + +const mockContinueServerClient = { + connected: false, + getFromIndexCache: jest.fn(), +} as unknown as IContinueServerClient; + +const mockResults: RefreshIndexResults = { + compute: [], + addTag: [], + removeTag: [], + del: [], +}; + +const mockMarkComplete = jest + .fn() + .mockImplementation(() => Promise.resolve()) as any; + +export async function insertMockChunks() { + const pathSep = await testIde.pathSep(); + + const index = new ChunkCodebaseIndex( + testIde.readFile.bind(testIde), + pathSep, + mockContinueServerClient, + 1000, + ); + + addToTestDir([[mockFilename, mockFileContents]]); + + await updateIndexAndAwaitGenerator(index, "compute", mockMarkComplete); + await updateIndexAndAwaitGenerator(index, "addTag", mockMarkComplete); +} + +export async function updateIndexAndAwaitGenerator( + index: CodebaseIndex, + resultType: keyof RefreshIndexResults, + markComplete: any, + tag: IndexTag = mockTag, +) { + const computeGenerator = index.update( + tag, + { ...mockResults, [resultType]: [mockPathAndCacheKey] }, + markComplete, + "test-repo", + ); + + while (!(await computeGenerator.next()).done) {} +} diff --git a/core/test/util/lcs.test.ts b/core/test/util/lcs.test.ts deleted file mode 100644 index c7116fd8b..000000000 --- a/core/test/util/lcs.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -// This file is generated by Continue -import { longestCommonSubsequence } from "../../util/lcs.js"; - -describe("longestCommonSubsequence", () => { - beforeAll(() => { - // Setup if needed - }); - - afterAll(() => { - // Teardown if needed - }); - - test("should return the longest common subsequence for non-empty strings", () => { - expect(longestCommonSubsequence("abcde", "ace")).toBe("ace"); - expect(longestCommonSubsequence("abc", "abc")).toBe("abc"); - expect(longestCommonSubsequence("abc", "def")).toBe(""); - }); - - test("should handle cases where one or both strings are empty", () => { - expect(longestCommonSubsequence("", "abc")).toBe(""); - expect(longestCommonSubsequence("abc", "")).toBe(""); - expect(longestCommonSubsequence("", "")).toBe(""); - }); - - test("should handle cases with no common subsequence", () => { - expect(longestCommonSubsequence("abc", "def")).toBe(""); - expect(longestCommonSubsequence("xyz", "abc")).toBe(""); - }); - - test("should handle cases with special characters", () => { - expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$"); - expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe(""); - }); - - test("should handle long strings efficiently", () => { - const str1 = "a".repeat(1000) + "b".repeat(1000); - const str2 = "a".repeat(1000) + "c".repeat(1000); - expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000)); - }); -}); diff --git a/core/test/util/ranges/getRangeInString.test.ts b/core/test/util/ranges/getRangeInString.test.ts deleted file mode 100644 index 95d9f25af..000000000 --- a/core/test/util/ranges/getRangeInString.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -// This file is generated by Continue - -import { getRangeInString } from "../../../util/ranges.js"; - -describe.skip("getRangeInString", () => { - let content: string; - - beforeEach(() => { - content = `Line 1 -Line 2 -Line 3 -Line 4 -Line 5`; - }); - - afterEach(() => { - content = ""; - }); - - test("should return substring within the same line", () => { - const range = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 4 }, - }; - expect(getRangeInString(content, range)).toBe("Line"); - }); - - test("should return substring spanning multiple lines", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 3, character: 3 }, - }; - const expected = `ne 2 -Line 3 -Line 4`; - expect(getRangeInString(content, range)).toBe(expected); - }); - - test("should handle range that starts and ends at the same character", () => { - const range = { - start: { line: 2, character: 0 }, - end: { line: 2, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe("L"); - }); - - test("should handle range that spans entire content", () => { - const range = { - start: { line: 0, character: 0 }, - end: { line: 4, character: 5 }, - }; - expect(getRangeInString(content, range)).toBe(content); - }); - - test("should handle range that spans to the end of the last line", () => { - const range = { - start: { line: 3, character: 2 }, - end: { line: 4, character: 5 }, - }; - const expected = `ne 4 -Line 5`; - expect(getRangeInString(content, range)).toBe(expected); - }); - - test("should handle empty content", () => { - content = ""; - const range = { - start: { line: 0, character: 0 }, - end: { line: 0, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle invalid range (start line > end line)", () => { - const range = { - start: { line: 3, character: 0 }, - end: { line: 2, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle invalid range (start character > end character on same line)", () => { - const range = { - start: { line: 1, character: 5 }, - end: { line: 1, character: 2 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle range that starts and ends at the same line but different characters", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 1, character: 6 }, - }; - expect(getRangeInString(content, range)).toBe("ne 2"); - }); - - test("should handle range that starts and ends at the same line and same characters", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 1, character: 2 }, - }; - expect(getRangeInString(content, range)).toBe("n"); - }); -}); diff --git a/core/test/util/ranges/intersection.test.ts b/core/test/util/ranges/intersection.test.ts deleted file mode 100644 index e1b0a3d52..000000000 --- a/core/test/util/ranges/intersection.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -// This file is generated by Continue - -import { intersection } from "../../../util/ranges.js"; - -interface Position { - line: number; - character: number; -} - -interface Range { - start: Position; - end: Position; -} - -describe("intersection", () => { - let rangeA: Range; - let rangeB: Range; - - beforeEach(() => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 3, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 2 }, - end: { line: 4, character: 0 }, - }; - }); - - test("returns correct intersection for overlapping ranges", () => { - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 2 }, - end: { line: 3, character: 5 }, - }); - }); - - test("returns null for non-overlapping ranges", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 2, character: 0 }, - }; - - rangeB = { - start: { line: 3, character: 0 }, - end: { line: 4, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toBeNull(); - }); - - // TODO - test.skip("returns correct intersection for single line overlap", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 5 }, - }; - - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 2, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 3 }, - end: { line: 1, character: 5 }, - }); - }); - - test("returns null for single line non-overlapping ranges", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 2 }, - }; - - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 1, character: 5 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toBeNull(); - }); - - test("returns correct intersection when one range is fully within another", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 4, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 2 }, - end: { line: 3, character: 3 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 2 }, - end: { line: 3, character: 3 }, - }); - }); - - test("returns correct intersection when ranges touch at the edge", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 2, character: 0 }, - }; - - rangeB = { - start: { line: 2, character: 0 }, - end: { line: 3, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 0 }, - end: { line: 2, character: 0 }, - }); - }); -}); diff --git a/core/test/util/ranges/maxMinPosition.test.ts b/core/test/util/ranges/maxMinPosition.test.ts deleted file mode 100644 index 684dced31..000000000 --- a/core/test/util/ranges/maxMinPosition.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { maxPosition, minPosition } from "../../../util/ranges.js"; - -// This file is generated by Continue -interface Position { - line: number; - character: number; -} - -describe("Position comparison functions", () => { - let pos1: Position; - let pos2: Position; - let pos3: Position; - let pos4: Position; - - beforeAll(() => { - // Setup: Initializing positions - pos1 = { line: 1, character: 5 }; - pos2 = { line: 2, character: 3 }; - pos3 = { line: 1, character: 7 }; - pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality - }); - - describe("maxPosition", () => { - it("should return the position with the greater line number", () => { - expect(maxPosition(pos1, pos2)).toEqual(pos2); - }); - - it("should return the position with the greater character number when lines are equal", () => { - expect(maxPosition(pos1, pos3)).toEqual(pos3); - }); - - it("should return the first position when both positions are equal", () => { - expect(maxPosition(pos2, pos4)).toEqual(pos2); - }); - - it("should handle positions with negative line numbers", () => { - const posNegative = { line: -1, character: 0 }; - expect(maxPosition(posNegative, pos1)).toEqual(pos1); - }); - - it("should handle positions with negative character numbers", () => { - const posNegativeChar = { line: 1, character: -1 }; - expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1); - }); - }); - - describe("minPosition", () => { - it("should return the position with the lesser line number", () => { - expect(minPosition(pos1, pos2)).toEqual(pos1); - }); - - it("should return the position with the lesser character number when lines are equal", () => { - expect(minPosition(pos1, pos3)).toEqual(pos1); - }); - - it("should return the first position when both positions are equal", () => { - expect(minPosition(pos2, pos4)).toEqual(pos2); - }); - - it("should handle positions with negative line numbers", () => { - const posNegative = { line: -1, character: 0 }; - expect(minPosition(posNegative, pos1)).toEqual(posNegative); - }); - - it("should handle positions with negative character numbers", () => { - const posNegativeChar = { line: 1, character: -1 }; - expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar); - }); - }); -}); diff --git a/core/test/util/ranges/union.test.ts b/core/test/util/ranges/union.test.ts deleted file mode 100644 index 0ee62cb4f..000000000 --- a/core/test/util/ranges/union.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { union } from "../../../util/ranges.js"; - -// This file is generated by Continue -interface Position { - line: number; - character: number; -} - -interface Range { - start: Position; - end: Position; -} - -describe("union", () => { - let rangeA: Range; - let rangeB: Range; - - beforeEach(() => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 3, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 3 }, - end: { line: 4, character: 2 }, - }; - }); - - test("should return the union of two overlapping ranges", () => { - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 4, character: 2 }, - }); - }); - - test("should return the union when ranges are identical", () => { - const result = union(rangeA, rangeA); - expect(result).toEqual(rangeA); - }); - - test("should return the union when ranges do not overlap but are adjacent", () => { - rangeB = { - start: { line: 3, character: 5 }, - end: { line: 4, character: 2 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 4, character: 2 }, - }); - }); - - test("should return the union when one range is completely within the other", () => { - rangeB = { - start: { line: 2, character: 1 }, - end: { line: 2, character: 4 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual(rangeA); - }); - - test("should return the union when ranges do not overlap and are not adjacent", () => { - rangeB = { - start: { line: 4, character: 3 }, - end: { line: 5, character: 1 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 5, character: 1 }, - }); - }); - - // TODO - test.skip("should handle edge case where start and end lines are the same", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 5 }, - }; - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 1, character: 7 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 1, character: 7 }, - }); - }); -}); diff --git a/core/test/testUtils/testDir.ts b/core/test/util/testDir.ts similarity index 91% rename from core/test/testUtils/testDir.ts rename to core/test/util/testDir.ts index 557906cef..d6bc462dc 100644 --- a/core/test/testUtils/testDir.ts +++ b/core/test/util/testDir.ts @@ -1,8 +1,9 @@ import fs from "fs"; import path from "path"; +import os from "os"; // Want this outside of the git repository so we can change branches in tests -export const TEST_DIR = path.join(__dirname, "..", "..", "testDir"); +export const TEST_DIR = path.join(os.tmpdir(), "testDir"); export function setUpTestDir() { if (fs.existsSync(TEST_DIR)) { diff --git a/core/util/devdataSqlite.ts b/core/util/devdataSqlite.ts index 9724e9f21..4f86cb1a1 100644 --- a/core/util/devdataSqlite.ts +++ b/core/util/devdataSqlite.ts @@ -21,14 +21,14 @@ export class DevDataSqliteDb { // Add tokens_prompt column if it doesn't exist const columnCheckResult = await db.all( - `PRAGMA table_info(tokens_generated);`, + "PRAGMA table_info(tokens_generated);", ); const columnExists = columnCheckResult.some( (col: any) => col.name === "tokens_prompt", ); if (!columnExists) { await db.exec( - `ALTER TABLE tokens_generated ADD COLUMN tokens_prompt INTEGER NOT NULL DEFAULT 0;`, + "ALTER TABLE tokens_generated ADD COLUMN tokens_prompt INTEGER NOT NULL DEFAULT 0;", ); } } @@ -41,7 +41,7 @@ export class DevDataSqliteDb { ) { const db = await DevDataSqliteDb.get(); await db?.run( - `INSERT INTO tokens_generated (model, provider, tokens_prompt, tokens_generated) VALUES (?, ?, ?, ?)`, + "INSERT INTO tokens_generated (model, provider, tokens_prompt, tokens_generated) VALUES (?, ?, ?, ?)", [model, provider, promptTokens, generatedTokens], ); } diff --git a/core/util/extractMinimalStackTraceInfo.ts b/core/util/extractMinimalStackTraceInfo.ts index a2fa226de..51fcde91a 100644 --- a/core/util/extractMinimalStackTraceInfo.ts +++ b/core/util/extractMinimalStackTraceInfo.ts @@ -5,7 +5,7 @@ * @returns A string containing the minimal stack trace information. */ export function extractMinimalStackTraceInfo(stack: unknown): string { - if (typeof stack !== "string") return ""; + if (typeof stack !== "string") {return "";} const lines = stack.split("\n"); const minimalLines = lines.filter((line) => { return line.trimStart().startsWith("at ") && !line.includes("node_modules"); diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 330776518..06209a474 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -84,12 +84,12 @@ class FileSystemIde implements IDE { } async getTags(artifactId: string): Promise { - const directory =(await this.getWorkspaceDirs())[0] + const directory =(await this.getWorkspaceDirs())[0]; return [{ artifactId, branch: await this.getBranch(directory), directory - }] + }]; } getIdeInfo(): Promise { diff --git a/core/util/index.test.ts b/core/util/index.test.ts new file mode 100644 index 000000000..0d618069c --- /dev/null +++ b/core/util/index.test.ts @@ -0,0 +1,200 @@ +// File generated by Continue +import { + dedentAndGetCommonWhitespace, + deduplicateArray, + getLastNPathParts, +} from "./"; + +describe("getLastNPathParts", () => { + test("returns the last N parts of a filepath with forward slashes", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt"); + }); + + test("returns the last N parts of a filepath with backward slashes", () => { + const filepath = "C:\\home\\user\\documents\\project\\file.txt"; + expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); + }); + + test("returns the last part if N is 1", () => { + const filepath = "/home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 1)).toBe("file.txt"); + }); + + test("returns the entire path if N is greater than the number of parts", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 10)).toBe( + "home/user/documents/project/file.txt", + ); + }); + + test("returns an empty string if N is 0", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 0)).toBe(""); + }); + + test("handles paths with mixed forward and backward slashes", () => { + const filepath = "home\\user/documents\\project/file.txt"; + expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); + }); + + test("handles edge case with empty filepath", () => { + const filepath = ""; + expect(getLastNPathParts(filepath, 2)).toBe(""); + }); +}); + +describe("deduplicateArray", () => { + it("should return an empty array when given an empty array", () => { + const result = deduplicateArray([], (a, b) => a === b); + expect(result).toEqual([]); + }); + + it("should return the same array when there are no duplicates", () => { + const input = [1, 2, 3, 4, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual(input); + }); + + it("should remove duplicates based on the equality function", () => { + const input = [1, 2, 2, 3, 4, 4, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([1, 2, 3, 4, 5]); + }); + + it("should work with objects using custom equality function", () => { + const input = [ + { id: 1, name: "Alice" }, + { id: 2, name: "Bob" }, + { id: 1, name: "Alice" }, + { id: 3, name: "Charlie" }, + ]; + const result = deduplicateArray(input, (a, b) => a.id === b.id); + expect(result).toEqual([ + { id: 1, name: "Alice" }, + { id: 2, name: "Bob" }, + { id: 3, name: "Charlie" }, + ]); + }); + + it("should preserve the order of items", () => { + const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([3, 1, 4, 5, 9, 2, 6]); + }); + + it("should work with strings", () => { + const input = ["apple", "banana", "apple", "cherry", "banana", "date"]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual(["apple", "banana", "cherry", "date"]); + }); + + it("should handle arrays with all duplicate elements", () => { + const input = [1, 1, 1, 1, 1]; + const result = deduplicateArray(input, (a, b) => a === b); + expect(result).toEqual([1]); + }); + + it("should work with custom equality function for complex objects", () => { + const input = [ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 1, y: 2 }, + { x: 3, y: 4 }, + ]; + const result = deduplicateArray( + input, + (a, b) => a.x === b.x && a.y === b.y, + ); + expect(result).toEqual([ + { x: 1, y: 2 }, + { x: 2, y: 1 }, + { x: 3, y: 4 }, + ]); + }); + + it("should handle large arrays efficiently", () => { + const input = Array(10000) + .fill(0) + .map((_, i) => i % 100); + const start = performance.now(); + const result = deduplicateArray(input, (a, b) => a === b); + const end = performance.now(); + expect(result).toHaveLength(100); + expect(end - start).toBeLessThan(1000); // Ensure it completes in less than 1 second + }); +}); + +describe("dedentAndGetCommonWhitespace", () => { + let originalString: string; + + beforeEach(() => { + // Setup any global variables or states if needed + originalString = " line1\n line2\n line3"; + }); + + afterEach(() => { + // Tear down any changes to global variables or states if needed + originalString = ""; + }); + + test("should dedent and return common whitespace for a simple case", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", " "]); + }); + + test("should handle empty string", () => { + const input = ""; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["", ""]); + }); + + test("should handle string with only whitespace", () => { + const input = " "; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["", ""]); + }); + + test("should handle string with mixed whitespace and content", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([" line1\nline2\n line3", " "]); + }); + + test("should handle string with no common leading whitespace", () => { + const input = "line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([input, ""]); + }); + + test("should handle string with empty lines", () => { + const input = " line1\n\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\n\nline3", " "]); + }); + + test("should handle string with only empty lines", () => { + const input = "\n\n"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["\n\n", ""]); + }); + + test("should handle string with tabs as whitespace", () => { + const input = "\tline1\n\tline2\n\tline3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", "\t"]); + }); + + test("should handle string with mixed tabs and spaces", () => { + const input = "\t line1\n\t line2\n\t line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", "\t "]); + }); + + test("should handle string with different leading whitespace lengths", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([" line1\nline2\n line3", " "]); + }); +}); diff --git a/core/util/index.ts b/core/util/index.ts index 0c7a06317..a628948c7 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -2,19 +2,19 @@ export function removeQuotesAndEscapes(output: string): string { output = output.trim(); // Replace smart quotes - output = output.replace("“", '"'); - output = output.replace("”", '"'); + output = output.replace("“", "\""); + output = output.replace("”", "\""); output = output.replace("‘", "'"); output = output.replace("’", "'"); // Remove escapes - output = output.replace('\\"', '"'); + output = output.replace("\\\"", "\""); output = output.replace("\\'", "'"); output = output.replace("\\n", "\n"); output = output.replace("\\t", "\t"); output = output.replace("\\\\", "\\"); while ( - (output.startsWith('"') && output.endsWith('"')) || + (output.startsWith("\"") && output.endsWith("\"")) || (output.startsWith("'") && output.endsWith("'")) ) { output = output.slice(1, -1); @@ -120,7 +120,7 @@ export function getUniqueFilePath( } export function shortestRelativePaths(paths: string[]): string[] { - if (paths.length === 0) return []; + if (paths.length === 0) {return [];} const partsLengths = paths.map((x) => x.split(SEP_REGEX).length); const currentRelativePaths = paths.map(getBasename); @@ -135,7 +135,7 @@ export function shortestRelativePaths(paths: string[]): string[] { const firstDuplicatedPath = currentRelativePaths.find( (x, i) => isDuplicated[i], ); - if (!firstDuplicatedPath) break; + if (!firstDuplicatedPath) {break;} currentRelativePaths.forEach((x, i) => { if (x === firstDuplicatedPath) { diff --git a/core/util/lcs.test.ts b/core/util/lcs.test.ts new file mode 100644 index 000000000..2f8e1f92f --- /dev/null +++ b/core/util/lcs.test.ts @@ -0,0 +1,31 @@ +import { longestCommonSubsequence as lcs } from "./lcs"; + +describe("longestCommonSubsequence", () => { + test("should return the longest common subsequence for non-empty strings", () => { + expect(lcs("abcde", "ace")).toBe("ace"); + expect(lcs("abc", "abc")).toBe("abc"); + expect(lcs("abc", "def")).toBe(""); + }); + + test("should handle cases where one or both strings are empty", () => { + expect(lcs("", "abc")).toBe(""); + expect(lcs("abc", "")).toBe(""); + expect(lcs("", "")).toBe(""); + }); + + test("should handle cases with no common subsequence", () => { + expect(lcs("abc", "def")).toBe(""); + expect(lcs("xyz", "abc")).toBe(""); + }); + + test("should handle cases with special characters", () => { + expect(lcs("a!@#b$c", "!@#$")).toBe("!@#$"); + expect(lcs("a!@#b$c", "xyz")).toBe(""); + }); + + test("should handle long strings efficiently", () => { + const str1 = "a".repeat(1000) + "b".repeat(1000); + const str2 = "a".repeat(1000) + "c".repeat(1000); + expect(lcs(str1, str2)).toBe("a".repeat(1000)); + }); +}); diff --git a/core/test/util/merge.test.ts b/core/util/merge.test.ts similarity index 96% rename from core/test/util/merge.test.ts rename to core/util/merge.test.ts index 3bd8309a8..237f362c4 100644 --- a/core/test/util/merge.test.ts +++ b/core/util/merge.test.ts @@ -1,5 +1,6 @@ // File generated by Continue -import { mergeJson } from "../../util/merge.js"; + +import mergeJson from "./merge"; describe("mergeJson", () => { it("should merge two simple JSON objects", () => { @@ -9,7 +10,7 @@ describe("mergeJson", () => { expect(result).toEqual({ a: 1, b: 3, c: 4 }); }); - it('should overwrite values when mergeBehavior is "overwrite"', () => { + it("should overwrite values when mergeBehavior is \"overwrite\"", () => { const first = { a: 1, b: 2 }; const second = { b: 3, c: 4 }; const result = mergeJson(first, second, "overwrite"); diff --git a/core/util/messenger.ts b/core/util/messenger.ts index 416e4e8da..2b0593ef3 100644 --- a/core/util/messenger.ts +++ b/core/util/messenger.ts @@ -75,7 +75,7 @@ export class InProcessMessenger< messageId?: string, ): ToProtocol[T][1] { const listener = this.myTypeListeners.get(messageType); - if (!listener) return; + if (!listener) {return;} const msg: Message = { messageType: messageType as string, diff --git a/core/util/paths.ts b/core/util/paths.ts index 7c208f92c..7a6ed8831 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -200,6 +200,10 @@ export async function migrate( callback: () => void | Promise, onAlreadyComplete?: () => void, ) { + if (process.env.NODE_ENV === "test") { + return await Promise.resolve(callback()); + } + const migrationsPath = getMigrationsFolderPath(); const migrationPath = path.join(migrationsPath, id); diff --git a/core/util/ranges.test.ts b/core/util/ranges.test.ts new file mode 100644 index 000000000..d9d12c07a --- /dev/null +++ b/core/util/ranges.test.ts @@ -0,0 +1,374 @@ +// This file is generated by Continue + +import { + intersection, + getRangeInString, + maxPosition, + minPosition, + union, +} from "./ranges"; + +interface Position { + line: number; + character: number; +} + +interface Range { + start: Position; + end: Position; +} + +describe("union", () => { + let rangeA: Range; + let rangeB: Range; + + beforeEach(() => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 3, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 3 }, + end: { line: 4, character: 2 }, + }; + }); + + test("should return the union of two overlapping ranges", () => { + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 4, character: 2 }, + }); + }); + + test("should return the union when ranges are identical", () => { + const result = union(rangeA, rangeA); + expect(result).toEqual(rangeA); + }); + + test("should return the union when ranges do not overlap but are adjacent", () => { + rangeB = { + start: { line: 3, character: 5 }, + end: { line: 4, character: 2 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 4, character: 2 }, + }); + }); + + test("should return the union when one range is completely within the other", () => { + rangeB = { + start: { line: 2, character: 1 }, + end: { line: 2, character: 4 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual(rangeA); + }); + + test("should return the union when ranges do not overlap and are not adjacent", () => { + rangeB = { + start: { line: 4, character: 3 }, + end: { line: 5, character: 1 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 5, character: 1 }, + }); + }); + + // TODO + test.skip("should handle edge case where start and end lines are the same", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 5 }, + }; + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 1, character: 7 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 1, character: 7 }, + }); + }); +}); + +describe("Position comparison functions", () => { + let pos1: Position; + let pos2: Position; + let pos3: Position; + let pos4: Position; + + beforeAll(() => { + // Setup: Initializing positions + pos1 = { line: 1, character: 5 }; + pos2 = { line: 2, character: 3 }; + pos3 = { line: 1, character: 7 }; + pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality + }); + + describe("maxPosition", () => { + it("should return the position with the greater line number", () => { + expect(maxPosition(pos1, pos2)).toEqual(pos2); + }); + + it("should return the position with the greater character number when lines are equal", () => { + expect(maxPosition(pos1, pos3)).toEqual(pos3); + }); + + it("should return the first position when both positions are equal", () => { + expect(maxPosition(pos2, pos4)).toEqual(pos2); + }); + + it("should handle positions with negative line numbers", () => { + const posNegative = { line: -1, character: 0 }; + expect(maxPosition(posNegative, pos1)).toEqual(pos1); + }); + + it("should handle positions with negative character numbers", () => { + const posNegativeChar = { line: 1, character: -1 }; + expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1); + }); + }); + + describe("minPosition", () => { + it("should return the position with the lesser line number", () => { + expect(minPosition(pos1, pos2)).toEqual(pos1); + }); + + it("should return the position with the lesser character number when lines are equal", () => { + expect(minPosition(pos1, pos3)).toEqual(pos1); + }); + + it("should return the first position when both positions are equal", () => { + expect(minPosition(pos2, pos4)).toEqual(pos2); + }); + + it("should handle positions with negative line numbers", () => { + const posNegative = { line: -1, character: 0 }; + expect(minPosition(posNegative, pos1)).toEqual(posNegative); + }); + + it("should handle positions with negative character numbers", () => { + const posNegativeChar = { line: 1, character: -1 }; + expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar); + }); + }); +}); + +describe.skip("getRangeInString", () => { + let content: string; + + beforeEach(() => { + content = `Line 1 +Line 2 +Line 3 +Line 4 +Line 5`; + }); + + afterEach(() => { + content = ""; + }); + + test("should return substring within the same line", () => { + const range = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 4 }, + }; + expect(getRangeInString(content, range)).toBe("Line"); + }); + + test("should return substring spanning multiple lines", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 3, character: 3 }, + }; + const expected = `ne 2 +Line 3 +Line 4`; + expect(getRangeInString(content, range)).toBe(expected); + }); + + test("should handle range that starts and ends at the same character", () => { + const range = { + start: { line: 2, character: 0 }, + end: { line: 2, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe("L"); + }); + + test("should handle range that spans entire content", () => { + const range = { + start: { line: 0, character: 0 }, + end: { line: 4, character: 5 }, + }; + expect(getRangeInString(content, range)).toBe(content); + }); + + test("should handle range that spans to the end of the last line", () => { + const range = { + start: { line: 3, character: 2 }, + end: { line: 4, character: 5 }, + }; + const expected = `ne 4 +Line 5`; + expect(getRangeInString(content, range)).toBe(expected); + }); + + test("should handle empty content", () => { + content = ""; + const range = { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle invalid range (start line > end line)", () => { + const range = { + start: { line: 3, character: 0 }, + end: { line: 2, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle invalid range (start character > end character on same line)", () => { + const range = { + start: { line: 1, character: 5 }, + end: { line: 1, character: 2 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle range that starts and ends at the same line but different characters", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 1, character: 6 }, + }; + expect(getRangeInString(content, range)).toBe("ne 2"); + }); + + test("should handle range that starts and ends at the same line and same characters", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 1, character: 2 }, + }; + expect(getRangeInString(content, range)).toBe("n"); + }); +}); + +describe("intersection", () => { + let rangeA: Range; + let rangeB: Range; + + beforeEach(() => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 3, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 2 }, + end: { line: 4, character: 0 }, + }; + }); + + test("returns correct intersection for overlapping ranges", () => { + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 2 }, + end: { line: 3, character: 5 }, + }); + }); + + test("returns null for non-overlapping ranges", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 2, character: 0 }, + }; + + rangeB = { + start: { line: 3, character: 0 }, + end: { line: 4, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toBeNull(); + }); + + // TODO + test.skip("returns correct intersection for single line overlap", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 5 }, + }; + + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 2, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 3 }, + end: { line: 1, character: 5 }, + }); + }); + + test("returns null for single line non-overlapping ranges", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 2 }, + }; + + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 1, character: 5 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toBeNull(); + }); + + test("returns correct intersection when one range is fully within another", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 4, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 2 }, + end: { line: 3, character: 3 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 2 }, + end: { line: 3, character: 3 }, + }); + }); + + test("returns correct intersection when ranges touch at the edge", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 2, character: 0 }, + }; + + rangeB = { + start: { line: 2, character: 0 }, + end: { line: 3, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 0 }, + end: { line: 2, character: 0 }, + }); + }); +}); diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 44a908810..f6611bea0 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -189,7 +189,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "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)", @@ -197,6 +198,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", @@ -214,7 +216,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, @@ -239,6 +242,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 44a908810..f6611bea0 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -189,7 +189,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "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)", @@ -197,6 +198,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", @@ -214,7 +216,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, @@ -239,6 +242,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 44a908810..f6611bea0 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -189,7 +189,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "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)", @@ -197,6 +198,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", @@ -214,7 +216,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, @@ -239,6 +242,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index d6c797596..5bcfaa05c 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -192,7 +192,8 @@ "deepseek", "azure", "msty", - "watsonx" + "watsonx", + "openrouter" ], "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)", @@ -200,6 +201,7 @@ "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)", + "### Sagemaker\nSagemaker is AWS' machine learning platform.", "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", @@ -217,7 +219,8 @@ "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." + "### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", + "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)." ], "type": "string" }, @@ -242,6 +245,11 @@ "default": 2048, "type": "integer" }, + "maxStopWords": { + "title": "Max Stop Words", + "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", + "type": "integer" + }, "template": { "title": "Template", "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", diff --git a/extensions/vscode/scripts/prepackage-cross-platform.js b/extensions/vscode/scripts/prepackage-cross-platform.js index 59089dd62..018ea70c2 100644 --- a/extensions/vscode/scripts/prepackage-cross-platform.js +++ b/extensions/vscode/scripts/prepackage-cross-platform.js @@ -24,6 +24,7 @@ const { copySqliteBinary, installNodeModuleInTempDirAndCopyToCurrent, downloadSqliteBinary, + copyTokenizers, } = require("./utils"); // Clear folders that will be packaged to ensure clean slate @@ -104,6 +105,9 @@ async function package(target, os, arch, exe) { // *** onnxruntime-node *** await copyOnnxRuntimeFromNodeModules(target); + // copy llama tokenizers to out + copyTokenizers(); + // *** Install @lancedb binary *** const lancePackageToInstall = { "darwin-arm64": "@lancedb/vectordb-darwin-arm64", diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index b0d7def7d..6a129bc61 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -39,6 +39,20 @@ function copyConfigSchema() { fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2)); } +function copyTokenizers() { + fs.copyFileSync( + path.join(__dirname, "../../../core/llm/llamaTokenizerWorkerPool.mjs"), + path.join(__dirname, "../out/llamaTokenizerWorkerPool.mjs"), + ); + console.log("[info] Copied llamaTokenizerWorkerPool"); + + fs.copyFileSync( + path.join(__dirname, "../../../core/llm/llamaTokenizer.mjs"), + path.join(__dirname, "../out/llamaTokenizer.mjs"), + ); + console.log("[info] Copied llamaTokenizer"); +} + function installNodeModules() { // Make sure we are in the right directory if (!process.cwd().endsWith("vscode")) { @@ -242,6 +256,7 @@ async function copyNodeModules() { "@esbuild", "@lancedb", "@vscode/ripgrep", + "workerpool" ]; fs.mkdirSync("out/node_modules", { recursive: true }); @@ -497,4 +512,5 @@ module.exports = { installNodeModuleInTempDirAndCopyToCurrent, downloadSqliteBinary, downloadRipgrepBinary, + copyTokenizers }; diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index 639fc167c..d2f8575e0 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -6,16 +6,12 @@ "outDir": "out/tsc/src", "sourceMap": true, "rootDir": "../../", - "strict": true /* enable all strict type-checking options */, - /* Additional Checks */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, - "resolveJsonModule": true /* Enable importing .json files */, + "strict": true, + "esModuleInterop": true, + "resolveJsonModule": true, "types": ["mocha"] // This solves conflict between jest and mocha: https://github.com/cypress-io/cypress/issues/7435#issuecomment-631695007 }, "include": ["src/**/*", "../../core/**/*.ts", "../../core/**/*.d.ts"], // core/test uses @types/jest, which conflicts with @types/mocha - "exclude": ["../../core/dist/**/*", "../../core/test/**/*"] + "exclude": ["../../core/dist/**/*", "../../core/**/*.test.ts"] }