Merge pull request #2423 from continuedev/nate/hctx

hctx
This commit is contained in:
Nate Sesti 2024-09-29 12:32:56 -07:00 • committed by GitHub
commit 60fe319864
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
53 changed files with 1049 additions and 67 deletions

2
.gitignore vendored
View file

@ -169,4 +169,4 @@ Icon?
.prompts/
.aider*
notes.md
notes.md

View file

@ -1,4 +1,4 @@
extensions/vscode/continue_rc_schema.json
**/.continueignore
CHANGELOG.md
**/continue_tutorial.py
**/continue_tutorial.py

19
.prompts/test.prompt Normal file
View file

@ -0,0 +1,19 @@
temperature: 0.5
maxTokens: 4096
name: jest
description: Write Jest unit tests
---
<system>
You are an expert programmer
</system>
{{{ input }}}
Write unit tests for the above selected code, following each of these instructions:
- Use `jest`
- Properly set up and tear down
- Include important edge cases
- The tests should be complete and sophisticated
- Give the tests just as chat output, don't edit any file
- Don't explain how to set up `jest`
- Write a single code block, making sure to label with the language being used (e.g. "```typscript")

View file

@ -2,6 +2,8 @@ import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../commands/util.js";
import { getParserForFile } from "../util/treeSitter.js";
export type AstPath = Parser.SyntaxNode[];
export async function getAst(
filepath: string,
fileContents: string,
@ -23,7 +25,7 @@ export async function getAst(
export async function getTreePathAtCursor(
ast: Parser.Tree,
cursorIndex: number,
): Promise<Parser.SyntaxNode[] | undefined> {
): Promise<AstPath> {
const path = [ast.rootNode];
while (path[path.length - 1].childCount > 0) {
let foundChild = false;

View file

@ -1,4 +1,4 @@
import { stopAtStopTokens } from "./charStream";
import { stopAtStopTokens } from "./streamTransforms/charStream";
describe("stopAtStopTokens", () => {
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {

View file

@ -22,20 +22,18 @@ import {
} from "../util/parameters.js";
import { Telemetry } from "../util/posthog.js";
import { getRangeInString } from "../util/ranges.js";
import { ImportDefinitionsService } from "./ImportDefinitionsService.js";
import { BracketMatchingService } from "./brackets.js";
import AutocompleteLruCache from "./cache.js";
import {
noFirstCharNewline,
onlyWhitespaceAfterEndOfLine,
stopAtStopTokens,
} from "./charStream.js";
import {
constructAutocompletePrompt,
languageForFilepath,
} from "./constructPrompt.js";
import { isOnlyPunctuationAndWhitespace } from "./filter.js";
import { AutocompleteLanguageInfo } from "./languages.js";
import { postprocessCompletion } from "./postprocessing.js";
import { AutocompleteSnippet } from "./ranking.js";
import { RecentlyEditedRange } from "./recentlyEdited.js";
import { RootPathContextService } from "./services/RootPathContextService.js";
import {
avoidPathLineAndEmptyComments,
noTopLevelKeywordsMidline,
@ -44,15 +42,19 @@ import {
stopAtRepeatingLines,
stopAtSimilarLine,
streamWithNewLines,
} from "./lineStream.js";
import { postprocessCompletion } from "./postprocessing.js";
import { AutocompleteSnippet } from "./ranking.js";
import { RecentlyEditedRange } from "./recentlyEdited.js";
} from "./streamTransforms/lineStream.js";
import { getTemplateForModel } from "./templates.js";
import { GeneratorReuseManager } from "./util.js";
// @prettier-ignore
import Handlebars from "handlebars";
import { getConfigJsonPath } from "../util/paths.js";
import { BracketMatchingService } from "./services/BracketMatchingService.js";
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
import {
noFirstCharNewline,
onlyWhitespaceAfterEndOfLine,
stopAtStopTokens,
} from "./streamTransforms/charStream.js";
export interface AutocompleteInput {
completionId: string;
@ -158,9 +160,14 @@ export class CompletionProvider {
this.onError.bind(this),
);
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
this.rootPathContextService = new RootPathContextService(
this.importDefinitionsService,
this.ide,
);
}
private importDefinitionsService: ImportDefinitionsService;
private rootPathContextService: RootPathContextService;
private generatorReuseManager: GeneratorReuseManager;
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
@ -542,6 +549,7 @@ export class CompletionProvider {
llm.model,
extrasSnippets,
this.importDefinitionsService,
this.rootPathContextService,
);
// If prefix is manually passed

View file

@ -1,4 +1,3 @@
import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../commands/util.js";
import { TabAutocompleteOptions } from "../index.js";
@ -7,8 +6,7 @@ import {
pruneLinesFromBottom,
pruneLinesFromTop,
} from "../llm/countTokens.js";
import { ImportDefinitionsService } from "./ImportDefinitionsService.js";
import { getAst, getTreePathAtCursor } from "./ast.js";
import { AstPath, getAst, getTreePathAtCursor } from "./ast.js";
import {
AutocompleteLanguageInfo,
LANGUAGES,
@ -22,6 +20,8 @@ import {
type AutocompleteSnippet,
} from "./ranking.js";
import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js";
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
import { RootPathContextService } from "./services/RootPathContextService.js";
export function languageForFilepath(
filepath: string,
@ -32,7 +32,7 @@ export function languageForFilepath(
const BLOCK_TYPES = ["body", "statement_block"];
function shouldCompleteMultilineAst(
treePath: Parser.SyntaxNode[],
treePath: AstPath,
cursorLine: number,
): boolean {
// If at the base of the file, do multiline
@ -63,7 +63,7 @@ function isMidlineCompletion(prefix: string, suffix: string): boolean {
}
async function shouldCompleteMultiline(
filepath: string,
treePath: AstPath | undefined,
fullPrefix: string,
fullSuffix: string,
language: AutocompleteLanguageInfo,
@ -94,18 +94,6 @@ async function shouldCompleteMultiline(
}
// Use AST to determine whether to complete multiline
let treePath: Parser.SyntaxNode[] | undefined;
try {
const ast = await getAst(filepath, fullPrefix + fullSuffix);
if (!ast) {
return true;
}
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
} catch (e) {
console.error("Failed to parse AST", e);
}
let completeMultiline = false;
if (treePath) {
const cursorLine = fullPrefix.split("\n").length - 1;
@ -127,6 +115,7 @@ export async function constructAutocompletePrompt(
modelName: string,
extraSnippets: AutocompleteSnippet[],
importDefinitionsService: ImportDefinitionsService,
rootPathContextService: RootPathContextService,
): Promise<{
prefix: string;
suffix: string;
@ -145,6 +134,17 @@ export async function constructAutocompletePrompt(
);
const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
// Calculate AST Path
let treePath: AstPath | undefined;
try {
const ast = await getAst(filepath, fullPrefix + fullSuffix);
if (ast) {
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
}
} catch (e) {
console.error("Failed to parse AST", e);
}
// Find external snippets
let snippets: AutocompleteSnippet[] = [];
@ -215,6 +215,14 @@ export async function constructAutocompletePrompt(
snippets.push(...importSnippets);
}
if (options.useHierarchicalContext && treePath) {
const ctx = await rootPathContextService.getContextForPath(
filepath,
treePath,
);
snippets.push(...ctx);
}
// Filter out empty snippets and ones that are already in the prefix/suffix
snippets = snippets
.map((snippet) => ({ ...snippet }))
@ -269,7 +277,7 @@ export async function constructAutocompletePrompt(
suffix,
useFim: true,
completeMultiline: await shouldCompleteMultiline(
filepath,
treePath,
fullPrefix,
fullSuffix,
language,

View file

@ -1,4 +1,4 @@
import type { LineFilter } from "./lineStream.js";
import { LineFilter } from "./streamTransforms/lineStream";
export interface AutocompleteLanguageInfo {
name: string;
@ -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: [],
};

View file

@ -1,5 +1,5 @@
import { jest } from "@jest/globals";
import * as lineStream from "./lineStream";
import * as lineStream from "./streamTransforms/lineStream";
describe("lineStream", () => {
let mockFullStop: jest.Mock;

View file

@ -1,6 +1,6 @@
import type { ILLM } from "../index.js";
import { longestCommonSubsequence } from "../util/lcs.js";
import { lineIsRepeated } from "./lineStream.js";
import { lineIsRepeated } from "./streamTransforms/lineStream.js";
function rewritesLineAbove(completion: string, prefix: string): boolean {
const lineAbove = prefix

View file

@ -1,11 +1,11 @@
import { IDE } from "../index.js";
import { RangeInFileWithContents } from "../commands/util.js";
import { PrecalculatedLruCache } from "../util/LruCache.js";
import { IDE } from "../..";
import { RangeInFileWithContents } from "../../commands/util";
import { PrecalculatedLruCache } from "../../util/LruCache";
import {
TSQueryType,
getParserForFile,
getQueryForFile,
} from "../util/treeSitter.js";
} from "../../util/treeSitter";
interface FileInfo {
imports: { [key: string]: RangeInFileWithContents[] };

View file

@ -0,0 +1,45 @@
import { IDE, Location } from "../..";
import { LANGUAGES } from "../languages";
import { getSymbolsForSnippet } from "../ranking";
interface FileInfo {
filepath: string;
}
export class NearbyDefinitionsService {
static N = 10;
constructor(private readonly ide: IDE) {}
async getDefinitionsForLine(filepath: string, line: number) {
const lineContent = await this.ide.readRangeInFile(filepath, {
start: {
line,
character: 0,
},
end: {
line: line + 1,
character: 0,
},
});
// Remove keywords
const lang = LANGUAGES[filepath.split(".").slice(-1)[0]];
const symbols = Array.from(getSymbolsForSnippet(lineContent))
.filter((s) => s.length > 0)
.filter((s) => !(lang && lang?.stopWords?.includes(s)));
return Promise.all(
symbols.map((s) => {
const character = lineContent.indexOf(s);
const pos: Location = {
filepath,
position: {
line,
character,
},
};
}),
);
}
}

View file

@ -0,0 +1,129 @@
import { createHash } from "crypto";
import { LRUCache } from "lru-cache";
import Parser from "web-tree-sitter";
import { IDE } from "../..";
import { getQueryForFile, TSQueryType } from "../../util/treeSitter";
import { AstPath } from "../ast";
import { AutocompleteSnippet } from "../ranking";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
export class RootPathContextService {
private cache = new LRUCache<string, AutocompleteSnippet[]>({
max: 100,
});
constructor(
private readonly importDefinitionsService: ImportDefinitionsService,
private readonly ide: IDE,
) {}
private static getNodeId(node: Parser.SyntaxNode): string {
return `${node.startIndex}`;
}
private static TYPES_TO_USE = new Set([
"program",
"function_declaration",
"method_definition",
]);
/**
* Key comes from hash of parent key and node type and node id.
*/
private static keyFromNode(
parentKey: string,
astNode: Parser.SyntaxNode,
): string {
return createHash("sha256")
.update(parentKey)
.update(astNode.type)
.update(RootPathContextService.getNodeId(astNode))
.digest("hex");
}
private async getSnippetsForNode(
filepath: string,
node: Parser.SyntaxNode,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
let query: Parser.Query | undefined;
switch (node.type) {
case "program":
this.importDefinitionsService.get(filepath);
break;
case "function_declaration":
query = await getQueryForFile(
filepath,
TSQueryType.FunctionDeclaration,
);
break;
case "method_definition":
query = await getQueryForFile(filepath, TSQueryType.MethodDefinition);
break;
case "function_definition":
query = await getQueryForFile(filepath, TSQueryType.FunctionDefinition);
break;
case "method_declaration":
query = await getQueryForFile(filepath, TSQueryType.MethodDeclaration);
break;
default:
break;
}
if (!query) {
return snippets;
}
await Promise.all(
query.matches(node).map(async (match) => {
const startPosition = match.captures[0].node.startPosition;
const endPosition = match.captures[0].node.endPosition;
const definitions = await this.ide.gotoDefinition({
filepath,
position: {
line: endPosition.row,
character: endPosition.column,
},
});
const newSnippets = await Promise.all(
definitions.map(async (def) => ({
...def,
contents: await this.ide.readRangeInFile(def.filepath, def.range),
})),
);
snippets.push(...newSnippets);
}),
);
return snippets;
}
async getContextForPath(
filepath: string,
astPath: AstPath,
// cursorIndex: number,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
let parentKey = filepath;
for (const astNode of astPath.filter((node) =>
RootPathContextService.TYPES_TO_USE.has(node.type),
)) {
const key = RootPathContextService.keyFromNode(parentKey, astNode);
const foundInCache = this.cache.get(key);
const newSnippets =
foundInCache ?? (await this.getSnippetsForNode(filepath, astNode));
snippets.push(...newSnippets);
if (!foundInCache) {
this.cache.set(key, newSnippets);
}
parentKey = key;
}
return snippets;
}
}

View file

@ -1,6 +1,6 @@
import { distance } from "fastest-levenshtein";
import { DiffLine } from "../";
import { LineStream } from "../diff/util";
import { DiffLine } from "../..";
import { LineStream } from "../../diff/util";
export type LineFilter = (args: {
lines: LineStream;

View file

@ -1,3 +1,4 @@
import { ContextItemWithId, ILLM, SlashCommand } from "../../";
import {
filterCodeBlockLines,
filterEnglishLinesAtEnd,
@ -5,9 +6,8 @@ import {
fixCodeLlamaFirstLineIndentation,
stopAtLines,
streamWithNewLines,
} from "../../autocomplete/lineStream";
} from "../../autocomplete/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { ContextItemWithId, ILLM, SlashCommand } from "../../";
import { stripImages } from "../../llm/images";
import {
dedentAndGetCommonWhitespace,

View file

@ -600,15 +600,19 @@ async function loadFullConfigNode(
try {
module = await import(configJsPath);
} catch (e) {
console.log(e)
console.log("Could not load config.ts as absolute path, retrying as file url ...");
console.log(e);
console.log(
"Could not load config.ts as absolute path, retrying as file url ...",
);
try {
module = await import(`file://${configJsPath}`);
} catch (e) {
throw new Error("Could not load config.ts as file url either", { cause: e });
throw new Error("Could not load config.ts as file url either", {
cause: e,
});
}
}
if (typeof require !== "undefined") {
delete require.cache[require.resolve(configJsPath)];
}

View file

@ -2,7 +2,7 @@ import { ILLM } from "../..";
import {
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/lineStream";
} from "../../autocomplete/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { dedent } from "../../util";

View file

@ -2,7 +2,7 @@ import {
filterLeadingAndTrailingNewLineInsertion,
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/lineStream.js";
} from "../../autocomplete/streamTransforms/lineStream";
import { streamDiff } from "../../diff/streamDiff.js";
import { LineStream, streamLines } from "../../diff/util.js";
import { DiffLine, ILLM } from "../../index.js";

View file

@ -5,7 +5,7 @@ import {
filterLeadingAndTrailingNewLineInsertion,
skipLines,
stopAtLines,
} from "../autocomplete/lineStream.js";
} from "../autocomplete/streamTransforms/lineStream.js";
import { streamDiff } from "../diff/streamDiff.js";
import { streamLines } from "../diff/util.js";
import {

1
core/index.d.ts vendored
View file

@ -882,6 +882,7 @@ export interface TabAutocompleteOptions {
recentLinePrefixMatchMinLength: number;
disableInFiles?: string[];
useImports?: boolean;
useHierarchicalContext?: boolean;
}
export interface ContinueUIConfig {

View file

@ -1,6 +1,7 @@
import { findLlmInfo } from "@continuedev/llm-info";
import Handlebars from "handlebars";
import {
CacheBehavior,
ChatMessage,
ChatMessageRole,
CompletionOptions,
@ -14,7 +15,6 @@ import {
PromptTemplate,
RequestOptions,
TemplateType,
CacheBehavior
} from "../index.js";
import { logDevData } from "../util/devdata.js";
import { DevDataSqliteDb } from "../util/devdataSqlite.js";

21
core/package-lock.json generated
View file

@ -39,6 +39,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
@ -1342,6 +1343,15 @@
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"dev": true,
"dependencies": {
"yallist": "^3.0.2"
}
},
"node_modules/@babel/helper-compilation-targets/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
@ -10481,12 +10491,11 @@
"integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q=="
},
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"dev": true,
"dependencies": {
"yallist": "^3.0.2"
"version": "10.2.2",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz",
"integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==",
"engines": {
"node": "14 || >=16.14"
}
},
"node_modules/mac-ca": {

View file

@ -69,6 +69,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -0,0 +1,76 @@
// File generated by Continue
import { dedentAndGetCommonWhitespace } from "../../util";
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", " "]);
});
});

View file

@ -0,0 +1,51 @@
// File generated by Continue
import { getLastNPathParts } from "../../util";
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("");
});
});

View file

@ -0,0 +1,40 @@
// This file is generated by Continue
import { longestCommonSubsequence } from "../../util/lcs";
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));
});
});

View file

@ -0,0 +1,100 @@
// File generated by Continue
import { mergeJson } from "../../util/merge";
describe("mergeJson", () => {
it("should merge two simple JSON objects", () => {
const first = { a: 1, b: 2 };
const second = { b: 3, c: 4 };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: 3, c: 4 });
});
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");
expect(result).toEqual({ a: 1, b: 3, c: 4 });
});
it("should merge nested objects", () => {
const first = { a: { b: 1 } };
const second = { a: { c: 2 } };
const result = mergeJson(first, second);
expect(result).toEqual({ a: { b: 1, c: 2 } });
});
it("should merge arrays without mergeKeys", () => {
const first = { a: [1, 2] };
const second = { a: [3, 4] };
const result = mergeJson(first, second);
expect(result).toEqual({ a: [1, 2, 3, 4] });
});
it("should merge arrays with mergeKeys", () => {
const first = {
a: [
{ id: 1, value: "first" },
{ id: 2, value: "second" },
],
};
const second = {
a: [
{ id: 2, value: "updated" },
{ id: 3, value: "third" },
],
};
const mergeKeys = {
a: (item1: any, item2: any) => item1.id === item2.id,
};
const result = mergeJson(first, second, undefined, mergeKeys);
expect(result).toEqual({
a: [
{ id: 1, value: "first" },
{ id: 2, value: "updated" },
{ id: 3, value: "third" },
],
});
});
it("should handle non-object values correctly", () => {
const first = { a: 1, b: "string", c: true };
const second = { a: 2, b: "new string", c: false };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 2, b: "new string", c: false });
});
it("should handle null and undefined values correctly", () => {
const first = { a: 1, b: null };
const second = { b: 2, c: undefined };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: 2, c: undefined });
});
it("should handle empty objects", () => {
const first = {};
const second = { a: 1 };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1 });
});
it("should handle empty second object", () => {
const first = { a: 1 };
const second = {};
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1 });
});
it("should handle errors gracefully", () => {
const first = { a: 1 };
const second = { b: () => {} }; // Functions are not serializable in JSON
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: expect.any(Function) });
});
it("should merge deeply nested objects", () => {
const first = { a: { b: { c: 1 } } };
const second = { a: { b: { d: 2 } } };
const result = mergeJson(first, second);
expect(result).toEqual({ a: { b: { c: 1, d: 2 } } });
});
});

