feat(autocomplete): recently visited ranged service

This commit is contained in:
Test 2025-01-08 15:59:33 -08:00
parent d597e6fe5e
commit 811507a406
10 changed files with 144 additions and 185 deletions

View file

@ -7,13 +7,11 @@ import { HelperVars } from "../util/HelperVars";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
import { getSymbolsForSnippet } from "./ranking";
import { RecentFilesService } from "./RecentFilesService";
import { RootPathContextService } from "./root-path-context/RootPathContextService";
export class ContextRetrievalService {
private importDefinitionsService: ImportDefinitionsService;
private rootPathContextService: RootPathContextService;
private recentFilesService: RecentFilesService;
constructor(private readonly ide: IDE) {
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
@ -21,7 +19,6 @@ export class ContextRetrievalService {
this.importDefinitionsService,
this.ide,
);
this.recentFilesService = new RecentFilesService(this.ide);
}
public async getSnippetsFromImportDefinitions(
@ -73,8 +70,4 @@ export class ContextRetrievalService {
helper.treePath,
);
}
public async getRecentFileSnippets(): Promise<AutocompleteCodeSnippet[]> {
return this.recentFilesService.getSnippets();
}
}

View file

@ -1,119 +0,0 @@
import { LRUCache } from "lru-cache";
import Parser from "web-tree-sitter";
import { IDE } from "../..";
import {
getFullLanguageName,
getParserForFile,
getQueryForFile,
} from "../../util/treeSitter";
import {
AutocompleteCodeSnippet,
AutocompleteSnippetType,
} from "../snippets/types";
const DEFAULT_NUM_RECENT_FILES = 5;
export class RecentFilesService {
private cache: LRUCache<string, AutocompleteCodeSnippet[]>;
private numRecentFiles: number;
constructor(
private readonly ide: IDE,
numRecentFiles = DEFAULT_NUM_RECENT_FILES,
) {
this.numRecentFiles = numRecentFiles;
this.cache = new LRUCache<string, AutocompleteCodeSnippet[]>({
max: this.numRecentFiles,
});
this.ide.onDidChangeActiveTextEditor((filepath) => {
void this.onFileOpened(filepath);
});
}
private async onFileOpened(filepath: string) {
// Remove from cache if already present to update its position
if (this.cache.has(filepath)) {
this.cache.delete(filepath);
}
// Get function signatures from the file
const snippets = await this.getFunctionSignatures(filepath);
if (snippets.length > 0) {
// Store in cache
this.cache.set(filepath, snippets);
}
}
private async getFunctionSignatures(
filepath: string,
): Promise<AutocompleteCodeSnippet[]> {
const snippets: AutocompleteCodeSnippet[] = [];
const parser = await getParserForFile(filepath);
if (!parser) {
return snippets;
}
let fileContents: string;
try {
fileContents = await this.ide.readFile(filepath);
} catch (err) {
// File might have been deleted or inaccessible
return snippets;
}
const ast = parser.parse(fileContents);
const language = getFullLanguageName(filepath);
const query = await getQueryForFile(
filepath,
`code-snippet-queries/${language}.scm`,
);
if (!query) {
return snippets;
}
const matches = query.matches(ast.rootNode);
if (!matches) {
return snippets;
}
return matches
.map((match) => this.getSnippetFromMatch(match, filepath))
.filter(
(snippet): snippet is AutocompleteCodeSnippet => snippet !== null,
);
}
private getSnippetFromMatch(
match: Parser.QueryMatch,
filepath: string,
): AutocompleteCodeSnippet | null {
// We only care about the function signature/declaration, not the body
for (const { name, node } of match.captures) {
// Skip function bodies, we only want the signature
// if (name.includes("body") || node.type.includes("body")) {
// continue;
// }
return {
filepath,
content: node.text.trim(),
type: AutocompleteSnippetType.Code,
};
}
return null;
}
public getSnippets(): AutocompleteCodeSnippet[] {
const allSnippets: AutocompleteCodeSnippet[] = [];
for (const snippets of this.cache.values()) {
allSnippets.push(...snippets);
}
return allSnippets;
}
}

View file

