From d597e6fe5ea632f2bdf762ad2555c056fd736ba8 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 26 Dec 2024 15:53:35 -0600 Subject: [PATCH 01/11] feat: create RecentFilesService --- .../context/ContextRetrievalService.ts | 7 ++ .../context/RecentFilesService.ts | 119 ++++++++++++++++++ core/autocomplete/snippets/getAllSnippets.ts | 5 + 3 files changed, 131 insertions(+) create mode 100644 core/autocomplete/context/RecentFilesService.ts diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 72e061fed..f372456be 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -7,11 +7,13 @@ 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); @@ -19,6 +21,7 @@ export class ContextRetrievalService { this.importDefinitionsService, this.ide, ); + this.recentFilesService = new RecentFilesService(this.ide); } public async getSnippetsFromImportDefinitions( @@ -70,4 +73,8 @@ export class ContextRetrievalService { helper.treePath, ); } + + public async getRecentFileSnippets(): Promise { + return this.recentFilesService.getSnippets(); + } } diff --git a/core/autocomplete/context/RecentFilesService.ts b/core/autocomplete/context/RecentFilesService.ts new file mode 100644 index 000000000..b5a8f34c6 --- /dev/null +++ b/core/autocomplete/context/RecentFilesService.ts @@ -0,0 +1,119 @@ +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; + private numRecentFiles: number; + + constructor( + private readonly ide: IDE, + numRecentFiles = DEFAULT_NUM_RECENT_FILES, + ) { + this.numRecentFiles = numRecentFiles; + this.cache = new LRUCache({ + 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 { + 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; + } +} diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index 5ff4a7d60..a663c0dde 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -3,6 +3,7 @@ import { findUriInDirs } from "../../util/uri"; import { ContextRetrievalService } from "../context/ContextRetrievalService"; import { GetLspDefinitionsFunction } from "../types"; import { HelperVars } from "../util/HelperVars"; + import { AutocompleteClipboardSnippet, AutocompleteCodeSnippet, @@ -17,6 +18,7 @@ export interface SnippetPayload { recentlyEditedRangeSnippets: AutocompleteCodeSnippet[]; diffSnippets: AutocompleteDiffSnippet[]; clipboardSnippets: AutocompleteClipboardSnippet[]; + recentFileSnippets: AutocompleteCodeSnippet[]; } function racePromise(promise: Promise): Promise { @@ -118,6 +120,7 @@ export const getAllSnippets = async ({ ideSnippets, diffSnippets, clipboardSnippets, + recentFileSnippets, ] = await Promise.all([ racePromise(contextRetrievalService.getRootPathSnippets(helper)), racePromise( @@ -126,6 +129,7 @@ export const getAllSnippets = async ({ racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)), racePromise(getDiffSnippets(ide)), racePromise(getClipboardSnippets(ide)), + racePromise(contextRetrievalService.getRecentFileSnippets()), ]); return { @@ -135,5 +139,6 @@ export const getAllSnippets = async ({ recentlyEditedRangeSnippets, diffSnippets, clipboardSnippets, + recentFileSnippets, }; }; From 811507a406ed543adb4a8f876c3c3f30d8a9be35 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 8 Jan 2025 15:59:33 -0800 Subject: [PATCH 02/11] feat(autocomplete): recently visited ranged service --- .../context/ContextRetrievalService.ts | 7 -- .../context/RecentFilesService.ts | 119 ------------------ core/autocomplete/snippets/getAllSnippets.ts | 6 +- core/autocomplete/templating/filtering.ts | 2 + core/autocomplete/util/types.ts | 2 + .../autocomplete/AutocompleteService.kt | 9 +- extensions/vscode/package-lock.json | 46 ++++--- extensions/vscode/package.json | 1 + .../RecentlyVisitedRangesService.ts | 90 +++++++++++++ .../src/autocomplete/completionProvider.ts | 47 +++---- 10 files changed, 144 insertions(+), 185 deletions(-) delete mode 100644 core/autocomplete/context/RecentFilesService.ts create mode 100644 extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index f372456be..72e061fed 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -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 { - return this.recentFilesService.getSnippets(); - } } diff --git a/core/autocomplete/context/RecentFilesService.ts b/core/autocomplete/context/RecentFilesService.ts deleted file mode 100644 index b5a8f34c6..000000000 --- a/core/autocomplete/context/RecentFilesService.ts +++ /dev/null @@ -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; - private numRecentFiles: number; - - constructor( - private readonly ide: IDE, - numRecentFiles = DEFAULT_NUM_RECENT_FILES, - ) { - this.numRecentFiles = numRecentFiles; - this.cache = new LRUCache({ - 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 { - 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; - } -} diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index a663c0dde..198bf16c6 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -16,9 +16,9 @@ export interface SnippetPayload { importDefinitionSnippets: AutocompleteCodeSnippet[]; ideSnippets: AutocompleteCodeSnippet[]; recentlyEditedRangeSnippets: AutocompleteCodeSnippet[]; + recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[]; diffSnippets: AutocompleteDiffSnippet[]; clipboardSnippets: AutocompleteClipboardSnippet[]; - recentFileSnippets: AutocompleteCodeSnippet[]; } function racePromise(promise: Promise): Promise { @@ -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, }; }; diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index a6cdf0957..c741dedc8 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -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], diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index c11d8c2d9..7567f0f62 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -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; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index 6279e03f7..9c39d06be 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -74,9 +74,10 @@ class AutocompleteService(private val project: Project) { "line" to editor.caretModel.primaryCaret.logicalPosition.line, "character" to column ), - "recentlyEditedFiles" to emptyList(), - "recentlyEditedRanges" to emptyList(), - "clipboardText" to "" + "clipboardText" to "", + "recentlyEditedFiles" to emptyList(), + "recentlyEditedRanges" to emptyList(), + "recentlyVisitedRanges" to emptyList(), ) 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() } } }) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index ca4edfc38..6a41a6adb 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -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", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 8470f84fd..f1506c617 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -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", diff --git a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts new file mode 100644 index 000000000..bbe032933 --- /dev/null +++ b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts @@ -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 + >; + private numSurroundingLines = 5; + private maxRecentFiles = 3; + private maxSnippetsPerFile = 3; + + constructor(private readonly ide: IDE) { + this.cache = new LRUCache< + string, + Array + >({ + 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 = + []; + + // 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); + } +} diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index f5388e397..b4c6a611a 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -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); From 0b3cc929220c5c6988cd7349ead525072633cc9b Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 8 Jan 2025 16:56:29 -0800 Subject: [PATCH 03/11] bugfix: only allow `maxSnippetsPerFile` --- core/autocomplete/filtering/test/util.ts | 1 + core/autocomplete/templating/filtering.ts | 4 +++ .../RecentlyVisitedRangesService.ts | 34 ++++++++++++------- .../src/autocomplete/completionProvider.ts | 2 ++ 4 files changed, 28 insertions(+), 13 deletions(-) diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 41a35db07..63bc8147b 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -61,6 +61,7 @@ export async function testAutocompleteFiltering( }, recentlyEditedFiles: [], recentlyEditedRanges: [], + recentlyVisitedRanges: [], }; // Generate a completion diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index c741dedc8..3a72741a2 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -54,6 +54,10 @@ export const getSnippets = ( ), ]; + console.log({ + snippets, + recentlyVisitedRangesSnippets: payload.recentlyVisitedRangesSnippets, + }); const finalSnippets = []; let remainingTokenCount = getRemainingTokenCount(helper); diff --git a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts index bbe032933..b7ed37464 100644 --- a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +++ b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts @@ -26,17 +26,21 @@ export class RecentlyVisitedRangesService { 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); - }); + vscode.window.onDidChangeTextEditorSelection( + this.handleOnDidChangeTextEditorSelection, + ); } - private async onCursorMoved(filepath: string, line: number) { + private handleOnDidChangeTextEditorSelection = async ( + event: vscode.TextEditorSelectionChangeEvent, + ) => { + const filepath = event.textEditor.document.uri.fsPath; + const line = event.selections[0].active.line; const startLine = Math.max(0, line - this.numSurroundingLines); - const endLine = line + this.numSurroundingLines; + const endLine = Math.min( + line + this.numSurroundingLines, + event.textEditor.document.lineCount - 1, + ); try { const fileContents = await this.ide.readFile(filepath); @@ -54,15 +58,19 @@ export class RecentlyVisitedRangesService { }; const existing = this.cache.get(filepath) || []; - this.cache.set(filepath, [...existing, snippet]); + const newSnippets = [...existing, snippet] + .sort((a, b) => b.timestamp - a.timestamp) + .slice(0, this.maxSnippetsPerFile); + + this.cache.set(filepath, newSnippets); } catch (err) { - console.log( + console.error( "Error caching recently visited ranges for autocomplete", err, ); return; } - } + }; /** * Returns up to {@link maxSnippetsPerFile} snippets from the {@link maxRecentFiles} most recently visited files. @@ -71,7 +79,7 @@ export class RecentlyVisitedRangesService { */ public getSnippets(): AutocompleteCodeSnippet[] { const currentFilepath = vscode.window.activeTextEditor?.document.uri.fsPath; - const allSnippets: Array = + let allSnippets: Array = []; // Get most recent snippets from each file in cache @@ -79,7 +87,7 @@ export class RecentlyVisitedRangesService { const snippets = (this.cache.get(filepath) || []) .sort((a, b) => b.timestamp - a.timestamp) .slice(0, this.maxSnippetsPerFile); - allSnippets.push(...snippets); + allSnippets = [...allSnippets, ...snippets]; } return allSnippets diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index b4c6a611a..d00d73987 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -207,6 +207,8 @@ export class ContinueCompletionProvider await this.recentlyEditedTracker.getRecentlyEditedRanges(), }; + console.log({ input }); + setupStatusBar(undefined, true); const outcome = await this.completionProvider.provideInlineCompletionItems( From 1cabf9b745b0222799a93b6611bd8c4567a1e1bc Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 9 Jan 2025 09:50:16 -0800 Subject: [PATCH 04/11] add posthog experiment --- core/autocomplete/templating/filtering.ts | 4 ---- core/util/posthog.ts | 8 ++++++++ .../autocomplete/RecentlyVisitedRangesService.ts | 15 +++++++++++++-- .../vscode/src/autocomplete/completionProvider.ts | 2 -- 4 files changed, 21 insertions(+), 8 deletions(-) diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index 3a72741a2..c741dedc8 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -54,10 +54,6 @@ export const getSnippets = ( ), ]; - console.log({ - snippets, - recentlyVisitedRangesSnippets: payload.recentlyVisitedRangesSnippets, - }); const finalSnippets = []; let remainingTokenCount = getRemainingTokenCount(helper); diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 09a0d9e10..fa0c29f87 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -2,10 +2,12 @@ import os from "node:os"; import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; import { IdeInfo } from "../index.js"; + import type { PostHog as PostHogType } from "posthog-node"; export enum PosthogFeatureFlag { AutocompleteTimeout = "autocomplete-timeout", + RecentlyVisitedRangesNumSurroundingLines = "recently-visited-ranges-num-surrounding-lines", } export const EXPERIMENTS: { @@ -19,6 +21,12 @@ export const EXPERIMENTS: { "350": { value: 350 }, "450": { value: 450 }, }, + [PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines]: { + control: { value: 5 }, + "10": { value: 10 }, + "15": { value: 15 }, + "20": { value: 20 }, + }, }; export class Telemetry { diff --git a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts index b7ed37464..4ddab6046 100644 --- a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +++ b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts @@ -3,6 +3,7 @@ import { AutocompleteCodeSnippet, AutocompleteSnippetType, } from "core/autocomplete/snippets/types"; +import { PosthogFeatureFlag, Telemetry } from "core/util/posthog"; import { LRUCache } from "lru-cache"; import * as vscode from "vscode"; @@ -14,6 +15,7 @@ export class RecentlyVisitedRangesService { string, Array >; + // Default value, we override in setNumSurroundingLinesFromPostHogExperiment private numSurroundingLines = 5; private maxRecentFiles = 3; private maxSnippetsPerFile = 3; @@ -26,15 +28,23 @@ export class RecentlyVisitedRangesService { max: this.maxRecentFiles, }); + void this.setNumSurroundingLinesFromPostHogExperiment(); + vscode.window.onDidChangeTextEditorSelection( this.handleOnDidChangeTextEditorSelection, ); } + private async setNumSurroundingLinesFromPostHogExperiment() { + this.numSurroundingLines = await Telemetry.getValueForFeatureFlag( + PosthogFeatureFlag.AutocompleteTimeout, + ); + } + private handleOnDidChangeTextEditorSelection = async ( event: vscode.TextEditorSelectionChangeEvent, ) => { - const filepath = event.textEditor.document.uri.fsPath; + const filepath = event.textEditor.document.uri.toString(); const line = event.selections[0].active.line; const startLine = Math.max(0, line - this.numSurroundingLines); const endLine = Math.min( @@ -78,7 +88,8 @@ export class RecentlyVisitedRangesService { * @returns Array of code snippets from recently visited files */ public getSnippets(): AutocompleteCodeSnippet[] { - const currentFilepath = vscode.window.activeTextEditor?.document.uri.fsPath; + const currentFilepath = + vscode.window.activeTextEditor?.document.uri.toString(); let allSnippets: Array = []; diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index d00d73987..b4c6a611a 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -207,8 +207,6 @@ export class ContinueCompletionProvider await this.recentlyEditedTracker.getRecentlyEditedRanges(), }; - console.log({ input }); - setupStatusBar(undefined, true); const outcome = await this.completionProvider.provideInlineCompletionItems( From 2a20b5adc98e6923302d9551fcfcb5b4981ca417 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 9 Jan 2025 09:57:30 -0800 Subject: [PATCH 05/11] Update RecentlyVisitedRangesService.ts --- .../src/autocomplete/RecentlyVisitedRangesService.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts index 4ddab6046..5c083b841 100644 --- a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +++ b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts @@ -36,9 +36,10 @@ export class RecentlyVisitedRangesService { } private async setNumSurroundingLinesFromPostHogExperiment() { - this.numSurroundingLines = await Telemetry.getValueForFeatureFlag( - PosthogFeatureFlag.AutocompleteTimeout, - ); + this.numSurroundingLines = + (await Telemetry.getValueForFeatureFlag( + PosthogFeatureFlag.AutocompleteTimeout, + )) ?? this.numSurroundingLines; } private handleOnDidChangeTextEditorSelection = async ( From b283f1b4024361e6713c41905795b4ff9a16fea0 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 9 Jan 2025 10:14:26 -0800 Subject: [PATCH 06/11] update control for posthog --- core/util/posthog.ts | 5 ++-- .../RecentlyVisitedRangesService.ts | 26 ++++++++++++++----- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/core/util/posthog.ts b/core/util/posthog.ts index fa0c29f87..198041207 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -12,7 +12,7 @@ export enum PosthogFeatureFlag { export const EXPERIMENTS: { [key in PosthogFeatureFlag]: { - [key: string]: { value: number }; + [key: string]: { value: any }; }; } = { [PosthogFeatureFlag.AutocompleteTimeout]: { @@ -22,7 +22,8 @@ export const EXPERIMENTS: { "450": { value: 450 }, }, [PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines]: { - control: { value: 5 }, + control: { value: null }, + "5": { value: 5 }, "10": { value: 10 }, "15": { value: 15 }, "20": { value: 20 }, diff --git a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts index 5c083b841..38240d9e1 100644 --- a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +++ b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts @@ -19,6 +19,7 @@ export class RecentlyVisitedRangesService { private numSurroundingLines = 5; private maxRecentFiles = 3; private maxSnippetsPerFile = 3; + private isActive: boolean = false; constructor(private readonly ide: IDE) { this.cache = new LRUCache< @@ -31,18 +32,23 @@ export class RecentlyVisitedRangesService { void this.setNumSurroundingLinesFromPostHogExperiment(); vscode.window.onDidChangeTextEditorSelection( - this.handleOnDidChangeTextEditorSelection, + this.cacheCurrentSelectionContext, ); } private async setNumSurroundingLinesFromPostHogExperiment() { - this.numSurroundingLines = - (await Telemetry.getValueForFeatureFlag( - PosthogFeatureFlag.AutocompleteTimeout, - )) ?? this.numSurroundingLines; + const recentlyVisitedRangesNumSurroundingLines = + await Telemetry.getValueForFeatureFlag( + PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines, + ); + + if (recentlyVisitedRangesNumSurroundingLines) { + this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines; + this.isActive = true; + } } - private handleOnDidChangeTextEditorSelection = async ( + private cacheCurrentSelectionContext = async ( event: vscode.TextEditorSelectionChangeEvent, ) => { const filepath = event.textEditor.document.uri.toString(); @@ -76,7 +82,7 @@ export class RecentlyVisitedRangesService { this.cache.set(filepath, newSnippets); } catch (err) { console.error( - "Error caching recently visited ranges for autocomplete", + "Error caching recently visited ranges for autocomplete: ", err, ); return; @@ -89,6 +95,12 @@ export class RecentlyVisitedRangesService { * @returns Array of code snippets from recently visited files */ public getSnippets(): AutocompleteCodeSnippet[] { + // If the feature is not active (e.g. user is in control group), + // return an empty array to exclude recently visited ranges snippets + if (!this.isActive) { + return []; + } + const currentFilepath = vscode.window.activeTextEditor?.document.uri.toString(); let allSnippets: Array = From 3afe0458393ac9739ac87206039db06c8878f79d Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 9 Jan 2025 10:34:05 -0800 Subject: [PATCH 07/11] fix codestral bug --- core/autocomplete/filtering/test/util.ts | 1 - core/autocomplete/templating/AutocompleteTemplate.ts | 2 +- core/autocomplete/util/types.ts | 1 - .../autocomplete/AutocompleteService.kt | 1 - extensions/vscode/src/autocomplete/completionProvider.ts | 1 - 5 files changed, 1 insertion(+), 5 deletions(-) diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 63bc8147b..6533074b9 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -59,7 +59,6 @@ export async function testAutocompleteFiltering( line, character, }, - recentlyEditedFiles: [], recentlyEditedRanges: [], recentlyVisitedRanges: [], }; diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index e3f087102..e79a9cad7 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -111,7 +111,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { return snippet.content; } - return `+++++ ${relativePaths[i]}\n${snippet.content}`; + return `+++++ ${relativePaths[i].uri} \n${snippet.content}`; }) .join("\n\n"); diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index 7567f0f62..b6379dd61 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -18,7 +18,6 @@ export interface AutocompleteInput { completionId: string; filepath: string; pos: Position; - recentlyEditedFiles: RangeInFileWithContents[]; recentlyVisitedRanges: AutocompleteCodeSnippet[]; recentlyEditedRanges: RecentlyEditedRange[]; // Used for notebook files diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt index f36409d2e..d21c04f56 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/AutocompleteService.kt @@ -75,7 +75,6 @@ class AutocompleteService(private val project: Project) { "character" to column ), "clipboardText" to "", - "recentlyEditedFiles" to emptyList(), "recentlyEditedRanges" to emptyList(), "recentlyVisitedRanges" to emptyList(), ) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index b4c6a611a..d6053869c 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -201,7 +201,6 @@ export class ContinueCompletionProvider isUntitledFile: document.isUntitled, completionId: uuidv4(), filepath: document.uri.toString(), - recentlyEditedFiles: [], recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), recentlyEditedRanges: await this.recentlyEditedTracker.getRecentlyEditedRanges(), From e63e990e78a7680f322e62ac748524b915ad3812 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 9 Jan 2025 10:38:04 -0800 Subject: [PATCH 08/11] Update AutocompleteTemplate.ts --- core/autocomplete/templating/AutocompleteTemplate.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index e79a9cad7..8f7bbd66d 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -117,7 +117,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { return [ `${otherFiles}\n\n+++++ ${ - relativePaths[relativePaths.length - 1] + relativePaths[relativePaths.length - 1].uri }\n${prefix}`, suffix, ]; From 04ad17e2ea14c10eb64daa8b7b6736a78dc344e7 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 9 Jan 2025 11:01:11 -0800 Subject: [PATCH 09/11] Update RecentlyVisitedRangesService.ts --- .../RecentlyVisitedRangesService.ts | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts index 38240d9e1..93a4a7ee6 100644 --- a/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts +++ b/extensions/vscode/src/autocomplete/RecentlyVisitedRangesService.ts @@ -19,7 +19,7 @@ export class RecentlyVisitedRangesService { private numSurroundingLines = 5; private maxRecentFiles = 3; private maxSnippetsPerFile = 3; - private isActive: boolean = false; + private isEnabled = false; constructor(private readonly ide: IDE) { this.cache = new LRUCache< @@ -29,23 +29,25 @@ export class RecentlyVisitedRangesService { max: this.maxRecentFiles, }); - void this.setNumSurroundingLinesFromPostHogExperiment(); - - vscode.window.onDidChangeTextEditorSelection( - this.cacheCurrentSelectionContext, - ); + void this.initWithPostHog(); } - private async setNumSurroundingLinesFromPostHogExperiment() { + private async initWithPostHog() { const recentlyVisitedRangesNumSurroundingLines = await Telemetry.getValueForFeatureFlag( PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines, ); - if (recentlyVisitedRangesNumSurroundingLines) { - this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines; - this.isActive = true; + if (!recentlyVisitedRangesNumSurroundingLines) { + this.isEnabled = false; + return; } + + this.isEnabled = true; + this.numSurroundingLines = recentlyVisitedRangesNumSurroundingLines; + vscode.window.onDidChangeTextEditorSelection( + this.cacheCurrentSelectionContext, + ); } private cacheCurrentSelectionContext = async ( @@ -95,9 +97,7 @@ export class RecentlyVisitedRangesService { * @returns Array of code snippets from recently visited files */ public getSnippets(): AutocompleteCodeSnippet[] { - // If the feature is not active (e.g. user is in control group), - // return an empty array to exclude recently visited ranges snippets - if (!this.isActive) { + if (!this.isEnabled) { return []; } @@ -107,7 +107,7 @@ export class RecentlyVisitedRangesService { []; // Get most recent snippets from each file in cache - for (const filepath of this.cache.keys()) { + for (const filepath of Array.from(this.cache.keys())) { const snippets = (this.cache.get(filepath) || []) .sort((a, b) => b.timestamp - a.timestamp) .slice(0, this.maxSnippetsPerFile); From e6533965bd0c717a1cee0fabccb964e5444d9c8b Mon Sep 17 00:00:00 2001 From: Test Date: Fri, 10 Jan 2025 15:29:12 -0800 Subject: [PATCH 10/11] test(e2e): edit flow --- .eslintrc.shared.json | 1 + extensions/vscode/.eslintrc.json | 2 +- extensions/vscode/e2e/TestUtils.ts | 7 +- .../e2e/actions/Autocomplete.actions.ts | 7 +- extensions/vscode/e2e/actions/Edit.actions.ts | 40 ++++++ extensions/vscode/e2e/actions/GUI.actions.ts | 3 +- .../vscode/e2e/actions/Global.actions.ts | 24 +++- .../e2e/actions/KeyboardShortcuts.actions.ts | 4 +- .../vscode/e2e/selectors/Edit.selectors.ts | 13 ++ .../vscode/e2e/selectors/GUI.selectors.ts | 3 +- .../vscode/e2e/tests/Autocomplete.test.ts | 17 +-- extensions/vscode/e2e/tests/Edit.test.ts | 125 ++++++++++++++++++ extensions/vscode/e2e/tests/GUI.test.ts | 7 +- gui/.eslintrc.json | 3 + .../StepContainer/AcceptRejectAllButtons.tsx | 2 + 15 files changed, 227 insertions(+), 31 deletions(-) create mode 100644 extensions/vscode/e2e/actions/Edit.actions.ts create mode 100644 extensions/vscode/e2e/selectors/Edit.selectors.ts create mode 100644 extensions/vscode/e2e/tests/Edit.test.ts diff --git a/.eslintrc.shared.json b/.eslintrc.shared.json index f4b9c4c78..f62954280 100644 --- a/.eslintrc.shared.json +++ b/.eslintrc.shared.json @@ -6,6 +6,7 @@ }, "plugins": ["@typescript-eslint", "import"], "rules": { + "@typescript-eslint/naming-convention": "off", "@typescript-eslint/semi": "warn", "curly": "warn", "eqeqeq": "warn", diff --git a/extensions/vscode/.eslintrc.json b/extensions/vscode/.eslintrc.json index c25ccff20..f4973fa87 100644 --- a/extensions/vscode/.eslintrc.json +++ b/extensions/vscode/.eslintrc.json @@ -5,6 +5,6 @@ }, "extends": ["../../.eslintrc.shared.json"], "rules": { - "@typescript-eslint/naming-convention": "warn" + "@typescript-eslint/naming-convention": "off" } } diff --git a/extensions/vscode/e2e/TestUtils.ts b/extensions/vscode/e2e/TestUtils.ts index e1ae22227..ad5bc8ede 100644 --- a/extensions/vscode/e2e/TestUtils.ts +++ b/extensions/vscode/e2e/TestUtils.ts @@ -1,9 +1,6 @@ import { expect } from "chai"; -import { - Key, - WebElement, - waitForAttributeValue, -} from "vscode-extension-tester"; +import { Key } from "vscode-extension-tester"; + import { DEFAULT_TIMEOUT } from "./constants"; export class TestUtils { diff --git a/extensions/vscode/e2e/actions/Autocomplete.actions.ts b/extensions/vscode/e2e/actions/Autocomplete.actions.ts index d8b43df29..c35c47a29 100644 --- a/extensions/vscode/e2e/actions/Autocomplete.actions.ts +++ b/extensions/vscode/e2e/actions/Autocomplete.actions.ts @@ -1,8 +1,9 @@ -import { TextEditor } from "vscode-extension-tester"; -import { TestUtils } from "../TestUtils"; -import { AutocompleteSelectors } from "../selectors/Autocomplete.selectors"; import { expect } from "chai"; +import { TextEditor } from "vscode-extension-tester"; + import { DEFAULT_TIMEOUT } from "../constants"; +import { AutocompleteSelectors } from "../selectors/Autocomplete.selectors"; +import { TestUtils } from "../TestUtils"; export class AutocompleteActions { public static async testCompletions(editor: TextEditor) { diff --git a/extensions/vscode/e2e/actions/Edit.actions.ts b/extensions/vscode/e2e/actions/Edit.actions.ts new file mode 100644 index 000000000..c53c2caba --- /dev/null +++ b/extensions/vscode/e2e/actions/Edit.actions.ts @@ -0,0 +1,40 @@ +import { TextEditor, WebView } from "vscode-extension-tester"; + +import { EditSelectors } from "../selectors/Edit.selectors"; +import { TestUtils } from "../TestUtils"; + +export class EditActions { + static async invokeEditShortcut(editor: TextEditor) { + editor + .getDriver() + .actions() + .keyDown(TestUtils.osControlKey) + .sendKeys("i") + .keyUp(TestUtils.osControlKey) + .perform(); + } + + static async acceptEditInGUI(view: WebView): Promise { + await TestUtils.waitForSuccess(async () => + (await EditSelectors.getEditAcceptButton(view)).click(), + ); + await view.switchBack(); + } + + static async rejectEditInGUI(view: WebView): Promise { + await TestUtils.waitForSuccess(async () => + (await EditSelectors.getEditRejectButton(view)).click(), + ); + await view.switchBack(); + } + + static async acceptEditWithCodeLens(editor: TextEditor): Promise { + const acceptCodeLens = await editor.getCodeLens("Accept"); + await acceptCodeLens?.click(); + } + + static async rejectEditWithCodeLens(editor: TextEditor): Promise { + const rejectCodeLens = await editor.getCodeLens("Reject"); + await rejectCodeLens?.click(); + } +} diff --git a/extensions/vscode/e2e/actions/GUI.actions.ts b/extensions/vscode/e2e/actions/GUI.actions.ts index 567a2f572..ace296ca3 100644 --- a/extensions/vscode/e2e/actions/GUI.actions.ts +++ b/extensions/vscode/e2e/actions/GUI.actions.ts @@ -6,9 +6,10 @@ import { WebView, Workbench, } from "vscode-extension-tester"; + +import { DEFAULT_TIMEOUT } from "../constants"; import { GUISelectors } from "../selectors/GUI.selectors"; import { TestUtils } from "../TestUtils"; -import { DEFAULT_TIMEOUT } from "../constants"; export class GUIActions { public static moveContinueToSidebar = async (driver: WebDriver) => { diff --git a/extensions/vscode/e2e/actions/Global.actions.ts b/extensions/vscode/e2e/actions/Global.actions.ts index b6d599089..aafd1040a 100644 --- a/extensions/vscode/e2e/actions/Global.actions.ts +++ b/extensions/vscode/e2e/actions/Global.actions.ts @@ -1,7 +1,29 @@ -import { VSBrowser, WebView } from "vscode-extension-tester"; +import { + EditorView, + InputBox, + TextEditor, + VSBrowser, + Workbench, +} from "vscode-extension-tester"; + +import { DEFAULT_TIMEOUT } from "../constants"; export class GlobalActions { public static async openTestWorkspace() { return VSBrowser.instance.openResources("e2e/test-continue"); } + + public static async createAndOpenNewTextFile(): Promise<{ + editor: TextEditor; + }> { + await new Workbench().executeCommand("Create: New File..."); + await ( + await InputBox.create(DEFAULT_TIMEOUT.MD) + ).selectQuickPick("Text File"); + const editor = (await new EditorView().openEditor( + "Untitled-1", + )) as TextEditor; + + return { editor }; + } } diff --git a/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts b/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts index 0a4cc51ad..358d883bd 100644 --- a/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts +++ b/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts @@ -1,6 +1,4 @@ -import { TextEditor, WebDriver, WebView } from "vscode-extension-tester"; - -import { TestUtils } from "../TestUtils"; +import { TextEditor } from "vscode-extension-tester"; export class KeyboardShortcutsActions { /** diff --git a/extensions/vscode/e2e/selectors/Edit.selectors.ts b/extensions/vscode/e2e/selectors/Edit.selectors.ts new file mode 100644 index 000000000..aaebe576d --- /dev/null +++ b/extensions/vscode/e2e/selectors/Edit.selectors.ts @@ -0,0 +1,13 @@ +import { WebView } from "vscode-extension-tester"; + +import { SelectorUtils } from "./SelectorUtils"; + +export class EditSelectors { + public static getEditAcceptButton(view: WebView) { + return SelectorUtils.getElementByDataTestId(view, "edit-accept-button"); + } + + public static getEditRejectButton(view: WebView) { + return SelectorUtils.getElementByDataTestId(view, "edit-reject-button"); + } +} diff --git a/extensions/vscode/e2e/selectors/GUI.selectors.ts b/extensions/vscode/e2e/selectors/GUI.selectors.ts index 82c0292b4..e7f8c78d0 100644 --- a/extensions/vscode/e2e/selectors/GUI.selectors.ts +++ b/extensions/vscode/e2e/selectors/GUI.selectors.ts @@ -1,4 +1,5 @@ -import { By, until, WebDriver, WebView } from "vscode-extension-tester"; +import { By, WebDriver, WebView } from "vscode-extension-tester"; + import { SelectorUtils } from "./SelectorUtils"; export class GUISelectors { diff --git a/extensions/vscode/e2e/tests/Autocomplete.test.ts b/extensions/vscode/e2e/tests/Autocomplete.test.ts index 50ac6c341..836c2c60e 100644 --- a/extensions/vscode/e2e/tests/Autocomplete.test.ts +++ b/extensions/vscode/e2e/tests/Autocomplete.test.ts @@ -1,13 +1,8 @@ -import { - EditorView, - TextEditor, - InputBox, - Workbench, -} from "vscode-extension-tester"; +import { EditorView, TextEditor } from "vscode-extension-tester"; -import { DEFAULT_TIMEOUT } from "../constants"; -import { GlobalActions } from "../actions/Global.actions"; import { AutocompleteActions } from "../actions/Autocomplete.actions"; +import { GlobalActions } from "../actions/Global.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; describe("Autocomplete", () => { let editor: TextEditor; @@ -16,11 +11,7 @@ describe("Autocomplete", () => { this.timeout(DEFAULT_TIMEOUT.XL); await GlobalActions.openTestWorkspace(); - await new Workbench().executeCommand("Create: New File..."); - await ( - await InputBox.create(DEFAULT_TIMEOUT.MD) - ).selectQuickPick("Text File"); - editor = (await new EditorView().openEditor("Untitled-1")) as TextEditor; + ({ editor } = await GlobalActions.createAndOpenNewTextFile()); }); afterEach(async function () { diff --git a/extensions/vscode/e2e/tests/Edit.test.ts b/extensions/vscode/e2e/tests/Edit.test.ts new file mode 100644 index 000000000..e79dd010c --- /dev/null +++ b/extensions/vscode/e2e/tests/Edit.test.ts @@ -0,0 +1,125 @@ +import { + EditorView, + WebView, + WebDriver, + Key, + VSBrowser, + InputBox, + TextEditor, + Workbench, +} from "vscode-extension-tester"; + +import { EditActions } from "../actions/Edit.actions"; +import { GlobalActions } from "../actions/Global.actions"; +import { GUIActions } from "../actions/GUI.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; +import { EditSelectors } from "../selectors/Edit.selectors"; +import { GUISelectors } from "../selectors/GUI.selectors"; +import { TestUtils } from "../TestUtils"; + +describe("Edit Test", () => { + let view: WebView; + let editor: TextEditor; + let originalEditorText = "Hello world!"; + let { userMessage, llmResponse } = TestUtils.generateTestMessagePair(); + + before(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + await GUIActions.moveContinueToSidebar(VSBrowser.instance.driver); + await GlobalActions.openTestWorkspace(); + ({ editor } = await GlobalActions.createAndOpenNewTextFile()); + }); + + beforeEach(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await GUIActions.toggleGui(); + + await editor.typeTextAt(1, 1, originalEditorText); + await editor.selectText(originalEditorText); + + await EditActions.invokeEditShortcut(editor); + + ({ view } = await GUIActions.switchToReactIframe()); + + await GUIActions.sendMessage({ + view, + message: userMessage, + inputFieldIndex: 0, + }); + + await view.switchBack(); + + await TestUtils.waitForSuccess(async () => { + const editorText = await editor.getText(); + return editorText.includes(llmResponse); + }); + }); + + afterEach(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + await editor.clearText(); + }); + + it("Accepts an Edit in the GUI", async () => { + ({ view } = await GUIActions.switchToReactIframe()); + + await EditActions.acceptEditInGUI(view); + + await view.switchBack(); + + const editorText = await editor.getText(); + + await TestUtils.waitForSuccess( + async () => + !editorText.includes(originalEditorText) && + editorText.includes(llmResponse), + DEFAULT_TIMEOUT.SM, + ); + }).timeout(DEFAULT_TIMEOUT.XL); + + it("Rejects an Edit in the GUI", async () => { + ({ view } = await GUIActions.switchToReactIframe()); + + await EditActions.rejectEditInGUI(view); + + await view.switchBack(); + + const editorText = await editor.getText(); + + await TestUtils.waitForSuccess( + async () => + editorText.includes(originalEditorText) && + !editorText.includes(llmResponse), + DEFAULT_TIMEOUT.SM, + ); + }).timeout(DEFAULT_TIMEOUT.XL); + + it("Accepts an Edit using CodeLens buttons", async () => { + const acceptCodeLens = await editor.getCodeLens("Accept"); + await acceptCodeLens?.click(); + + const editorText = await editor.getText(); + + await TestUtils.waitForSuccess( + async () => + !editorText.includes(originalEditorText) && + editorText.includes(llmResponse), + DEFAULT_TIMEOUT.SM, + ); + }).timeout(DEFAULT_TIMEOUT.XL); + + it("Rejects an Edit using CodeLens buttons", async () => { + const rejectCodeLens = await editor.getCodeLens("Reject"); + await rejectCodeLens?.click(); + + const editorText = await editor.getText(); + + await TestUtils.waitForSuccess( + async () => + !editorText.includes(originalEditorText) && + editorText.includes(llmResponse), + DEFAULT_TIMEOUT.SM, + ); + }).timeout(DEFAULT_TIMEOUT.XL); +}); diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index b5e3cabc3..644cbaf64 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -1,3 +1,4 @@ +import { expect } from "chai"; import { EditorView, WebView, @@ -7,12 +8,12 @@ import { VSBrowser, until, } from "vscode-extension-tester"; -import { expect } from "chai"; + +import { GlobalActions } from "../actions/Global.actions"; import { GUIActions } from "../actions/GUI.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; import { GUISelectors } from "../selectors/GUI.selectors"; import { TestUtils } from "../TestUtils"; -import { DEFAULT_TIMEOUT } from "../constants"; -import { GlobalActions } from "../actions/Global.actions"; describe("GUI Test", () => { let view: WebView; diff --git a/gui/.eslintrc.json b/gui/.eslintrc.json index 346c650fe..c902e379f 100644 --- a/gui/.eslintrc.json +++ b/gui/.eslintrc.json @@ -11,6 +11,9 @@ // "plugin:@typescript-eslint/recommended-requiring-type-checking" // "plugin:react/recommended" ], + "rules": { + "@typescript-eslint/naming-convention": "off" + }, "overrides": [ { "files": ["src/**/*.{js,ts,jsx,tsx}"] diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx index 532593c18..8d2e59dd3 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -38,6 +38,7 @@ export default function AcceptRejectAllButtons({