View file

@ -0,0 +1,105 @@
// This file is generated by Continue
import { getRangeInString } from "../../../util/ranges";
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");
});
});

View file

@ -0,0 +1,123 @@
// This file is generated by Continue
import { intersection } from "../../../util/ranges";
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 },
});
});
});

View file

@ -0,0 +1,70 @@
import { maxPosition, minPosition } from "../../../util/ranges";
// 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);
});
});
});

View file

@ -0,0 +1,92 @@
import { union } from "../../../util/ranges";
// 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 },
});
});
});

View file

@ -20,6 +20,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
recentLinePrefixMatchMinLength: 7,
disableInFiles: undefined,
useImports: true,
useHierarchicalContext: true,
};
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;

View file

@ -129,6 +129,11 @@ export async function getLanguageForFile(
export enum TSQueryType {
CodeSnippets = "code-snippet-queries",
Imports = "import-queries",
// Used in HierarchicalContextService.ts
FunctionDeclaration = "root-path-context-queries/function_declaration",
MethodDefinition = "root-path-context-queries/method_definition",
FunctionDefinition = "root-path-context-queries/function_definition",
MethodDeclaration = "root-path-context-queries/method_declaration",
}
export async function getQueryForFile(

View file

@ -125,6 +125,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -12,4 +12,4 @@
(interface_declaration
name: (_) @name.definition.interface
) @definition.interface
) @definition.interface

View file

@ -19,4 +19,4 @@
name: (_) @name
parameters: (_) @parameters
) @definition
)
)