@ -16,9 +16,9 @@ export interface SnippetPayload {
importDefinitionSnippets: AutocompleteCodeSnippet[];
ideSnippets: AutocompleteCodeSnippet[];
recentlyEditedRangeSnippets: AutocompleteCodeSnippet[];
recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[];
diffSnippets: AutocompleteDiffSnippet[];
clipboardSnippets: AutocompleteClipboardSnippet[];
recentFileSnippets: AutocompleteCodeSnippet[];
}
function racePromise<T>(promise: Promise<T[]>): Promise<T[]> {
@ -120,7 +120,6 @@ export const getAllSnippets = async ({
ideSnippets,
diffSnippets,
clipboardSnippets,
recentFileSnippets,
] = await Promise.all([
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
racePromise(
@ -129,7 +128,6 @@ export const getAllSnippets = async ({
racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)),
racePromise(getDiffSnippets(ide)),
racePromise(getClipboardSnippets(ide)),
racePromise(contextRetrievalService.getRecentFileSnippets()),
]);
return {
@ -139,6 +137,6 @@ export const getAllSnippets = async ({
recentlyEditedRangeSnippets,
diffSnippets,
clipboardSnippets,
recentFileSnippets,
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
};
};

View file

@ -5,6 +5,7 @@ import {
AutocompleteSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { isValidSnippet } from "./validation";
const getRemainingTokenCount = (helper: HelperVars): number => {
@ -44,6 +45,7 @@ export const getSnippets = (
const snippets = [
...payload.diffSnippets,
...payload.clipboardSnippets,
...payload.recentlyVisitedRangesSnippets,
...shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],

View file

@ -5,6 +5,7 @@ import {
RangeInFileWithContents,
TabAutocompleteOptions,
} from "../..";
import { AutocompleteCodeSnippet } from "../snippets/types";
export type RecentlyEditedRange = RangeInFile & {
timestamp: number;
@ -18,6 +19,7 @@ export interface AutocompleteInput {
filepath: string;
pos: Position;
recentlyEditedFiles: RangeInFileWithContents[];
recentlyVisitedRanges: AutocompleteCodeSnippet[];
recentlyEditedRanges: RecentlyEditedRange[];
// Used for notebook files
manuallyPassFileContents?: string;

View file

@ -74,9 +74,10 @@ class AutocompleteService(private val project: Project) {
"line" to editor.caretModel.primaryCaret.logicalPosition.line,
"character" to column
),
"recentlyEditedFiles" to emptyList<String>(),
"recentlyEditedRanges" to emptyList<String>(),
"clipboardText" to ""
"clipboardText" to "",
"recentlyEditedFiles" to emptyList<Any>(),
"recentlyEditedRanges" to emptyList<Any>(),
"recentlyVisitedRanges" to emptyList<Any>(),
)
val lineStart = editor.document.getLineStartOffset(editor.caretModel.primaryCaret.logicalPosition.line)
@ -98,8 +99,6 @@ class AutocompleteService(private val project: Project) {
if (shouldRenderCompletion(finalTextToInsert, column, lineLength, editor)) {
renderCompletion(editor, offset, finalTextToInsert)
pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert)
// Hide auto-popup
// AutoPopupController.getInstance(project).cancelAllRequests()
}
}
})

View file

@ -35,6 +35,7 @@
"https-proxy-agent": "^7.0.2",
"ignore": "^5.3.0",
"jsdom": "^24.0.0",
"lru-cache": "^11.0.2",
"minisearch": "^7.0.0",
"monaco-editor": "^0.45.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",
@ -6738,6 +6739,18 @@
"node": ">=10"
}
},
"node_modules/hosted-git-info/node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
"dev": true,
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/hpagent": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/hpagent/-/hpagent-1.2.0.tgz",
@ -7919,15 +7932,11 @@
}
},
"node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
"devOptional": true,
"dependencies": {
"yallist": "^4.0.0"
},
"version": "11.0.2",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.2.tgz",
"integrity": "sha512-123qHRfJBmo2jXDbo/a5YOQrJoHF/GNQTLzQ5+IdK5pWpceK17yRc6ozlWd25FxvGKQbIUs91fDFkXmDHTKcyA==",
"engines": {
"node": ">=10"
"node": "20 || >=22"
}
},
"node_modules/lru-queue": {
@ -9367,6 +9376,18 @@
"node": ">= 6"
}
},
"node_modules/node-gyp/node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
"optional": true,
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/node-gyp/node_modules/make-fetch-happen": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-9.1.0.tgz",
@ -14294,15 +14315,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/vscode-extension-tester/node_modules/lru-cache": {
"version": "11.0.2",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.0.2.tgz",
"integrity": "sha512-123qHRfJBmo2jXDbo/a5YOQrJoHF/GNQTLzQ5+IdK5pWpceK17yRc6ozlWd25FxvGKQbIUs91fDFkXmDHTKcyA==",
"dev": true,
"engines": {
"node": "20 || >=22"
}
},
"node_modules/vscode-extension-tester/node_modules/markdown-it": {
"version": "14.1.0",
"resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz",

View file

@ -690,6 +690,7 @@
"https-proxy-agent": "^7.0.2",
"ignore": "^5.3.0",
"jsdom": "^24.0.0",
"lru-cache": "^11.0.2",
"minisearch": "^7.0.0",
"monaco-editor": "^0.45.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",

View file

@ -0,0 +1,90 @@
import { IDE } from "core";
import {
AutocompleteCodeSnippet,
AutocompleteSnippetType,
} from "core/autocomplete/snippets/types";
import { LRUCache } from "lru-cache";
import * as vscode from "vscode";
/**
* Service to keep track of recently visited ranges in files.
*/
export class RecentlyVisitedRangesService {
private cache: LRUCache<
string,
Array<AutocompleteCodeSnippet & { timestamp: number }>
>;
private numSurroundingLines = 5;
private maxRecentFiles = 3;
private maxSnippetsPerFile = 3;
constructor(private readonly ide: IDE) {
this.cache = new LRUCache<
string,
Array<AutocompleteCodeSnippet & { timestamp: number }>
>({
max: this.maxRecentFiles,
});
// Subscribe to cursor movement
vscode.window.onDidChangeTextEditorSelection((event) => {
const filepath = event.textEditor.document.uri.fsPath;
const line = event.selections[0].active.line;
void this.onCursorMoved(filepath, line);
});
}
private async onCursorMoved(filepath: string, line: number) {
const startLine = Math.max(0, line - this.numSurroundingLines);
const endLine = line + this.numSurroundingLines;
try {
const fileContents = await this.ide.readFile(filepath);
const lines = fileContents.split("\n");
const relevantLines = lines
.slice(startLine, endLine + 1)
.join("\n")
.trim();
const snippet: AutocompleteCodeSnippet & { timestamp: number } = {
filepath,
content: relevantLines,
type: AutocompleteSnippetType.Code,
timestamp: Date.now(),
};
const existing = this.cache.get(filepath) || [];
this.cache.set(filepath, [...existing, snippet]);
} catch (err) {
console.log(
"Error caching recently visited ranges for autocomplete",
err,
);
return;
}
}
/**
* Returns up to {@link maxSnippetsPerFile} snippets from the {@link maxRecentFiles} most recently visited files.
* Excludes snippets from the currently active file.
* @returns Array of code snippets from recently visited files
*/
public getSnippets(): AutocompleteCodeSnippet[] {
const currentFilepath = vscode.window.activeTextEditor?.document.uri.fsPath;
const allSnippets: Array<AutocompleteCodeSnippet & { timestamp: number }> =
[];
// Get most recent snippets from each file in cache
for (const filepath of this.cache.keys()) {
const snippets = (this.cache.get(filepath) || [])
.sort((a, b) => b.timestamp - a.timestamp)
.slice(0, this.maxSnippetsPerFile);
allSnippets.push(...snippets);
}
return allSnippets
.filter((s) => !currentFilepath || s.filepath !== currentFilepath)
.sort((a, b) => b.timestamp - a.timestamp)
.map(({ timestamp, ...snippet }) => snippet);
}
}

View file

@ -4,25 +4,27 @@ import {
type AutocompleteOutcome,
} from "core/autocomplete/util/types";
import { ConfigHandler } from "core/config/ConfigHandler";
import * as URI from "uri-js";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
const Diff = require("diff");
import { showFreeTrialLoginMessage } from "../util/messages";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import { getDefinitionsFromLsp } from "./lsp";
import { RecentlyEditedTracker } from "./recentlyEdited";
import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService";
import {
StatusBarStatus,
getStatusBarStatus,
setupStatusBar,
stopStatusBarLoading,
} from "./statusBar";
import * as URI from "uri-js";
import type { IDE } from "core";
import type { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import type { IDE } from "core";
const Diff = require("diff");
interface DiffType {
count: number;
@ -70,6 +72,7 @@ export class ContinueCompletionProvider
}
private completionProvider: CompletionProvider;
private recentlyVisitedRanges: RecentlyVisitedRangesService;
private recentlyEditedTracker = new RecentlyEditedTracker();
constructor(
@ -85,6 +88,7 @@ export class ContinueCompletionProvider
this.onError.bind(this),
getDefinitionsFromLsp,
);
this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide);
}
_lastShownCompletion: AutocompleteOutcome | undefined;
@ -126,30 +130,6 @@ export class ContinueCompletionProvider
}
let injectDetails: string | undefined = undefined;
// Here we could use the details from the intellisense dropdown
// and place them just above the line being typed but because
// we don't have control over the formatting of the details and
// they could be especially long, not doing this for now
// if (context.selectedCompletionInfo) {
// const results: any = await vscode.commands.executeCommand(
// "vscode.executeCompletionItemProvider",
// document.uri,
// position,
// null,
// 1,
// );
// if (results?.items) {
// injectDetails = results.items?.[0]?.detail;
// // const label = results?.items?.[0].label;
// // const workspaceSymbols = (
// // (await vscode.commands.executeCommand(
// // "vscode.executeWorkspaceSymbolProvider",
// // label,
// // )) as any
// // ).filter((symbol: any) => symbol.name === label);
// // console.log(label, "=>", workspaceSymbols);
// }
// }
// The first time intellisense dropdown shows up, and the first choice is selected,
// we should not consider this. Only once user explicitly moves down the list
@ -213,17 +193,18 @@ export class ContinueCompletionProvider
let manuallyPassPrefix: string | undefined = undefined;
const input: AutocompleteInput = {
isUntitledFile: document.isUntitled,
completionId: uuidv4(),
filepath: document.uri.toString(),
pos,
recentlyEditedFiles: [],
recentlyEditedRanges:
await this.recentlyEditedTracker.getRecentlyEditedRanges(),
manuallyPassFileContents,
manuallyPassPrefix,
selectedCompletionInfo,
injectDetails,
isUntitledFile: document.isUntitled,
completionId: uuidv4(),
filepath: document.uri.toString(),
recentlyEditedFiles: [],
recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
recentlyEditedRanges:
await this.recentlyEditedTracker.getRecentlyEditedRanges(),
};
setupStatusBar(undefined, true);