View file

@ -5,4 +5,4 @@
name: (name) @name) @definition
(method_declaration
name: (name) @name) @definition
name: (name) @name) @definition

View file

@ -4,4 +4,4 @@
(function_definition
name: (_) @name
parameters: (_) @parameters
) @definition
) @definition

View file

@ -8,4 +8,4 @@
name: (_) @name) @definition
(impl_item
type: (_) @name) @definition
type: (_) @name) @definition

View file

@ -25,4 +25,4 @@
(comment)? @comment
(interface_declaration
name: (_) @name) @definition
)
)

View file

@ -0,0 +1,9 @@
(using_declaration
(qualified_identifier
(identifier) @a))
(namespace_alias_definition
(nested_namespace_specifier) @b)
(preproc_include
(system_lib_string) @c)

View file

@ -0,0 +1,3 @@
(import_declaration
(scoped_identifier
(identifier) @import))

View file

@ -0,0 +1,8 @@
(import_from_statement
(dotted_name) ; skip the first (this is the module)
(dotted_name
(identifier) @importa))
(import_statement
(dotted_name
(identifier) @importb ))

View file

@ -0,0 +1,9 @@
(
(function_declaration
(formal_parameters
(_
(type_annotation) @type
)
)
)
)

View file

@ -0,0 +1,13 @@
(function_definition
(function_declarator
(parameter_list
(parameter_declaration
(type_identifier) @a
)
)
)
)
(function_definition
(type_identifier) @b
)

View file

@ -0,0 +1,17 @@
(
(function_definition
(parameters
(_
(type) @a
(#not-match? @a "^(str|int|float|bool|list|dict|tuple)$")
)
)
)
)
(
(function_definition
(type) @b
(#not-match? @b "^(str|int|float|bool|list|dict|tuple)$")
)
)

View file

@ -0,0 +1,13 @@
; Method parameters
(method_declaration
(formal_parameters
(formal_parameter
(type_identifier) @a
)
)
)
; Return type
(method_declaration
(type_identifier) @b
)

View file

@ -0,0 +1,9 @@
(
(method_definition
(formal_parameters
(_
(type_annotation) @type
)
)
)
)

1
gui/package-lock.json generated
View file

@ -118,6 +118,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -126,7 +126,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
</StyledHeaderButtonWithText>
)}
<ButtonWithTooltip
ext="Delete"
text="Delete"
onClick={(e) => {
e.stopPropagation();
props.onDelete?.();

View file

@ -1,5 +1,15 @@
def main():
from typing import List
Vector = List[float]
def main(a: Vector):
print("Hello Nested!")
class MyClass:
def test(a: Vector) -> Vector:
return a
raise Exception("This is an error")