diff --git a/binary/package-lock.json b/binary/package-lock.json index 11dd6505b..85ce515a1 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -77,6 +77,7 @@ "handlebars": "^4.7.8", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", + "iconv-lite": "^0.6.3", "ignore": "^5.3.1", "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", @@ -90,7 +91,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.76.0", + "openai": "^4.104.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", diff --git a/core/config/types.ts b/core/config/types.ts index c90220ed4..b9be2b209 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -743,6 +743,10 @@ declare global { // LSP gotoDefinition(location: Location): Promise; + gotoTypeDefinition(location: Location): Promise; + getSignatureHelp(location: Location): Promise; + getReferences(location: Location): Promise; + getDocumentSymbols(textDocumentIdentifier: string): Promise; // Callbacks onDidChangeActiveTextEditor(callback: (filepath: string) => void): void; diff --git a/core/core.ts b/core/core.ts index 9b7e80cde..7cf6dd6e1 100644 --- a/core/core.ts +++ b/core/core.ts @@ -603,6 +603,7 @@ export class Core { const outcome = await this.nextEditProvider.provideInlineCompletionItems( msg.data, undefined, + { withChain: false }, ); return outcome ? [outcome.completion, outcome.originalEditableRange] : []; }); diff --git a/core/index.d.ts b/core/index.d.ts index f96cc7716..07685da50 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -874,6 +874,8 @@ export interface IDE { gotoDefinition(location: Location): Promise; gotoTypeDefinition(location: Location): Promise; // TODO: add to jetbrains getSignatureHelp(location: Location): Promise; // TODO: add to jetbrains + getReferences(location: Location): Promise; + getDocumentSymbols(textDocumentIdentifier: string): Promise; // Callbacks onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void; @@ -1795,3 +1797,56 @@ export interface CompiledMessagesResult { export interface MessageOption { precompiled: boolean; } + +/* LSP-specific interfaces. */ + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolKind. +// We shift this one index down to match vscode.SymbolKind. +export enum SymbolKind { + File = 0, + Module = 1, + Namespace = 2, + Package = 3, + Class = 4, + Method = 5, + Property = 6, + Field = 7, + Constructor = 8, + Enum = 9, + Interface = 10, + Function = 11, + Variable = 12, + Constant = 13, + String = 14, + Number = 15, + Boolean = 16, + Array = 17, + Object = 18, + Key = 19, + Null = 20, + EnumMember = 21, + Struct = 22, + Event = 23, + Operator = 24, + TypeParameter = 25, +} + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolTag. +export namespace SymbolTag { + export const Deprecated: 1 = 1; +} + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolTag. +export type SymbolTag = 1; + +// See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#documentSymbol. +export interface DocumentSymbol { + name: string; + detail?: string; + kind: SymbolKind; + tags?: SymbolTag[]; + deprecated?: boolean; + range: Range; + selectionRange: Range; + children?: DocumentSymbol[]; +} diff --git a/core/nextEdit/DocumentHistoryTracker.ts b/core/nextEdit/DocumentHistoryTracker.ts new file mode 100644 index 000000000..7cca91f56 --- /dev/null +++ b/core/nextEdit/DocumentHistoryTracker.ts @@ -0,0 +1,137 @@ +import Parser from "web-tree-sitter"; + +/** + * Singleton class that keeps track of a map of document paths to their history. + * The point here is to prevent re-calculating the AST, + * and to preserve an older, original state of the document before any user edits. + */ +export class DocumentHistoryTracker { + private static instance: DocumentHistoryTracker | null = null; + + // Map from document path to history (LIFO stack where newest representation is at the front). + private documentAstMap: Map; + private documentContentHistoryMap: Map; + + private constructor() { + this.documentAstMap = new Map(); + this.documentContentHistoryMap = new Map(); + } + + /** + * Get the singleton instance of DocumentHistoryTracker. + */ + public static getInstance(): DocumentHistoryTracker { + if (!DocumentHistoryTracker.instance) { + DocumentHistoryTracker.instance = new DocumentHistoryTracker(); + } + + return DocumentHistoryTracker.instance; + } + + /** + * Add a document and its first state to the tracker. + * + * @param documentPath The path of the document. + * @param documentContent The first content of the document. + * @param ast The first AST of the document. + */ + public addDocument( + documentPath: string, + documentContent: string, + ast: Parser.Tree, + ): void { + this.documentAstMap.set(documentPath, [ast]); + this.documentContentHistoryMap.set(documentPath, [documentContent]); + } + + /** + * Push a new AST to an existing document's history stack. + * + * @param documentPath The path of the document. + * @param documentContent The new content to push to the document's history stack. + * @param ast The new AST to push to the document's history stack. + * @throws Error if the document doesn't exist in the tracker. + */ + public push( + documentPath: string, + documentContent: string, + ast: Parser.Tree, + ): void { + const astHistory = this.documentAstMap.get(documentPath); + const documentHistory = this.documentContentHistoryMap.get(documentPath); + + if (!astHistory || !documentHistory) { + console.error(`Document ${documentPath} not found in AST tracker`); + this.addDocument(documentPath, documentContent, ast); + return; // Early return - document was added with initial state + } + + // Only execute this if the arrays already existed + astHistory.unshift(ast); + documentHistory.unshift(documentContent); + } + + /** + * Get the most recent AST of a document. + * + * @param documentPath The path of the document. + * @returns The most recent AST of the document. + * @throws Error if the document doesn't exist in the tracker. + */ + public getMostRecentAst(documentPath: string): Parser.Tree | null { + const astHistory = this.documentAstMap.get(documentPath); + + if (!astHistory) { + console.error(`Document ${documentPath} not found in AST tracker`); + return null; + } + if (astHistory.length === 0) { + console.error(`Document ${documentPath} has no ASTs`); + return null; + } + + // Return the first element (most recent AST). + return astHistory[0]; + } + + /** + * Get the most recent AST of a document. + * + * @param documentPath The path of the document. + * @returns The most recent document history of the document. + * @throws Error if the document doesn't exist in the tracker. + */ + public getMostRecentDocumentHistory(documentPath: string): string | null { + const documentHistory = this.documentContentHistoryMap.get(documentPath); + + if (!documentHistory) { + console.error(`Document ${documentPath} not found in AST tracker`); + return null; + } + if (documentHistory.length === 0) { + console.error(`Document ${documentPath} has no history`); + return null; + } + + // Return the first element (most recent doc history). + return documentHistory[0]; + } + + /** + * Delete a document from the tracker. + * + * @param documentPath The path of the document to delete. + */ + public deleteDocument(documentPath: string): void { + this.documentAstMap.delete(documentPath); + this.documentContentHistoryMap.delete(documentPath); + } + + /** + * Clear all documents from the tracker. + */ + public clearMap(): void { + this.documentAstMap.clear(); + this.documentContentHistoryMap.clear(); + } +} diff --git a/core/nextEdit/DocumentHistoryTracker.vitest.ts b/core/nextEdit/DocumentHistoryTracker.vitest.ts new file mode 100644 index 000000000..f6c9b2dd4 --- /dev/null +++ b/core/nextEdit/DocumentHistoryTracker.vitest.ts @@ -0,0 +1,228 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import Parser from "web-tree-sitter"; +import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; + +// Mock the Parser.Tree class +vi.mock("web-tree-sitter", () => { + return { + default: { + Tree: class MockTree { + constructor() { + // Mock implementation + } + }, + }, + }; +}); + +describe("DocumentHistoryTracker", () => { + let tracker: DocumentHistoryTracker; + let mockAst1: Parser.Tree; + let mockAst2: Parser.Tree; + const testDocPath = "/test/document.ts"; + const testContent1 = "const x = 1;"; + const testContent2 = "const x = 2;"; + + beforeEach(() => { + // Reset singleton instance for each test + // @ts-ignore - accessing private static property for testing + DocumentHistoryTracker.instance = null; + tracker = DocumentHistoryTracker.getInstance(); + + // Create mock ASTs + //@ts-ignore + mockAst1 = new Parser.Tree() as Parser.Tree; + //@ts-ignore + mockAst2 = new Parser.Tree() as Parser.Tree; + }); + + afterEach(() => { + // Clear the tracker after each test + tracker.clearMap(); + }); + + describe("getInstance", () => { + it("should return a singleton instance", () => { + const instance1 = DocumentHistoryTracker.getInstance(); + const instance2 = DocumentHistoryTracker.getInstance(); + expect(instance1).toBe(instance2); + }); + }); + + describe("addDocument", () => { + it("should add a document to the tracker", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBe(mockAst1); + expect(content).toBe(testContent1); + }); + }); + + describe("push", () => { + it("should push a new AST to an existing document's history stack", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBe(mockAst2); + expect(content).toBe(testContent2); + }); + + it("should add a document if it doesn't exist when pushing", () => { + tracker.push(testDocPath, testContent1, mockAst1); + + // Check if document was actually added + const ast = tracker.getMostRecentAst(testDocPath); + expect(ast).toBe(mockAst1); + }); + }); + + describe("getMostRecentAst", () => { + it("should return the most recent AST of a document", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const ast = tracker.getMostRecentAst(testDocPath); + + expect(ast).toBe(mockAst2); + }); + + it("should return null if the document doesn't exist", () => { + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst("nonexistent-path"); + + expect(ast).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + "Document nonexistent-path not found in AST tracker", + ); + + consoleErrorSpy.mockRestore(); + }); + + it("should return null if the document has no ASTs", () => { + // This test would require modifying private properties + // So we'll mock an empty array situation + tracker.addDocument(testDocPath, testContent1, mockAst1); + + // @ts-ignore - accessing private property for testing + tracker.documentAstMap.set(testDocPath, []); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst(testDocPath); + + expect(ast).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} has no ASTs`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("getMostRecentDocumentHistory", () => { + it("should return the most recent document history", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.push(testDocPath, testContent2, mockAst2); + + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(content).toBe(testContent2); + }); + + it("should return null if the document doesn't exist", () => { + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const content = tracker.getMostRecentDocumentHistory("nonexistent-path"); + + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + "Document nonexistent-path not found in AST tracker", + ); + + consoleErrorSpy.mockRestore(); + }); + + it("should return null if the document has no history", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + + // @ts-ignore - accessing private property for testing + tracker.documentContentHistoryMap.set(testDocPath, []); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} has no history`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("deleteDocument", () => { + it("should delete a document from the tracker", () => { + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.deleteDocument(testDocPath); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + const ast = tracker.getMostRecentAst(testDocPath); + const content = tracker.getMostRecentDocumentHistory(testDocPath); + + expect(ast).toBeNull(); + expect(content).toBeNull(); + expect(consoleErrorSpy).toHaveBeenCalledWith( + `Document ${testDocPath} not found in AST tracker`, + ); + + consoleErrorSpy.mockRestore(); + }); + }); + + describe("clearMap", () => { + it("should clear all documents from the tracker", () => { + const anotherDocPath = "/test/another-document.ts"; + + tracker.addDocument(testDocPath, testContent1, mockAst1); + tracker.addDocument(anotherDocPath, testContent1, mockAst1); + + tracker.clearMap(); + + // Spy on console.error + const consoleErrorSpy = vi + .spyOn(console, "error") + .mockImplementation(() => {}); + + expect(tracker.getMostRecentAst(testDocPath)).toBeNull(); + expect(tracker.getMostRecentAst(anotherDocPath)).toBeNull(); + expect(tracker.getMostRecentDocumentHistory(testDocPath)).toBeNull(); + expect(tracker.getMostRecentDocumentHistory(anotherDocPath)).toBeNull(); + + consoleErrorSpy.mockRestore(); + }); + }); +}); diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts new file mode 100644 index 000000000..7f5d13b66 --- /dev/null +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -0,0 +1,800 @@ +import Parser from "web-tree-sitter"; +import { Chunk, IDE, ILLM, Position, Range, RangeInFile } from ".."; +import { getAst } from "../autocomplete/util/ast"; +import { DocumentHistoryTracker } from "./DocumentHistoryTracker"; + +export enum EditableRegionStrategy { + Naive = "naive", + Rerank = "rerank", + StaticRerank = "staticRerank", + Static = "static", +} + +export async function getNextEditableRegion( + strategy: EditableRegionStrategy, + ctx: any, +): Promise { + switch (strategy) { + case EditableRegionStrategy.Naive: + return naiveJump(ctx); + case EditableRegionStrategy.Rerank: + return await rerankJump(ctx); + case EditableRegionStrategy.StaticRerank: + return await staticRerankJump(ctx); + case EditableRegionStrategy.Static: + return await staticJump(ctx); + default: + return null; + } +} + +// Naive assumes that the entire file is editable. +// This relies on the next edit model to figure out where to jump next. +function naiveJump(ctx: any): RangeInFile[] | null { + const { fileLines, filepath } = ctx; + if (!fileLines || !filepath) { + console.warn("Missing required context for naive jump"); + return null; + } + + return [ + { + filepath, + range: { + start: { line: 0, character: 0 }, + end: { + line: fileLines.length - 1, + character: fileLines.at(-1).length, + }, + }, + }, + ]; +} + +// A rerank jump splits the current file into chunks. +// Then it uses a rerank model to get the most relevant chunks and their positions. +async function rerankJump(ctx: { + fileContent: string; + query: string; + filepath: string; + reranker: ILLM; + chunkSize: number; +}): Promise { + try { + const { fileContent, query, filepath, reranker, chunkSize = 5 } = ctx; + + if (!fileContent || !query || !filepath || !reranker) { + console.warn( + "Missing required context for rerank jump:", + !fileContent, + !query, + !filepath, + !reranker, + ); + return null; + } + + const lines = fileContent.split("\n"); + const chunks: Chunk[] = []; + + // Create chunks from the file. + for (let i = 0; i < lines.length; i += Math.floor(chunkSize / 2)) { + const endLine = Math.min(i + chunkSize - 1, lines.length - 1); + const chunkContent = lines.slice(i, endLine + 1).join("\n"); + if (chunkContent === "") continue; // Voyager throws an error if there are empty strings in its document field in the body. + chunks.push({ + content: chunkContent, + startLine: i, + endLine: endLine, + digest: `chunk-${i}-${endLine}`, + filepath: filepath, + index: i, + }); + } + + // Use the reranker to score each chunk against the query. + const scores = await reranker.rerank(query, chunks); + + // Sort by score in descending order and get the highest scoring chunk. + chunks.sort( + (a, b) => scores[chunks.indexOf(b)] - scores[chunks.indexOf(a)], + ); + + // const mostRelevantChunk = chunks[0]; + // Get the third most relevant chunk if there are enough chunks, + // otherwise fallback to second or first. + // The most relevant chunk seems to be the one that + // is similar enough lexically, + // but different enough to still justify making an edit. + const chunkIndex = Math.min(2, chunks.length - 1); + const mostRelevantChunk = chunks[chunkIndex]; + + // Return the range of the most relevant chunk. + // NOTE: It might be better to return a list of chunks, + // because it's very difficult to gauge when to stop the model. + // We could argue that we should always try to jump until the user says no. + return [ + { + filepath, + range: { + start: { line: mostRelevantChunk.startLine, character: 0 }, + end: { + line: mostRelevantChunk.endLine, + character: lines[mostRelevantChunk.endLine].length, + }, + }, + }, + ]; + } catch (error) { + console.error("Error in rerank jump:", error); + return null; + } +} + +// A static rerank jump runs a lightweight static analysis on the file +// and uses the reranker to jump to relevant locations. +async function staticRerankJump(ctx: { + oldFileContent: string; + newFileContent: string; + completionRange: Range; + filepath: string; + ide: IDE; + reranker?: ILLM; + chunkSize?: number; +}): Promise { + try { + const { oldFileContent, newFileContent, completionRange, filepath, ide } = + ctx; + + if ( + !oldFileContent || + !newFileContent || + !completionRange || + !filepath || + !ide + ) { + console.warn( + "Missing required context for static rerank jump:", + !oldFileContent, + !newFileContent, + !completionRange, + !filepath, + !ide, + ); + return null; + } + + // TODO: + // Parse the old file contents into an AST. + // Parse the new file contents into an AST. + // Compare the two trees and find which nodes have changed. + // Save the queue of changed nodes. The queue should contain the old node and the new node. Each of them can be null if the change is a deletion or insertion. + // Rank the queue by node depth (decreasing order because we want granular edits). + // Pop front until we find a queue item with an old node != null. + // Search the codebase for the old node's expression. For this, either use ide.getReferences(some_location), or other methods you see fit. If you can utilize the strategy pattern, even better. + // For now, filter out results from outside files. We only want to keep the results in the current file. + // Return the first result from this filtered list of results. + + // Parse the old file contents into an AST. + const oldAst = await getAst(filepath, oldFileContent); + if (!oldAst) return null; + + // Parse the new file contents into an AST. + const newAst = await getAst(filepath, newFileContent); + if (!newAst) return null; + + // Compare the two trees and find which nodes have changed. + const changedNodes = compareAsts(oldAst, newAst); + if (!changedNodes || changedNodes.length === 0) return null; + + // Save the queue of changed nodes. + // The queue should contain the old node and the new node. + // Each can be null if the change is a deletion or insertion. + // const nodeQueue = changedNodes.map((change) => ({ + // oldNode: change.oldNode, + // newNode: change.newNode, + // depth: change.depth, + // })); + + // Rank the queue by node depth. + // Decreasing order for granular edits. + // Increasing order for larger definition-based searches. + // Making it decreasing has issues when the deepest node is a string_fragment. + const nodeQueue = changedNodes.sort((a, b) => a.depth - b.depth); + console.log( + "nodeQueue:", + nodeQueue.map((node) => ({ + oldText: node.oldNode?.text || "", + newText: node.newNode?.text || "", + oldType: node.oldNode?.type || "", + newType: node.newNode?.type || "", + depth: node.depth, + })), + ); + + // Find the first item with a non-null old node. + let targetNode = null; + while (nodeQueue.length > 0 && !targetNode) { + const candidate = nodeQueue.shift(); + if ( + candidate && + candidate.oldNode && + candidate.oldNode.type !== "program" + ) { + targetNode = candidate.oldNode; + } + } + + if (!targetNode) return null; + + // Get the text representation of the old node's expression. + const nodeText = getNodeText(targetNode); + if (!nodeText || nodeText.trim() === "") return null; + + // Search for similar code in the file. + let references: RangeInFile[] = []; + + // Try to use IDE's reference finding capabilities if available. + try { + // Get the position of the target node in the old file. + const nodePosition = getNodePosition(targetNode); + if (nodePosition) { + // Use IDE to find references. + + // TODO: + // Get the list of document symbols using await ide.getDocumentSymbols. + // Each document symbol will be our query. + // Use the rerank model to rank the nodeText against the query. + // Get the highest scoring query and its location. + + // Get the list of document symbols using await ide.getDocumentSymbols. + // Filter out symbols that are directly inside the completion range. + const symbols = await ide.getDocumentSymbols(filepath); + + // Filter out symbols that are directly inside the completion range + const filteredSymbols = symbols.filter((symbol) => { + // Check if the symbol's range is outside of the completion range + return !doRangesOverlap(symbol.range, completionRange); + }); + + // Use the reranker to rank the filtered symbols against the node text. + if (!ctx.reranker) { + console.warn("No reranker available for static jump symbol ranking"); + return null; + } + + const symbolChunks: Chunk[] = filteredSymbols.map((symbol) => ({ + content: symbol.name, + startLine: symbol.range.start.line, + endLine: symbol.range.end.line, + digest: `symbol-${symbol.name}-${symbol.range.start.line}`, + filepath: filepath, + index: symbol.range.start.line, + })); + + if (symbolChunks.length === 0) { + console.warn("No symbols found for ranking"); + return null; + } + + const scores = await ctx.reranker.rerank(nodeText, symbolChunks); + symbolChunks.sort( + (a, b) => + scores[symbolChunks.indexOf(b)] - scores[symbolChunks.indexOf(a)], + ); + + const mostRelevantSymbol = symbolChunks[0]; + const originalSymbol = filteredSymbols.find( + (symbol) => + symbol.range.start.line === mostRelevantSymbol.startLine && + symbol.range.end.line === mostRelevantSymbol.endLine, + ); + + if (originalSymbol) { + references = [ + { + filepath, + range: originalSymbol.range, + }, + ]; + } + + // const foundReferences = await ide.getReferences({ + // filepath, + // position: nodePosition, + // }); + + // if (foundReferences && foundReferences.length > 0) { + // references = foundReferences; + // } + } + } catch (e) { + console.warn( + "Failed to use IDE references, falling back to text search:", + e, + ); + } + + // If IDE reference finding failed or returned no results, fall back to text search. + if (references.length === 0) { + references = findTextOccurrences(oldFileContent, nodeText).map( + (range) => ({ filepath, range }), + ); + } + + // Filter out results from outside the current file. + const currentFileReferences = references.filter( + (ref) => ref.filepath === filepath, + ); + + // Return the first reference if any found. + if (currentFileReferences.length > 0) { + return [currentFileReferences[0]]; + // return currentFileReferences; + } + + return null; + } catch (error) { + console.error("Error in static jump:", error); + return null; + } +} + +// Static jump relies purely on static analysis +// to determine where to edit next. +async function staticJump(ctx: { + cursorPosition: { line: number; character: number }; + filepath: string; + ide: IDE; +}): Promise { + try { + const { cursorPosition, filepath, ide } = ctx; + if (!cursorPosition || !filepath || !ide) { + console.warn( + "Missing required context for static jump:", + !cursorPosition, + !filepath, + !ide, + ); + return null; + } + + // Get the file's AST. + // Getting this once helps us live-track the current node. + const tree = + await DocumentHistoryTracker.getInstance().getMostRecentAst(filepath); + // const tree = await getAst(filepath, fileContent); + if (!tree) return null; + + // Convert cursor position to tree-sitter point format (0-based). + const point = { + row: cursorPosition.line, + column: cursorPosition.character, + }; + + // Find the node at the cursor position. + const nodeAtCursor = tree.rootNode.descendantForPosition(point); + if (!nodeAtCursor) { + console.log("No node found at cursor position"); + return null; + } + + // Find the closest identifier node. + const identifierNode = findClosestIdentifierNode(nodeAtCursor); + if (!identifierNode) { + console.log("No identifier node found near cursor position"); + return null; + } + console.log("closest identifier:", identifierNode.text); + + // Get all references to this identifier using the IDE's API + const references = await ide.getReferences({ + filepath, + position: { + line: identifierNode.startPosition.row, + character: identifierNode.startPosition.column, + }, + }); + + if (!references || references.length === 0) { + console.log(`No references found for identifier: ${identifierNode.text}`); + return null; + } + + console.log( + "references:", + JSON.stringify( + references.map((ref) => ({ + line: ref.range.start.line, + character: ref.range.start.character, + })), + null, + 2, + ), + ); + + return references.length > 1 ? references.slice(1) : null; + } catch (error) { + console.error("Error in staticJump:", error); + return null; + } +} + +/* AST HELPER FUNCTIONS */ + +// Helper function to find the closest identifier node. +function findClosestIdentifierNode( + node: Parser.SyntaxNode | null, +): Parser.SyntaxNode | null { + if (!node) return null; + + if (isIdentifierNode(node)) return node; + if (isDeclarationNode(node)) return findLeftmostIdentifier(node); + + // Check if the parent is an identifier. + // NOTE: This will probably never get triggered. + // Most identifiers are leaf nodes. + const parent = node.parent; + if (parent && isIdentifierNode(parent)) { + return parent; + } + + if (parent) { + if (isDeclarationNode(parent)) return findLeftmostIdentifier(parent); + + // Check if one of the siblings is an identifier. + for (let i = 0; i < parent.childCount; ++i) { + // const sibling = node.child(i); + const sibling = parent.child(i); + if (sibling && isIdentifierNode(sibling)) { + // Get the leftmost identifier sibling. + return sibling; + } + } + } + + return findClosestIdentifierNode(parent); +} + +function findLeftmostIdentifier( + node: Parser.SyntaxNode, +): Parser.SyntaxNode | null { + if (isIdentifierNode(node)) return node; + + for (let i = 0; i < node.childCount; ++i) { + const child = node.child(i); + if (child) { + const result = findLeftmostIdentifier(child); + if (result) return result; + } + } + + return null; +} + +// Helper function to check if a node is an identifier. +function isIdentifierNode(node: Parser.SyntaxNode) { + const nodeType = node.type; + + if (nodeType === "identifier") return true; + if (nodeType.includes("identifier")) return true; + + // Most language grammars will use the term "identifier". + // However some might not. + // Update this as they come. + const specialIdentifiers = ["name", "constant"]; + return specialIdentifiers.includes(nodeType); +} + +// Helper function to check if a node is a declaration. +function isDeclarationNode(node: Parser.SyntaxNode) { + const nodeType = node.type; + + // Common declaration patterns. + if (nodeType.endsWith("_declaration")) return true; + if (nodeType.endsWith("_definition")) return true; + if (nodeType.endsWith("_item")) return true; // Rust. + + // Language-specific patterns. + const declarationTypes = [ + // Python. + "function_definition", + "class_definition", + "async_function_definition", + "decorated_definition", + + // Ruby. + "method", + "class", + "module", + "singleton_method", + + // Java. + "variable_declarator", + "local_variable_declaration", + + // Go. + "short_var_declaration", + + // General + "method_definition", + ]; + + return declarationTypes.includes(nodeType); +} + +// // Helper function to find the closest identifier node. +// function findClosestIdentifierNode( +// node: Parser.SyntaxNode | undefined, +// ): Parser.SyntaxNode | undefined { +// if (!node) return undefined; + +// // Check if the current node is an identifier +// if (isIdentifierLike(node)) { +// return node; +// } + +// // Check if the parent is an identifier +// const parent = node.parent; +// if (parent && isIdentifierLike(parent)) { +// return parent; +// } + +// // Check if any of the node's children are identifiers +// // Return the leftmost identifier child if found +// for (let i = 0; i < node.childCount; i++) { +// const child = node.child(i); +// if (child && isIdentifierLike(child)) { +// return child; +// } +// } + +// // Check if any of the parent's children are identifiers +// if (parent) { +// for (let i = 0; i < parent.childCount; i++) { +// const sibling = parent.child(i); +// if (sibling && isIdentifierLike(sibling)) { +// return sibling; +// } +// } +// } + +// // Recurse on the parent if we haven't found anything yet +// return findClosestIdentifierNode(parent); +// } + +// // Helper function to determine if a node is identifier-like +// function isIdentifierLike(node: Parser.SyntaxNode): boolean { +// // Common identifier node types across languages +// const commonIdentifierTypes = [ +// "identifier", +// "property_identifier", +// "type_identifier", +// "field_identifier", +// "variable_identifier", +// "constant", +// "symbol", +// ]; + +// if (commonIdentifierTypes.includes(node.type)) { +// return true; +// } + +// // Check for common identifier patterns in node types +// return /identifier$|^identifier|_identifier/.test(node.type); +// } + +// Helper function to compare ASTs and find changed nodes. +function compareAsts(oldAst: Parser.Tree, newAst: Parser.Tree) { + const changedNodes: { + oldNode: Parser.SyntaxNode | null; + newNode: Parser.SyntaxNode | null; + depth: number; + }[] = []; + + // This is a simplified implementation. + // In practice, you would traverse both ASTs in parallel + // and identify nodes that differ. + + function traverse( + oldNode: Parser.SyntaxNode | null, + newNode: Parser.SyntaxNode | null, + depth: number = 0, + ) { + if (!oldNode && !newNode) return; + + // If one node exists and the other doesn't, or they're different types. + if ( + (!oldNode && newNode) || + (oldNode && !newNode) || + oldNode?.type !== newNode?.type + ) { + changedNodes.push({ oldNode, newNode, depth }); + return; + } + + // Compare properties. + if (oldNode?.text !== newNode?.text) { + changedNodes.push({ oldNode, newNode, depth }); + } + + // Recursively compare children. + const oldChildCount = oldNode?.childCount || 0; + const newChildCount = newNode?.childCount || 0; + + const maxLength = Math.max(oldChildCount, newChildCount); + for (let i = 0; i < maxLength; i++) { + const oldChild = i < oldChildCount ? oldNode?.child(i) || null : null; + const newChild = i < newChildCount ? newNode?.child(i) || null : null; + traverse(oldChild, newChild, depth + 1); + } + } + + traverse(oldAst.rootNode, newAst.rootNode); + return changedNodes; +} + +// Helper function to get a node's text. +function getNodeText(node: Parser.SyntaxNode): string { + if (!node) return ""; + + return node.text; +} + +// Helper function to get a node's position. +function getNodePosition(node: Parser.SyntaxNode): Position | null { + if (!node) return null; + + // Tree-sitter nodes have startPosition property that contains row and column. + return { + line: node.startPosition.row, + character: node.startPosition.column, + }; +} + +/* OTHER HELPER FUNCTIONS */ + +// Helper function to find all occurrences of text in a string. +function findTextOccurrences(text: string, searchText: string): Range[] { + const results: Range[] = []; + const lines = text.split("\n"); + + for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { + const line = lines[lineIndex]; + let charIndex = 0; + + while (charIndex < line.length) { + const foundIndex = line.indexOf(searchText, charIndex); + if (foundIndex === -1) break; + + results.push({ + start: { line: lineIndex, character: foundIndex }, + end: { line: lineIndex, character: foundIndex + searchText.length }, + }); + + charIndex = foundIndex + 1; + } + } + + return results; +} + +// Helper function to check if a range is within another range. +function isRangeWithin(innerRange: Range, outerRange: Range): boolean { + // Check if the inner range's start position is after or equal to the outer range's start. + const startWithin = + innerRange.start.line > outerRange.start.line || + (innerRange.start.line === outerRange.start.line && + innerRange.start.character >= outerRange.start.character); + + // Check if the inner range's end position is before or equal to the outer range's end. + const endWithin = + innerRange.end.line < outerRange.end.line || + (innerRange.end.line === outerRange.end.line && + innerRange.end.character <= outerRange.end.character); + + return startWithin && endWithin; +} + +// Helper function to check if two ranges overlap. +function doRangesOverlap(range1: Range, range2: Range): boolean { + // Check if one range starts after the other ends + const range1StartsAfterRange2Ends = + range1.start.line > range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character > range2.end.character); + + const range2StartsAfterRange1Ends = + range2.start.line > range1.end.line || + (range2.start.line === range1.end.line && + range2.start.character > range1.end.character); + + // If either condition is true, the ranges don't overlap + return !(range1StartsAfterRange2Ends || range2StartsAfterRange1Ends); +} + +// Helper function to check if the upper part of range1 overlaps with range2. +function doesUpperPartOverlap(range1: Range, range2: Range): boolean { + // Check if range1 starts before range2 ends + const range1StartsBeforeRange2Ends = + range1.start.line < range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character <= range2.end.character); + + // Check if range1 starts before range2 starts (meaning it's "upper" than range2) + const range1StartsBeforeRange2Starts = + range1.start.line < range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character < range2.start.character); + + // The upper part overlaps if range1 starts before range2 ends + // AND range1 starts before range2 starts + return range1StartsBeforeRange2Ends && range1StartsBeforeRange2Starts; +} + +// Helper function to check if the lower part of range1 overlaps with range2. +function doesLowerPartOverlap(range1: Range, range2: Range): boolean { + // Check if range1 starts inside range2 + const range1StartsInsideRange2 = + (range1.start.line > range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character >= range2.start.character)) && + (range1.start.line < range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character < range2.end.character)); + + // Check if range1 ends after range2 ends + const range1EndsAfterRange2 = + range1.end.line > range2.end.line || + (range1.end.line === range2.end.line && + range1.end.character > range2.end.character); + + // The lower part overlaps if range1 starts inside range2 + // AND range1 ends after range2 ends + return range1StartsInsideRange2 && range1EndsAfterRange2; +} + +// Helper function to check if a range overlaps with another range from either end +function doesRangePartiallyOverlap(range1: Range, range2: Range): boolean { + // Upper part overlap: range1 starts before range2 starts but ends inside range2 + const upperPartOverlap = + (range1.start.line < range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character < range2.start.character)) && + (range1.end.line > range2.start.line || + (range1.end.line === range2.start.line && + range1.end.character > range2.start.character)) && + (range1.end.line < range2.end.line || + (range1.end.line === range2.end.line && + range1.end.character <= range2.end.character)); + + // Lower part overlap: range1 starts inside range2 but ends after range2 ends + const lowerPartOverlap = + (range1.start.line > range2.start.line || + (range1.start.line === range2.start.line && + range1.start.character >= range2.start.character)) && + (range1.start.line < range2.end.line || + (range1.start.line === range2.end.line && + range1.start.character < range2.end.character)) && + (range1.end.line > range2.end.line || + (range1.end.line === range2.end.line && + range1.end.character > range2.end.character)); + + return upperPartOverlap || lowerPartOverlap; +} + +// Utility function to print chunks. +function printChunks(chunks: Chunk[]) { + console.log( + "chunks:", + JSON.stringify( + chunks.map((chunk) => ({ + content: chunk.content, + startLine: chunk.startLine, + endLine: chunk.endLine, + })), + null, + 2, + ), + ); +} diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 0f0d6ff48..a001df3b0 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -1,6 +1,7 @@ import * as path from "path"; +import { v4 as uuidv4 } from "uuid"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { ChatMessage, IDE, ILLM } from "../index.js"; +import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; @@ -10,24 +11,38 @@ import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchin import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js"; +import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js"; import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; +import { getAst } from "../autocomplete/util/ast.js"; import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js"; import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; +import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; +import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; +import { calculateFinalCursorPosition } from "./diff/diff.js"; +import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; +import { + EditableRegionStrategy, + getNextEditableRegion, +} from "./NextEditEditableRegionCalculator.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; import { renderDefaultSystemPrompt, renderDefaultUserPrompt, renderPrompt, } from "./templating/NextEditPromptEngine.js"; -import { NextEditOutcome, Prompt, PromptMetadata } from "./types.js"; -// import { renderPrompt } from "./templating/NextEditPromptEngine.js"; +import { + NextEditOutcome, + Prompt, + PromptMetadata, + RecentlyEditedRange, +} from "./types.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -52,6 +67,10 @@ export class NextEditProvider { private endpointType: "default" | "fineTuned"; private diffContext: string = ""; private promptMetadata: PromptMetadata | null = null; + private currentEditChainId: string | null = null; + private previousRequest: AutocompleteInput | null = null; + private previousCompletions: NextEditOutcome[] = []; + private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; private constructor( private readonly configHandler: ConfigHandler, @@ -185,11 +204,55 @@ export class NextEditProvider { return options; } + public chainExists(): boolean { + return this.currentEditChainId !== null; + } + + public getPreviousCompletion(): NextEditOutcome | null { + return this.previousCompletions[0]; + } + + public async deleteChain(): Promise { + this.currentEditChainId = null; + this.previousCompletions = []; + this.nextEditableRegionsInTheCurrentChain = []; + + if (this.previousRequest) { + const fileContent = ( + await this.ide.readFile(this.previousRequest.filepath) + ).toString(); + const ast = await getAst(this.previousRequest.filepath, fileContent); + if (ast) { + DocumentHistoryTracker.getInstance().push( + localPathOrUriToPath(this.previousRequest.filepath), + fileContent, + ast, + ); + } + } + } + + public startChain(id?: string) { + this.currentEditChainId = id ?? uuidv4(); + } + + public getChain() { + return this.previousCompletions; + } + + public isStartOfChain() { + return this.previousCompletions.length === 1; + } + public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, + opts?: { + withChain: boolean; + }, ): Promise { try { + this.previousRequest = input; // Create abort signal if not given if (!token) { const controller = this.loggingService.createAbortController( @@ -205,6 +268,14 @@ export class NextEditProvider { return undefined; } + // Depending on whether this method is called from provideInlineCompletionItemsWithChain, + // shift the next editable regions. + // This is handled here because this must run after the debouncer + // to prevent excessive shifts. + if (opts?.withChain) { + this.shiftNextEditableRegionsInTheCurrentChain(); + } + const llm = await this._prepareLlm(); if (!llm) { return undefined; @@ -237,17 +308,68 @@ export class NextEditProvider { // TODO: Toggle between the default endpoint and the finetuned endpoint. const prompts: Prompt[] = []; + if (this.endpointType === "default") { prompts.push(renderDefaultSystemPrompt()); prompts.push(renderDefaultUserPrompt(snippetPayload, helper)); } else { - const promptMetadata = renderPrompt(helper, this.diffContext); + const historyDiff = createDiff({ + beforeContent: + DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory( + localPathOrUriToPath(helper.filepath), + ) ?? "", + afterContent: helper.fileContents, + filePath: helper.filepath, + diffType: DiffFormatType.Unified, + contextLines: 3, + }); + + const promptMetadata = await renderPrompt( + helper, + historyDiff ?? this.diffContext, + ); + this.promptMetadata = promptMetadata; + + prompts.push({ + role: "system", + content: [ + "When the user deletes or replaces over previous code, you should respect that decision.", + "Respect the new code the user is writing, and complete it.", + "For example, if the user is changing a field name, try to autocomplete the new field name. Don't suggest the previous field name.", + "Do not roll back to previous content.", + "If the user has made a change, make sure you respect that and try to apply it to other parts of the code that used to use the old content.", + ].join("\n"), + }); + prompts.push(promptMetadata.prompt); } + const editableRegionStartLine = Math.max( + helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + + const editableRegionEndLine = Math.min( + helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + helper.fileLines.length - 1, + ); + + const oldEditRangeSlice = helper.fileContents + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + const finalCursorPos = calculateFinalCursorPosition( + helper.pos, + editableRegionStartLine, + oldEditRangeSlice, + "", + ); + if (this.endpointType === "default") { const msg: ChatMessage = await llm.chat(prompts, token); + if (typeof msg.content === "string") { const nextCompletion = JSON.parse(msg.content).newCode; const outcomeNext: NextEditOutcome = { @@ -255,7 +377,6 @@ export class NextEditProvider { modelProvider: llm.underlyingProviderName, modelName: llm.model + ":zetaDataset", completionOptions: null, - // filepath: helper.filepath, completionId: helper.input.completionId, gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), @@ -269,6 +390,9 @@ export class NextEditProvider { originalEditableRange: "", completion: nextCompletion, cursorPosition: helper.pos, + finalCursorPosition: finalCursorPos, + editableRegionStartLine: 0, + editableRegionEndLine: 0, ...helper.options, }; @@ -297,25 +421,34 @@ export class NextEditProvider { : ""; const currCursorPos = helper.pos; + const editableRegionStartLine = Math.max( currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0, ); + const editableRegionEndLine = Math.min( currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, helper.fileLines.length - 1, ); + const oldEditRangeSlice = helper.fileContents .split("\n") .slice(editableRegionStartLine, editableRegionEndLine + 1) .join("\n"); + const finalCursorPos = calculateFinalCursorPosition( + helper.pos, + editableRegionStartLine, + oldEditRangeSlice, + nextCompletion, + ); + const outcomeNext: NextEditOutcome = { elapsed: Date.now() - startTime, modelProvider: llm.underlyingProviderName, modelName: llm.model + ":zetaDataset", completionOptions: null, - // filepath: helper.filepath, completionId: helper.input.completionId, gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), @@ -329,9 +462,14 @@ export class NextEditProvider { originalEditableRange: oldEditRangeSlice, completion: nextCompletion, cursorPosition: helper.pos, + finalCursorPosition: finalCursorPos, + editableRegionStartLine, + editableRegionEndLine, ...helper.options, }; + this.previousCompletions.push(outcomeNext); + // When using the JetBrains extension, mark as displayed. // This helps us not need to make additional network calls just to mark as displayed. const ideType = (await this.ide.getIdeInfo()).ideType; @@ -350,4 +488,97 @@ export class NextEditProvider { this.loggingService.deleteAbortController(input.completionId); } } + + public async provideInlineCompletionItemsWithChain( + ctx: { + completionId: string; + manuallyPassFileContents?: string; + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + isUntitledFile: boolean; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + }, + token: AbortSignal | undefined, + ) { + try { + const previousOutcome = this.getPreviousCompletion(); + if (!previousOutcome) { + return undefined; + } + + const filepath = localPathOrUriToPath(previousOutcome.fileUri); + + // If we don't have a precomputed list of next editable regions already, compute and load it. + if (this.nextEditableRegionsInTheCurrentChain.length === 0) { + this.loadNextEditableRegionsInTheCurrentChain( + (await getNextEditableRegion(EditableRegionStrategy.Static, { + cursorPosition: previousOutcome.cursorPosition, + filepath, + ide: this.ide, + })) ?? [], + ); + + if (this.nextEditableRegionsInTheCurrentChain.length === 0) { + await this.deleteChain(); + return undefined; + } + } + + // Use the frontmost RangeInFile to build an input. + const input = await this.buildAutocompleteInputFromChain( + previousOutcome, + this.nextEditableRegionsInTheCurrentChain[0], // this will be shifted after debouncer check + ctx, + ); + if (!input) { + return undefined; + } + + return await this.provideInlineCompletionItems(input, token, { + withChain: true, + }); + } catch (e: any) { + this.onError(e); + } + } + + private buildAutocompleteInputFromChain( + previousOutcome: NextEditOutcome, + nextEditableRegion: RangeInFile, + ctx: { + completionId: string; + manuallyPassFileContents?: string; + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + isUntitledFile: boolean; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; + recentlyEditedRanges: RecentlyEditedRange[]; + }, + ): AutocompleteInput | undefined { + const input: AutocompleteInput = { + pos: { + line: nextEditableRegion.range.start.line, + character: nextEditableRegion.range.start.character, + }, + filepath: previousOutcome.fileUri, + ...ctx, + }; + + return input; + } + + public loadNextEditableRegionsInTheCurrentChain(regions: RangeInFile[]) { + this.nextEditableRegionsInTheCurrentChain = regions; + } + + public shiftNextEditableRegionsInTheCurrentChain() { + this.nextEditableRegionsInTheCurrentChain.shift(); + } } diff --git a/core/nextEdit/diff/diff.ts b/core/nextEdit/diff/diff.ts index bca4a6d08..fdcb78fb4 100644 --- a/core/nextEdit/diff/diff.ts +++ b/core/nextEdit/diff/diff.ts @@ -1,4 +1,6 @@ +import { Position } from "shiki"; import { DiffLine } from "../.."; +import { myersDiff } from "../../diff/myers"; /** * Given a diff of two editable regions, get the offset position at the last new line inside the editable region. @@ -134,6 +136,8 @@ export function checkFim( isFim: false; fimText: null; } { + // console.log("oldEditRange", oldEditRange); + // console.log("newEditRange", newEditRange); // Find the common prefix. let prefixLength = 0; while ( @@ -168,12 +172,19 @@ export function checkFim( // Convert cursor position to an offset in the string. // For simplicity, we need to calculate the cursor's position in the string. // This requires knowledge of line endings in the oldEditRange. - const lines = oldEditRange.substring(0, prefixLength).split("\n"); + // const lines = oldEditRange.substring(0, prefixLength).split("\n"); + // const lines = oldEditRange.split("\n"); + // const cursorOffset = + // lines.length > 1 + // ? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) + + // cursorPosition.character + // : cursorPosition.character; + const oldEditLines = oldEditRange.split("\n"); const cursorOffset = - lines.length > 1 - ? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) + - cursorPosition.character - : cursorPosition.character; + oldEditLines + .slice(0, cursorPosition.line) + .reduce((sum, line) => sum + line.length + 1, 0) + + cursorPosition.character; // Check if the cursor is positioned between the prefix and suffix. const cursorBetweenPrefixAndSuffix = @@ -192,3 +203,66 @@ export function checkFim( return { isFim, fimText: null }; } } + +export function calculateFinalCursorPosition( + currCursorPos: Position, + editableRegionStartLine: number, + oldEditRangeSlice: string, + newEditRangeSlice: string, +) { + // How far away is the current line from the start of the editable region? + const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine; + + // How long is the line at the current cursor position? + const lineContentAtCursorPos = + newEditRangeSlice.split("\n")[lineOffsetAtCursorPos]; + + const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + + const offset = getOffsetPositionAtLastNewLine( + diffLines, + lineContentAtCursorPos, + lineOffsetAtCursorPos, + ); + + // Calculate the actual line number in the editor by adding the startPos offset + // to the line number from the diff calculation. + const finalCursorPos: Position = { + line: editableRegionStartLine + offset.line, + character: offset.character, + }; + + return finalCursorPos; +} + +/** + * Applies a completion to file content by replacing lines starting from a specific line number + * + * @param fileContent The original file content + * @param completion The completion text to apply + * @param startLineNumber The line number (0-based) where replacement should start + * @param linesToReplace Optional number of lines to replace; if not provided, will replace the same number of lines as in the completion + * @returns The file content with the completion applied + */ +export function applyCompletionToFile( + fileContent: string, + completion: string, + startLineNumber: number, + linesToReplace?: number, +): string { + const lines = fileContent.split("\n"); + const completionLines = completion.split("\n"); + + // Determine how many lines to replace + const numLinesToReplace = + linesToReplace !== undefined ? linesToReplace : completionLines.length; + + // Replace the lines + const newLines = [ + ...lines.slice(0, startLineNumber), + ...completionLines, + ...lines.slice(startLineNumber + numLinesToReplace), + ]; + + return newLines.join("\n"); +} diff --git a/core/nextEdit/diff/diff.vitest.ts b/core/nextEdit/diff/diff.vitest.ts index fa161d49c..706fed14c 100644 --- a/core/nextEdit/diff/diff.vitest.ts +++ b/core/nextEdit/diff/diff.vitest.ts @@ -79,6 +79,46 @@ describe("checkFim", () => { "const data = fetchData();\n const result = processData(data);", }, }, + { + name: "interesting case", + oldEditRange: [" }", "}", ""].join("\n"), + newEditRange: [" }", "}", "", "module.exports = Calculator;"].join("\n"), + cursorPosition: { line: 0, character: 0 }, + expected: { + isFim: false, + fimText: null, + }, + }, + { + name: "calculator.js divide", + oldEditRange: [ + " ", + " if (number === 0) {", + ' throw new Error("Cannot divide by zero");', + " }", + " this.result /= number;", + " return this;", + ].join("\n"), + newEditRange: [ + " if (typeof number !== 'number') {", + ' throw new Error("Invalid input: must be a number");', + " }", + " if (number === 0) {", + ' throw new Error("Cannot divide by zero");', + " }", + " this.result /= number;", + " return this;", + ].join("\n"), + cursorPosition: { line: 0, character: 4 }, + expected: { + isFim: true, + fimText: [ + "if (typeof number !== 'number') {", + ' throw new Error("Invalid input: must be a number");', + " }", + ].join("\n"), + }, + }, ]; testCases.forEach( diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 93f794a63..bad3f5166 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -46,10 +46,10 @@ function templateRendererOfModel( }; } -export function renderPrompt( +export async function renderPrompt( helper: HelperVars, userEdits: string, -): PromptMetadata { +): Promise { let modelName = helper.modelName as NextEditModelName; if (modelName === "this field is not used") { @@ -80,7 +80,9 @@ export function renderPrompt( } const renderer = templateRendererOfModel(modelName); - const editedCodeWithTokens = insertTokens( + let editedCodeWithTokens = ""; + + editedCodeWithTokens = insertTokens( helper.fileContents.split("\n"), helper.pos, ); @@ -264,9 +266,19 @@ export function renderDefaultUserPrompt( // } // } -function insertTokens(lines: string[], cursorPos: Position) { +function insertTokens( + lines: string[], + cursorPos: Position, + editableRegionStart?: number, + editableRegionEnd?: number, +) { const a = insertCursorToken(lines, cursorPos); - const b = insertEditableRegionTokensWithStaticRange(a, cursorPos); + const b = insertEditableRegionTokensWithStaticRange( + a, + cursorPos, + editableRegionStart, + editableRegionEnd, + ); return b.join("\n"); } @@ -290,20 +302,28 @@ function insertCursorToken(lines: string[], cursorPos: Position) { function insertEditableRegionTokensWithStaticRange( lines: string[], cursorPos: Position, + editableRegionStart?: number, + editableRegionEnd?: number, ) { if (cursorPos.line < 0 || cursorPos.line >= lines.length) { return lines; } // Ensure editable regions are within bounds. - const editableRegionStart = Math.max( - cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, - 0, - ); - const editableRegionEnd = Math.min( - cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, - lines.length - 1, // Line numbers should be zero-indexed. - ); + if (editableRegionStart === undefined) { + editableRegionStart = Math.max( + cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + } + if (editableRegionEnd === undefined) { + editableRegionEnd = Math.min( + cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + lines.length - 1, // Line numbers should be zero-indexed. + ); + } + + // console.log("editableRegionStart:", editableRegionStart); const instrumentedLines = [ ...lines.slice(0, editableRegionStart), diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index 0837c5494..26e2b156a 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -53,7 +53,10 @@ export interface NextEditOutcome extends TabAutocompleteOptions { originalEditableRange: string; completion: string; cursorPosition: { line: number; character: number }; + finalCursorPosition: { line: number; character: number }; accepted?: boolean; + editableRegionStartLine: number; + editableRegionEndLine: number; } export interface PromptMetadata { diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 590968f33..d8b86ff96 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -1,4 +1,5 @@ import type { + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -83,6 +84,8 @@ export type ToIdeFromWebviewOrCoreProtocol = { gotoDefinition: [{ location: Location }, RangeInFile[]]; gotoTypeDefinition: [{ location: Location }, RangeInFile[]]; getSignatureHelp: [{ location: Location }, SignatureHelp | null]; + getReferences: [{ location: Location }, RangeInFile[]]; + getDocumentSymbols: [{ textDocumentIdentifier: string }, DocumentSymbol[]]; getControlPlaneSessionInfo: [ { silent: boolean; useOnboarding: boolean }, diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 0c66fd51a..795b483c4 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -2,6 +2,7 @@ import { FromIdeProtocol } from ".."; import { ToIdeFromWebviewOrCoreProtocol } from "../ide"; import type { + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -53,6 +54,16 @@ export class MessageIde implements IDE { return this.request("getSignatureHelp", { location }); } + async getReferences(location: Location): Promise { + return this.request("getReferences", { location }); + } + + async getDocumentSymbols( + textDocumentIdentifier: string, + ): Promise { + return this.request("getDocumentSymbols", { textDocumentIdentifier }); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 44bbd4ca6..67a70374a 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -2,6 +2,7 @@ import * as fs from "node:fs"; import { fileURLToPath } from "node:url"; import { + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -52,6 +53,14 @@ class FileSystemIde implements IDE { return Promise.resolve(null); } + getReferences(location: Location): Promise { + return Promise.resolve([]); + } + + getDocumentSymbols(fileUri: string): Promise { + return Promise.resolve([]); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { return; } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 7d2507617..d377cb3b1 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -622,6 +622,14 @@ class IntelliJIDE( throw NotImplementedError("getSignatureHelp not implemented yet") } + override suspend fun getReferences(location: Location): List { + throw NotImplementedError("getReferences not implemented yet") + } + + override suspend fun getDocumentSymbols(textDocumentIdentifier: String): List { + throw NotImplementedError("getDocumentSymbols not implemented yet") + } + override fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) { throw NotImplementedError("onDidChangeActiveTextEditor not implemented yet") } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index b3718661f..cddcd035b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -121,6 +121,13 @@ data class ParameterInformation( val label: String // Note: Kotlin doesn't have union types, so this represents the string case ) +data class DocumentSymbol( + val name: String, + val kind: String, + val range: Range, + val selectionRange: Range +) + data class ControlPlaneSessionInfo( val accessToken: String, val account: Account @@ -250,6 +257,8 @@ interface IDE { suspend fun gotoDefinition(location: Location): List suspend fun gotoTypeDefinition(location: Location): List suspend fun getSignatureHelp(location: Location): SignatureHelp? + suspend fun getReferences(location: Location): List + suspend fun getDocumentSymbols(textDocumentIdentifier: String): List // Callbacks fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 726c49161..141b2effb 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -350,6 +350,16 @@ "category": "Continue", "title": "Continue: Force Next Edit" }, + { + "command": "continue.acceptJump", + "category": "Continue", + "title": "Continue: Accept Jump Suggestion" + }, + { + "command": "continue.rejectJump", + "category": "Continue", + "title": "Continue: Reject Jump Suggestion" + }, { "command": "continue.generateRule", "category": "Continue", @@ -451,12 +461,22 @@ { "command": "continue.nextEditWindow.hideNextEditSuggestion", "key": "escape", - "when": "editorTextFocus && nextEditWindowActive" + "when": "editorTextFocus && nextEditWindowActive && !continue.jumpDecorationVisible" }, { "command": "continue.nextEditWindow.acceptNextEditSuggestion", "key": "tab", - "when": "editorTextFocus && nextEditWindowActive" + "when": "editorTextFocus && nextEditWindowActive && !continue.jumpDecorationVisible" + }, + { + "command": "continue.acceptJump", + "key": "tab", + "when": "editorTextFocus && continue.jumpDecorationVisible" + }, + { + "command": "continue.rejectJump", + "key": "escape", + "when": "editorTextFocus && continue.jumpDecorationVisible" } ], "submenus": [ diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 089252ab5..bc1f8c2da 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -9,6 +9,7 @@ import * as vscode from "vscode"; import { executeGotoProvider, executeSignatureHelpProvider, + executeSymbolProvider, } from "./autocomplete/lsp"; import { Repository } from "./otherExtensions/git"; import { SecretStorage } from "./stubs/SecretStorage"; @@ -17,6 +18,7 @@ import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; import { VsCodeWebviewProtocol } from "./webviewProtocol"; import type { + DocumentSymbol, FileStatsMap, FileType, IDE, @@ -112,6 +114,28 @@ class VsCodeIde implements IDE { return result; } + async getReferences(location: Location): Promise { + const result = await executeGotoProvider({ + uri: vscode.Uri.parse(location.filepath), + line: location.position.line, + character: location.position.character, + name: "vscode.executeReferenceProvider", + }); + + return result; + } + + async getDocumentSymbols( + textDocumentIdentifier: string, // uri + ): Promise { + const result = await executeSymbolProvider({ + uri: vscode.Uri.parse(textDocumentIdentifier), + name: "vscode.executeDocumentSymbolProvider", + }); + + return result; + } + onDidChangeActiveTextEditor(callback: (uri: string) => void): void { vscode.window.onDidChangeActiveTextEditor((editor) => { if (editor) { diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts new file mode 100644 index 000000000..1d180c072 --- /dev/null +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -0,0 +1,318 @@ +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { NextEditOutcome } from "core/nextEdit/types"; +import * as vscode from "vscode"; + +export interface CompletionDataForAfterJump { + completionId: string; + outcome: NextEditOutcome; + currentPosition: vscode.Position; +} + +export class JumpManager { + private static _instance: JumpManager | undefined; + + // Decoration state. + private _jumpDecoration: vscode.TextEditorDecorationType | undefined; + private _jumpDecorationVisible = false; + private _disposables: vscode.Disposable[] = []; + + private _jumpInProgress: boolean = false; + private _completionAfterJump: CompletionDataForAfterJump | null = null; + private _oldCursorPosition: vscode.Position | undefined; + + private constructor() {} + + initialize() {} + + public static getInstance(): JumpManager { + if (!JumpManager._instance) { + JumpManager._instance = new JumpManager(); + } + return JumpManager._instance; + } + + public static clearInstance() { + if (JumpManager._instance) { + JumpManager._instance.dispose(); + JumpManager._instance = undefined; + } + } + + public dispose() { + // Dispose current decoration. + this._disposables.forEach((d) => d.dispose()); + this._disposables = []; + } + + public async suggestJump( + currentPosition: vscode.Position, + nextJumpLocation: vscode.Position, + completionContent?: string, + ) { + // Deduplication logic. + // If the content at the next jump location is + // identical to the completion content, + // then we don't have to jump. + if (completionContent !== undefined) { + const editor = vscode.window.activeTextEditor; + if (editor) { + try { + const completionLines = completionContent.split("\n"); + + // Get document content at jump location spanning multiple lines. + const document = editor.document; + const startLine = nextJumpLocation.line; + const endLine = Math.min( + startLine + completionLines.length - 1, + document.lineCount - 1, + ); + + // Check if we have enough lines in the document to compare. + if (endLine - startLine + 1 < completionLines.length) { + // Not enough lines in document, so content can't be identical. + // Proceed to jump! + } else { + // Check the first line first for early exit. + const firstLineText = document.lineAt(startLine).text; + const firstLineSubstring = firstLineText.substring( + nextJumpLocation.character, + ); + const firstCompletionLine = completionLines[0]; + + if (!firstLineSubstring.startsWith(firstCompletionLine)) { + // First line doesn't match, so proceed to jump. + } else { + // Check remaining lines if there are any. + if (completionLines.length > 1) { + let fullMatch = true; + + // Process remaining lines. + for (let i = 1; i < completionLines.length; i++) { + const documentLine = startLine + i; + if (documentLine <= endLine) { + const lineText = document.lineAt(documentLine).text; + if (lineText !== completionLines[i]) { + fullMatch = false; + break; + } + } + } + + if (fullMatch) { + console.log( + "Skipping jump as content is identical at jump location", + ); + return; // Exit early, don't suggest jump. + } + } else { + // Only one line and it matches. + console.log( + "Skipping jump as content is identical at jump location", + ); + return; // Exit early, don't suggest jump. + } + } + } + } catch (error) { + console.error("Error checking content at jump location:", error); + // Continue with jump even if there's an error checking content. + } + } + } + + this._jumpInProgress = true; + this._oldCursorPosition = currentPosition; + + const editor = vscode.window.activeTextEditor; + + if (editor) { + const visibleRanges = editor.visibleRanges; + + if (visibleRanges.length > 0) { + const visibleRange = visibleRanges[0]; + const topLineNumber = visibleRange.start.line; + const bottomLineNumber = visibleRange.end.line; + + const decorationLine = nextJumpLocation.line; + + // Check if jump location is outside the visible range. + if (decorationLine < topLineNumber) { + await this.renderTabToJumpDecoration( + editor, + topLineNumber, + nextJumpLocation, + ); + } else if (decorationLine > bottomLineNumber) { + await this.renderTabToJumpDecoration( + editor, + bottomLineNumber, + nextJumpLocation, + ); + } else { + // No suggestion is made when the decoration is within visibleRange. + await this.renderTabToJumpDecoration( + editor, + decorationLine, + nextJumpLocation, + ); + } + + // Scroll to show the jump location. + editor.revealRange( + new vscode.Range(decorationLine, 0, decorationLine, 0), + vscode.TextEditorRevealType.InCenter, + ); + } + } + + // Set up a way to detect when the jump is complete. + const disposable = vscode.window.onDidChangeTextEditorSelection(() => { + this._jumpInProgress = false; + disposable.dispose(); + + // If there's a completion waiting to be shown after the jump, + // execute the command to show it. + if (this._completionAfterJump) { + vscode.commands.executeCommand( + "continue.showNextEditAfterJump", + this._completionAfterJump, + ); + this._completionAfterJump = null; + } + }); + + // Clean up after timeout if no jump has been made. + setTimeout(() => { + this._jumpInProgress = false; + disposable.dispose(); + }, 5000); + } + + private async renderTabToJumpDecoration( + editor: vscode.TextEditor, + lineToRenderOn: number, + jumpPosition: vscode.Position, + ) { + // Clean up any existing decoration beforehand. + await this.clearJumpDecoration(); + + // Create a decoration for jump. + this._jumpDecoration = vscode.window.createTextEditorDecorationType({ + before: { + contentText: "🦘 Press Tab to jump, Esc to cancel", + color: new vscode.ThemeColor("editorInfo.foreground"), + backgroundColor: new vscode.ThemeColor("editorInfo.background"), + margin: `0 0 0 4px`, + }, + }); + + // Apply the decoration. + const lastIndexOfLine = editor.document.lineAt(lineToRenderOn).text.length; + editor.setDecorations(this._jumpDecoration, [ + new vscode.Range( + lineToRenderOn, + lastIndexOfLine, + lineToRenderOn, + lastIndexOfLine, + ), + ]); + + // Set the context key to enable tab/esc shortcuts. + await vscode.commands.executeCommand( + "setContext", + "continue.jumpDecorationVisible", + true, + ); + this._jumpDecorationVisible = true; + + // Register the key listeners. + await this.registerKeyListeners(editor, jumpPosition); + } + + private async clearJumpDecoration() { + if (this._jumpDecoration) { + this._jumpDecoration.dispose(); + this._jumpDecoration = undefined; + } + + // Dispose any active listeners. + this._disposables.forEach((d) => d.dispose()); + this._disposables = []; + + // Reset the context. + await vscode.commands.executeCommand( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + this._jumpDecorationVisible = false; + } + + private async registerKeyListeners( + editor: vscode.TextEditor, + jumpPosition: vscode.Position, + ) { + const acceptJumpCommand = vscode.commands.registerCommand( + "continue.acceptJump", + async () => { + if (this._jumpDecorationVisible) { + // Move cursor to the jump position. + editor.selection = new vscode.Selection(jumpPosition, jumpPosition); + await this.clearJumpDecoration(); + } + }, + ); + + const rejectJumpCommand = vscode.commands.registerCommand( + "continue.rejectJump", + async () => { + if (this._jumpDecorationVisible) { + console.log( + "deleteChain from JumpManager.ts: rejectJump and decoration visible", + ); + NextEditProvider.getInstance().deleteChain(); + await this.clearJumpDecoration(); + } + }, + ); + + // Add a selection change listener to the editor to reject jump when cursor moves. + const selectionChangeListener = + vscode.window.onDidChangeTextEditorSelection((e) => { + // If jump decoration isn't visible, nothing to do. + if (!this._jumpDecorationVisible) { + return; + } + + const currentPosition = e.selections[0].active; + + // If cursor moved to jump position, this is likely the result of acceptJump. + if (currentPosition.isEqual(jumpPosition)) { + return; + } + + // If cursor position changed for any other reason, reject the jump. + if ( + this._oldCursorPosition && + !currentPosition.isEqual(this._oldCursorPosition) + ) { + vscode.commands.executeCommand("continue.rejectJump"); + } + }); + + // This allows us to dispose the command after a jump is completed. + this._disposables.push( + acceptJumpCommand, + rejectJumpCommand, + selectionChangeListener, + ); + } + + isJumpInProgress(): boolean { + return this._jumpInProgress; + } + + setCompletionAfterJump(completionData: CompletionDataForAfterJump): void { + this._completionAfterJump = completionData; + } +} diff --git a/extensions/vscode/src/activation/JumpManager.vitest.ts b/extensions/vscode/src/activation/JumpManager.vitest.ts new file mode 100644 index 000000000..3a74f479b --- /dev/null +++ b/extensions/vscode/src/activation/JumpManager.vitest.ts @@ -0,0 +1,458 @@ +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { NextEditOutcome } from "core/nextEdit/types"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; +import { CompletionDataForAfterJump, JumpManager } from "./JumpManager"; + +// Mock VSCode API +vi.mock("vscode", () => { + return { + window: { + createTextEditorDecorationType: vi.fn(() => ({ + dispose: vi.fn(), + })), + activeTextEditor: { + document: { + lineAt: vi.fn((line) => ({ + text: "Test line content", + lineNumber: line, + })), + lineCount: 10, + }, + setDecorations: vi.fn(), + selection: { active: { line: 0, character: 0 } }, + revealRange: vi.fn(), + visibleRanges: [{ start: { line: 0 }, end: { line: 5 } }], + }, + onDidChangeTextEditorSelection: vi.fn(() => ({ + dispose: vi.fn(), + })), + }, + commands: { + executeCommand: vi.fn(), + registerCommand: vi.fn(() => ({ + dispose: vi.fn(), + })), + }, + Position: class { + line: number; + character: number; + constructor(line: number, character: number) { + this.line = line; + this.character = character; + } + isEqual(other: any): boolean { + return this.line === other.line && this.character === other.character; + } + }, + Range: class { + start: any; + end: any; + constructor( + startLine: number, + startChar: number, + endLine: number, + endChar: number, + ) { + this.start = { line: startLine, character: startChar }; + this.end = { line: endLine, character: endChar }; + } + }, + Selection: class { + anchor: any; + active: any; + constructor(anchor: any, active: any) { + this.anchor = anchor; + this.active = active; + } + }, + TextEditorDecorationType: class { + dispose: () => void; + constructor() { + this.dispose = vi.fn(); + } + }, + TextEditorRevealType: { + InCenter: "inCenter", + }, + ThemeColor: class { + id: string; + constructor(id: string) { + this.id = id; + } + }, + }; +}); + +// Mock NextEditProvider +vi.mock("core/nextEdit/NextEditProvider", () => { + const mockDeleteChain = vi.fn(); + const mockGetInstance = vi.fn(() => ({ + deleteChain: mockDeleteChain, + })); + + return { + NextEditProvider: { + getInstance: mockGetInstance, + }, + }; +}); + +const createMockNextEditOutcome = ( + overrides: Partial = {}, +): NextEditOutcome => { + return { + // TabAutocompleteOptions properties + disable: false, + maxPromptTokens: 2048, + debounceDelay: 300, + modelTimeout: 5000, + maxSuffixPercentage: 0.5, + prefixPercentage: 0.8, + transform: true, + template: "default", + multilineCompletions: "auto", + slidingWindowPrefixPercentage: 0.5, + slidingWindowSize: 100, + useCache: true, + onlyMyCode: false, + useRecentlyEdited: true, + useRecentlyOpened: true, + disableInFiles: [".env", "node_modules/**"], + useImports: true, + showWhateverWeHaveAtXMs: 2000, + experimental_includeClipboard: true, + experimental_includeRecentlyVisitedRanges: true, + experimental_includeRecentlyEditedRanges: true, + experimental_includeDiff: true, + experimental_enableStaticContextualization: false, + // Base properties + elapsed: 1500, + modelProvider: "openai", + modelName: "gpt-4", + completionOptions: { + temperature: 0.7, + max_tokens: 1000, + }, + completionId: "comp_12345abcde", + uniqueId: "ne_67890fghij", + timestamp: Date.now(), + gitRepo: "continuedev/continue", + + // NextEdit specific properties + fileUri: "file:///workspace/project/src/main.ts", + workspaceDirUri: "file:///workspace/project", + prompt: "Add error handling to this function", + userEdits: "// I added a try/catch block", + userExcerpts: "function example() { ... }", + originalEditableRange: "function example() {\n return fetch(url);\n}", + completion: + "function example() {\n try {\n return fetch(url);\n } catch (error) {\n console.error('Fetch failed:', error);\n throw error;\n }\n}", + cursorPosition: { line: 2, character: 10 }, + finalCursorPosition: { line: 4, character: 5 }, + accepted: true, + editableRegionStartLine: 1, + editableRegionEndLine: 3, + + // Apply any overrides + ...overrides, + }; +}; + +describe("JumpManager", () => { + let jumpManager: JumpManager; + + beforeEach(() => { + // Reset mocks + vi.resetAllMocks(); + + // Clear any existing instance + JumpManager.clearInstance(); + + // Get a fresh instance + jumpManager = JumpManager.getInstance(); + }); + + afterEach(() => { + jumpManager.dispose(); + }); + + describe("getInstance", () => { + it("should return the same instance on multiple calls", () => { + const instance1 = JumpManager.getInstance(); + const instance2 = JumpManager.getInstance(); + expect(instance1).toBe(instance2); + }); + }); + + describe("clearInstance", () => { + it("should dispose the current instance and clear it", () => { + const instance = JumpManager.getInstance(); + const disposeSpy = vi.spyOn(instance, "dispose"); + + JumpManager.clearInstance(); + + expect(disposeSpy).toHaveBeenCalled(); + + // Get a new instance + const newInstance = JumpManager.getInstance(); + expect(newInstance).not.toBe(instance); + }); + }); + + describe("suggestJump", () => { + it("should set jumpInProgress to true", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(3, 0); + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + expect(jumpManager.isJumpInProgress()).toBe(true); + }); + + it("should not suggest jump if completion content matches document content", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(3, 0); + const completionContent = "Test line content"; + + // Mock document content to match the completion content + vscode.window.activeTextEditor!.document.lineAt = vi.fn(() => ({ + text: "Test line content", + lineNumber: 3, + })) as any; + + await jumpManager.suggestJump( + currentPosition, + nextJumpLocation, + completionContent, + ); + + // Jump should not be suggested, so decorations should not be created + expect( + vscode.window.createTextEditorDecorationType, + ).not.toHaveBeenCalled(); + }); + + it("should render decoration for jump location outside visible range (below)", async () => { + const currentPosition = new vscode.Position(1, 0); + const nextJumpLocation = new vscode.Position(8, 0); // Outside visible range (below) + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + // Should create decoration + expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled(); + // Should set context + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + true, + ); + // Should register key listeners + expect(vscode.commands.registerCommand).toHaveBeenCalledWith( + "continue.acceptJump", + expect.any(Function), + ); + expect(vscode.commands.registerCommand).toHaveBeenCalledWith( + "continue.rejectJump", + expect.any(Function), + ); + }); + + it("should render decoration for jump location outside visible range (above)", async () => { + // Set visible range to be below the jump target + // @ts-ignore + vscode.window.activeTextEditor!.visibleRanges = [ + { start: { line: 5 }, end: { line: 10 } }, + ]; + + const currentPosition = new vscode.Position(6, 0); + const nextJumpLocation = new vscode.Position(2, 0); // Outside visible range (above) + + await jumpManager.suggestJump(currentPosition, nextJumpLocation); + + // Should create decoration + expect(vscode.window.createTextEditorDecorationType).toHaveBeenCalled(); + }); + }); + + describe("registerKeyListeners", () => { + it("should register acceptJump command that moves cursor", async () => { + // Setup private method access (this is a bit of a hack for testing private methods) + const privateJumpManager = jumpManager as any; + + // Mock context + privateJumpManager._jumpDecorationVisible = true; + + // Create editor mock + const editor = { + selection: null, + setSelection: vi.fn(), + }; + + // Create jump position + const jumpPosition = new vscode.Position(3, 5); + + // Call the private method + await privateJumpManager.registerKeyListeners(editor, jumpPosition); + + // Find the command handler + //@ts-ignore + const commandArgs = vscode.commands.registerCommand.mock.calls.find( + (call: any) => call[0] === "continue.acceptJump", + ); + const acceptJumpHandler = commandArgs[1]; + + // Call the handler + await acceptJumpHandler(); + + // Expect selection to be updated + expect(editor.selection).toEqual( + new vscode.Selection(jumpPosition, jumpPosition), + ); + // Expect decoration to be cleared + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + + it("should register rejectJump command that deletes the chain", async () => { + // Setup private method access + const privateJumpManager = jumpManager as any; + + // Mock context + privateJumpManager._jumpDecorationVisible = true; + + // Get a reference to the mocked deleteChain + const mockDeleteChain = vi.mocked( + NextEditProvider.getInstance().deleteChain, + ); + mockDeleteChain.mockClear(); + + // Call the private method + await privateJumpManager.registerKeyListeners( + {} as vscode.TextEditor, + new vscode.Position(0, 0), + ); + + // Find the command handler + //@ts-ignore + const commandArgs = vscode.commands.registerCommand.mock.calls.find( + (call: any) => call[0] === "continue.rejectJump", + ); + expect(commandArgs).toBeDefined(); + const rejectJumpHandler = commandArgs?.[1]; + expect(rejectJumpHandler).toBeDefined(); + + // Reset executeCommand mock + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Call the handler + await rejectJumpHandler(); + + // Debug: Log state after calling handler + console.log("mockDeleteChain called:", mockDeleteChain.mock.calls.length); + + // Expect NextEditProvider.deleteChain to be called + expect(mockDeleteChain).toHaveBeenCalled(); + + // Expect decoration to be cleared + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + }); + + describe("setCompletionAfterJump", () => { + it("should store completion data", () => { + const completionData: CompletionDataForAfterJump = { + completionId: "test-id", + outcome: createMockNextEditOutcome(), + currentPosition: new vscode.Position(1, 0), + }; + + // Set the completion data + jumpManager.setCompletionAfterJump(completionData); + + // Verify the completion data was stored correctly + expect((jumpManager as any)._completionAfterJump).toEqual(completionData); + }); + + it("should process completion data when jump is completed", async () => { + const completionData: CompletionDataForAfterJump = { + completionId: "test-id", + outcome: createMockNextEditOutcome(), + currentPosition: new vscode.Position(1, 0), + }; + + // Set the completion data + jumpManager.setCompletionAfterJump(completionData); + + // Verify the completion data was set correctly + expect((jumpManager as any)._completionAfterJump).toEqual(completionData); + + // Reset executeCommand mock to clear previous calls + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Directly simulate what happens when a jump is completed + // by manipulating the internal state + (jumpManager as any)._jumpInProgress = false; + + // Now directly call the method that would show the completion + // We need to manually implement what the callback would do + if ((jumpManager as any)._completionAfterJump) { + vscode.commands.executeCommand( + "continue.showNextEditAfterJump", + (jumpManager as any)._completionAfterJump, + ); + (jumpManager as any)._completionAfterJump = null; + } + + // Verify that the command was called with the completion data + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "continue.showNextEditAfterJump", + completionData, + ); + + // Verify that _completionAfterJump was reset to null + expect((jumpManager as any)._completionAfterJump).toBeNull(); + }); + }); + + describe("clearJumpDecoration", () => { + it("should dispose decoration and reset state", async () => { + // Setup private method access + const privateJumpManager = jumpManager as any; + + // Create a mock decoration with a spy on dispose + const mockDispose = vi.fn(); + privateJumpManager._jumpDecoration = { + dispose: mockDispose, + }; + privateJumpManager._jumpDecorationVisible = true; + + // Reset executeCommand mock + vi.mocked(vscode.commands.executeCommand).mockClear(); + + // Call the method + await privateJumpManager.clearJumpDecoration(); + + // Expect dispose to have been called + expect(mockDispose).toHaveBeenCalled(); + + // Expect decoration to be undefined after clearing + expect(privateJumpManager._jumpDecoration).toBeUndefined(); + expect(privateJumpManager._jumpDecorationVisible).toBe(false); + + // Expect context to be reset + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + "setContext", + "continue.jumpDecorationVisible", + false, + ); + }); + }); +}); diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 89c3c1d57..89a43f765 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -8,6 +8,7 @@ import { CodeRenderer } from "core/codeRenderer/CodeRenderer"; import { myersCharDiff } from "core/diff/myers"; import { getOffsetPositionAtLastNewLine } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { getThemeString } from "../util/getTheme"; export interface TextApplier { @@ -198,10 +199,13 @@ export class NextEditWindowManager { await NextEditWindowManager.freeTabAndEsc(); // Register HIDE_TOOLTIP_COMMAND and ACCEPT_NEXT_EDIT_COMMAND with their corresponding callbacks. - this.registerCommandSafely( - HIDE_NEXT_EDIT_SUGGESTION_COMMAND, - async () => await this.hideAllNextEditWindowsAndResetCompletionId(), - ); + this.registerCommandSafely(HIDE_NEXT_EDIT_SUGGESTION_COMMAND, async () => { + console.log( + "deleteChain from NextEditWindowManager.ts: hide next edit command", + ); + NextEditProvider.getInstance().deleteChain(); + await this.hideAllNextEditWindowsAndResetCompletionId(); + }); this.registerCommandSafely( ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND, async () => await this.acceptNextEdit(), @@ -404,9 +408,9 @@ export class NextEditWindowManager { // Disable inline suggestions temporarily. // This prevents the race condition between vscode's inline completion provider // and the next edit window manager's cursor repositioning logic. - await vscode.workspace - .getConfiguration() - .update("editor.inlineSuggest.enabled", false, true); + // await vscode.workspace + // .getConfiguration() + // .update("editor.inlineSuggest.enabled", false, true); } if (success && this.finalCursorPos) { @@ -417,10 +421,10 @@ export class NextEditWindowManager { ); } - // Reenable inline suggestions. - await vscode.workspace - .getConfiguration() - .update("editor.inlineSuggest.enabled", true, true); + // Reenable inline suggestions after we move the cursor. + // await vscode.workspace + // .getConfiguration() + // .update("editor.inlineSuggest.enabled", true, true); // Log with accept = true. await vscode.commands.executeCommand( @@ -840,6 +844,10 @@ export class NextEditWindowManager { // If all else fails, return a reasonable default return SVG_CONFIG.fontSize * 0.6; } + + public hasAccepted() { + return this.accepted; + } } export default async function setupNextEditWindowManager( diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts new file mode 100644 index 000000000..a72c67202 --- /dev/null +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts @@ -0,0 +1,117 @@ +import * as vscode from "vscode"; + +export interface ExpectedGhostTextAcceptance { + documentUri: string; + documentVersion: number; + text: string; + startLine: number; + startCharacter: number; + endLine: number; + endCharacter: number; +} + +/** + * This singleton tracks whether a given ghost text is accepted or not. + * We need this because there is no clean way of determining if a ghost text has been accepted outside of vscode command callback. + * The above mentioned callback is not viable because it's too slow. + * We need a way to reject model predictions on cursor movement, but cursor can move due to many reasons -- one being accepting a ghost text. + * We need to differentiate the ghost text acceptance from a deliberate cursor movement to reject the completion. + * The cursor movement event listener fires much before the vscode command callback, so the chain of edits often breaks when cursor moves due to accepting a ghost text. + * This is not what we want, as we want to keep the current chain of edits alive when the user accepts the completion. + */ +export class GhostTextAcceptanceTracker { + private static instance: GhostTextAcceptanceTracker | undefined; + private expectedAcceptance: ExpectedGhostTextAcceptance | null = null; + + private constructor() {} + + public static getInstance(): GhostTextAcceptanceTracker { + if (!GhostTextAcceptanceTracker.instance) { + GhostTextAcceptanceTracker.instance = new GhostTextAcceptanceTracker(); + } + return GhostTextAcceptanceTracker.instance; + } + + public static clearInstance() { + GhostTextAcceptanceTracker.instance = undefined; + } + + public setExpectedGhostTextAcceptance( + document: vscode.TextDocument, + text: string, + startPosition: vscode.Position, + ) { + // Calculate end position + const lines = text.split("\n"); + let endLine: number; + let endCharacter: number; + + if (lines.length > 1) { + endLine = startPosition.line + lines.length - 1; + endCharacter = lines[lines.length - 1].length; + } else { + endLine = startPosition.line; + endCharacter = startPosition.character + text.length; + } + + this.expectedAcceptance = { + documentUri: document.uri.toString(), + documentVersion: document.version, + text, + startLine: startPosition.line, + startCharacter: startPosition.character, + endLine, + endCharacter, + }; + } + + public checkGhostTextWasAccepted( + document: vscode.TextDocument, + newPosition: vscode.Position, + ): boolean { + if (!this.expectedAcceptance) return false; + + // Check document match. + if (this.expectedAcceptance.documentUri !== document.uri.toString()) { + return false; + } + + // Check document version (must be newer). + if (document.version <= this.expectedAcceptance.documentVersion) { + return false; + } + + // Check if cursor is at expected end position. + const expectedEndPos = new vscode.Position( + this.expectedAcceptance.endLine, + this.expectedAcceptance.endCharacter, + ); + + if (newPosition.isEqual(expectedEndPos)) { + // The cursor is where we'd expect after accepting the ghost text. + + // Verify text was inserted (optional additional check). + const startPos = new vscode.Position( + this.expectedAcceptance.startLine, + this.expectedAcceptance.startCharacter, + ); + const expectedText = this.expectedAcceptance.text; + + try { + const actualRange = new vscode.Range(startPos, expectedEndPos); + + const actualText = document.getText(actualRange); + + if (actualText === expectedText) { + // Clear the expectation. + this.expectedAcceptance = null; + return true; + } + } catch (error) { + // Range might be invalid, just fall through. + } + } + + return false; + } +} diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.vitest.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.vitest.ts new file mode 100644 index 000000000..18a1b80ff --- /dev/null +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.vitest.ts @@ -0,0 +1,246 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import * as vscode from "vscode"; +import { GhostTextAcceptanceTracker } from "./GhostTextAcceptanceTracker"; + +// Mock the vscode module +vi.mock("vscode", () => ({ + Position: vi.fn((line: number, character: number) => ({ + line, + character, + isEqual: vi.fn( + (other: any) => other.line === line && other.character === character, + ), + })), + Range: vi.fn((start: any, end: any) => ({ start, end })), +})); + +describe("GhostTextAcceptanceTracker", () => { + let tracker: GhostTextAcceptanceTracker; + let mockDocument: vscode.TextDocument; + + beforeEach(() => { + // Clear any existing instance + GhostTextAcceptanceTracker.clearInstance(); + tracker = GhostTextAcceptanceTracker.getInstance(); + + // Create mock document + mockDocument = { + uri: { + toString: () => "file:///test.ts", + }, + version: 1, + getText: vi.fn(), + } as any; + }); + + describe("getInstance", () => { + it("should return the same instance when called multiple times", () => { + const instance1 = GhostTextAcceptanceTracker.getInstance(); + const instance2 = GhostTextAcceptanceTracker.getInstance(); + expect(instance1).toBe(instance2); + }); + + it("should create a new instance after clearInstance is called", () => { + const instance1 = GhostTextAcceptanceTracker.getInstance(); + GhostTextAcceptanceTracker.clearInstance(); + const instance2 = GhostTextAcceptanceTracker.getInstance(); + expect(instance1).not.toBe(instance2); + }); + }); + + describe("setExpectedGhostTextAcceptance", () => { + it("should set expected acceptance for single line text", () => { + const startPosition = new vscode.Position(5, 10); + const text = "console.log('hello')"; + + tracker.setExpectedGhostTextAcceptance(mockDocument, text, startPosition); + + // Verify internal state by testing checkGhostTextWasAccepted. + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(text), + } as any; + const endPosition = new vscode.Position(5, 30); // 10 in startPosition + 20 characters in text + + expect(tracker.checkGhostTextWasAccepted(newDocument, endPosition)).toBe( + true, + ); + }); + + it("should set expected acceptance for multi-line text", () => { + const startPosition = new vscode.Position(5, 10); + const text = "function test() {\n return 'hello';\n}"; + + tracker.setExpectedGhostTextAcceptance(mockDocument, text, startPosition); + + // For multi-line, end position should be at line 7 (5 + 3 lines - 1), character 1 (length of last line). + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(text), + } as any; + const endPosition = new vscode.Position(7, 1); + + expect(tracker.checkGhostTextWasAccepted(newDocument, endPosition)).toBe( + true, + ); + }); + }); + + describe("checkGhostTextWasAccepted", () => { + beforeEach(() => { + const startPosition = new vscode.Position(5, 10); + const text = "console.log('test')"; + tracker.setExpectedGhostTextAcceptance(mockDocument, text, startPosition); + }); + + it("should return false when no expected acceptance is set", () => { + GhostTextAcceptanceTracker.clearInstance(); + const newTracker = GhostTextAcceptanceTracker.getInstance(); + + const newDocument = { ...mockDocument, version: 2 } as any; + const position = new vscode.Position(5, 29); + + expect(newTracker.checkGhostTextWasAccepted(newDocument, position)).toBe( + false, + ); + }); + + it("should return false when document URI doesn't match", () => { + const differentDocument = { + ...mockDocument, + uri: { toString: () => "file:///different.ts" }, + version: 2, + } as any; + const position = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(differentDocument, position), + ).toBe(false); + }); + + it("should return false when document version is not newer", () => { + const sameVersionDocument = { + ...mockDocument, + version: 1, // same version + } as any; + const position = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(sameVersionDocument, position), + ).toBe(false); + + const olderVersionDocument = { + ...mockDocument, + version: 0, // older version + } as any; + + expect( + tracker.checkGhostTextWasAccepted(olderVersionDocument, position), + ).toBe(false); + }); + + it("should return false when cursor position doesn't match expected end position", () => { + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue("console.log('test')"), + } as any; + const wrongPosition = new vscode.Position(5, 20); // wrong position + + expect( + tracker.checkGhostTextWasAccepted(newDocument, wrongPosition), + ).toBe(false); + }); + + it("should return false when text content doesn't match", () => { + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue("different text"), // wrong text + } as any; + const correctPosition = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(false); + }); + + it("should return true when all conditions match and clear expectation", () => { + const expectedText = "console.log('test')"; + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(expectedText), + } as any; + const correctPosition = new vscode.Position(5, 29); // 10 + 19 characters + + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(true); + + // Check for clearing logic. + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(false); + }); + + it("should handle getText throwing an error gracefully", () => { + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockImplementation(() => { + throw new Error("Range invalid"); + }), + } as any; + const correctPosition = new vscode.Position(5, 29); + + expect( + tracker.checkGhostTextWasAccepted(newDocument, correctPosition), + ).toBe(false); + }); + + it("should work with multi-line ghost text acceptance", () => { + const startPosition = new vscode.Position(0, 0); + const multiLineText = "if (condition) {\n doSomething();\n}"; + tracker.setExpectedGhostTextAcceptance( + mockDocument, + multiLineText, + startPosition, + ); + + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(multiLineText), + } as any; + const endPosition = new vscode.Position(2, 1); // line 2, character 1 (length of "}") + + expect(tracker.checkGhostTextWasAccepted(newDocument, endPosition)).toBe( + true, + ); + }); + + it("should handle empty text", () => { + const startPosition = new vscode.Position(10, 5); + const emptyText = ""; + tracker.setExpectedGhostTextAcceptance( + mockDocument, + emptyText, + startPosition, + ); + + const newDocument = { + ...mockDocument, + version: 2, + getText: vi.fn().mockReturnValue(""), + } as any; + const samePosition = new vscode.Position(10, 5); // should be same as start for empty text + + expect(tracker.checkGhostTextWasAccepted(newDocument, samePosition)).toBe( + true, + ); + }); + }); +}); diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 39b82c1a0..966a048b5 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -5,8 +5,6 @@ import { type AutocompleteOutcome, } from "core/autocomplete/util/types"; import { ConfigHandler } from "core/config/ConfigHandler"; -// import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants"; -// import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; @@ -24,7 +22,9 @@ import { checkFim } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { NextEditOutcome } from "core/nextEdit/types"; +import { JumpManager } from "../activation/JumpManager"; import { NextEditWindowManager } from "../activation/NextEditWindowManager"; +import { GhostTextAcceptanceTracker } from "./GhostTextAcceptanceTracker"; import { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService"; @@ -66,6 +66,7 @@ export class ContinueCompletionProvider private completionProvider: CompletionProvider; private nextEditProvider: NextEditProvider; private nextEditLoggingService: NextEditLoggingService; + private jumpManager: JumpManager; public recentlyVisitedRanges: RecentlyVisitedRangesService; public recentlyEditedTracker: RecentlyEditedTracker; @@ -93,6 +94,7 @@ export class ContinueCompletionProvider } return config.selectedModelByRole.autocomplete ?? undefined; } + this.completionProvider = new CompletionProvider( this.configHandler, this.ide, @@ -112,11 +114,21 @@ export class ContinueCompletionProvider "fineTuned", ); + this.jumpManager = JumpManager.getInstance(); + this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide); } _lastShownCompletion: AutocompleteOutcome | NextEditOutcome | undefined; + private async getRerankModel() { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + return; + } + return config.selectedModelByRole.rerank ?? undefined; + } + public async provideInlineCompletionItems( document: vscode.TextDocument, position: vscode.Position, @@ -167,14 +179,11 @@ export class ContinueCompletionProvider token.onCancellationRequested(() => abortController.abort()); // Handle notebook cells - const pos = { + let pos = { line: position.line, character: position.character, }; - // const pos = { - // line: 0, - // character: 0, - // }; + let manuallyPassFileContents: string | undefined = undefined; if (document.uri.scheme === "vscode-notebook-cell") { const notebook = vscode.workspace.notebookDocuments.find((notebook) => @@ -220,35 +229,91 @@ export class ContinueCompletionProvider const wasManuallyTriggered = context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke; - const input: AutocompleteInput = { - pos, - manuallyPassFileContents, - manuallyPassPrefix, - selectedCompletionInfo, - injectDetails, - isUntitledFile: document.isUntitled, - completionId: uuidv4(), - filepath: document.uri.toString(), - recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), - recentlyEditedRanges: - await this.recentlyEditedTracker.getRecentlyEditedRanges(), - }; + let outcome: AutocompleteOutcome | NextEditOutcome | undefined; + const completionId = uuidv4(); + const filepath = document.uri.toString(); + const recentlyVisitedRanges = this.recentlyVisitedRanges.getSnippets(); + let recentlyEditedRanges = + await this.recentlyEditedTracker.getRecentlyEditedRanges(); - setupStatusBar(undefined, true); + if (this.nextEditProvider.chainExists()) { + // The chain of edits is alive because the user has accepted the previous completion. + // Get the next editable region and set the pos to be within that range. + outcome = + await this.nextEditProvider.provideInlineCompletionItemsWithChain( + { + completionId, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + isUntitledFile: document.isUntitled, + recentlyVisitedRanges, + recentlyEditedRanges, + }, + signal, + ); + } else { + // If the user has rejected, then we start a new chain of edits. + this.nextEditProvider.startChain(); - // TODO: fix type of outcome to be a union between NextEditOutcome and AutocompleteOutcome. - const outcome: AutocompleteOutcome | NextEditOutcome | undefined = this - .isNextEditActive - ? await this.nextEditProvider.provideInlineCompletionItems( + const input: AutocompleteInput = { + pos, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + injectDetails, + isUntitledFile: document.isUntitled, + completionId, + filepath, + recentlyVisitedRanges, + recentlyEditedRanges, + }; + + setupStatusBar(undefined, true); + + // Check if editChainId exists or needs to be refreshed. + if (this.isNextEditActive) { + outcome = await this.nextEditProvider.provideInlineCompletionItems( input, signal, - ) - : await this.completionProvider.provideInlineCompletionItems( + { withChain: false }, + ); + + if (!outcome || !outcome.completion) { + // Hitting this condition means that the model could not predict a next edit action. + // That happens when the user's recent edit is good enough, or if the model is totally lost. + // At this point we assume that the user typed something good enough to maintain a chain of edits. + // All we need to do here is to calculate next editable region. + // We also need to use the user's edits to create a user edits section in renderPrompt. + recentlyEditedRanges = + await this.recentlyEditedTracker.getRecentlyEditedRanges(); + + outcome = + await this.nextEditProvider.provideInlineCompletionItemsWithChain( + { + completionId, + manuallyPassFileContents, + manuallyPassPrefix, + selectedCompletionInfo, + isUntitledFile: document.isUntitled, + recentlyVisitedRanges, + recentlyEditedRanges, + }, + signal, + ); + } + } else { + // Handle autocomplete request. + outcome = await this.completionProvider.provideInlineCompletionItems( input, signal, wasManuallyTriggered, ); + } + } + // If the model cannot predict a completion or a next edit, + // then it's safe to assume that there are no more changes to be made. if (!outcome || !outcome.completion) { return null; } @@ -279,16 +344,16 @@ export class ContinueCompletionProvider return null; } - // Marking the outcome as displayed saves - // the current outcome as a value of the key completionId. + // Marking the outcome as displayed saves the current outcome + // as a value of the key completionId. if (this.isNextEditActive) { this.nextEditProvider.markDisplayed( - input.completionId, + completionId, outcome as NextEditOutcome, ); } else { this.completionProvider.markDisplayed( - input.completionId, + completionId, outcome as AutocompleteOutcome, ); } @@ -296,13 +361,9 @@ export class ContinueCompletionProvider // Construct the range/text to show const startPos = selectedCompletionInfo?.range.start ?? position; - // const startPos = new vscode.Position(0, 0); - // const endPos = new vscode.Position(0, 5); let range = new vscode.Range(startPos, startPos); - // let range = new vscode.Range(startPos, endPos); let completionText = outcome.completion; - // NOTE: This seems like an autocomplete logic. const isSingleLineCompletion = outcome.completion.split("\n").length <= 1; if (isSingleLineCompletion) { @@ -339,15 +400,46 @@ export class ContinueCompletionProvider { title: "Log Autocomplete Outcome", command: "continue.logAutocompleteOutcome", - arguments: [input.completionId, this.completionProvider], + arguments: [completionId, this.completionProvider], }, ); (autocompleteCompletionItem as any).completeBracketPairs = true; + const editor = vscode.window.activeTextEditor; + if (!editor) { + return undefined; + } + + const currCursorPos = editor.selection.active; + if (this.isNextEditActive) { - const editor = vscode.window.activeTextEditor; - if (!editor) { + if (!this.nextEditProvider.isStartOfChain()) { + const jumpPosition = new vscode.Position( + (outcome as NextEditOutcome).editableRegionStartLine, + 0, + ); + + // Suggest a jump if there is a valid next location. + // This will set isJumpInProgress if a jump is suggested. + await this.jumpManager.suggestJump( + currCursorPos, + jumpPosition, + outcome.completion, + ); + + // If a jump was just suggested, don't show ghost text yet. + if (this.jumpManager.isJumpInProgress()) { + // Store this completion to be rendered after jump is complete. + this.jumpManager.setCompletionAfterJump({ + completionId: completionId, + outcome: outcome as NextEditOutcome, + currentPosition: jumpPosition, + }); + + return undefined; // Don't show anything yet! + } + return undefined; } @@ -356,14 +448,11 @@ export class ContinueCompletionProvider // We don't need to show the next edit window if the predicted edits is empty. if (newEditRangeSlice === "") { - this.nextEditLoggingService.cancelRejectionTimeout( - input.completionId, - ); + this.nextEditLoggingService.cancelRejectionTimeout(completionId); return undefined; } // Get the contents of the old (current) editable region. - const currCursorPos = editor.selection.active; const editableRegionStartLine = Math.max( currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0, @@ -380,19 +469,42 @@ export class ContinueCompletionProvider // We don't need to show the next edit window if the predicted edits are identical to the previous version. if (oldEditRangeSlice === newEditRangeSlice) { - this.nextEditLoggingService.cancelRejectionTimeout( - input.completionId, - ); + this.nextEditLoggingService.cancelRejectionTimeout(completionId); return undefined; } + // Create a cursor position relative to the edit range slice. + const relativeCursorPos = { + line: currCursorPos.line - editableRegionStartLine, + character: currCursorPos.character, + }; + // If the diff is a FIM, render a ghost text. const { isFim, fimText } = checkFim( oldEditRangeSlice, newEditRangeSlice, - currCursorPos, + relativeCursorPos, ); + if (isFim) { + if (!fimText) { + console.log("deleteChain from completionProvider.ts: !fimText"); + this.nextEditProvider.deleteChain(); + return undefined; + } + + // Track this ghost text for acceptance detection. + // Ghost text acceptance can *technically* be acted upon in + // the command handler for "continue.logNextEditOutcomeAccept", + // but there is a substantial delay between accepting and logging, + // which introduces a lot of race conditions with different event handlers. + // Plus, separating these concerns seems to make sense logically as well. + GhostTextAcceptanceTracker.getInstance().setExpectedGhostTextAcceptance( + document, + fimText, + new vscode.Position(currCursorPos.line, currCursorPos.character), + ); + const nextEditCompletionItem = new vscode.InlineCompletionItem( fimText, new vscode.Range( @@ -402,7 +514,7 @@ export class ContinueCompletionProvider { title: "Log Next Edit Outcome", command: "continue.logNextEditOutcomeAccept", - arguments: [input.completionId, this.nextEditLoggingService], // TODO: this may have to be this.completionProvider. + arguments: [completionId, this.nextEditLoggingService], }, ); return [nextEditCompletionItem]; @@ -410,10 +522,16 @@ export class ContinueCompletionProvider // Else, render a next edit window. const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + if (diffLines.length === 0) { + console.log( + "deleteChain from completionProvider.ts: diffLines.length === 0", + ); + NextEditProvider.getInstance().deleteChain(); + } if (NextEditWindowManager.isInstantiated()) { NextEditWindowManager.getInstance().updateCurrentCompletionId( - input.completionId, + completionId, ); await NextEditWindowManager.getInstance().showNextEditWindow( diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index c3d5c11a4..32e8b03f5 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -14,6 +14,7 @@ import * as URI from "uri-js"; import * as vscode from "vscode"; import type { + DocumentSymbol, IDE, Range, RangeInFile, @@ -434,3 +435,90 @@ export async function executeSignatureHelpProvider( return null; } } + +type SymbolProviderName = "vscode.executeDocumentSymbolProvider"; + +interface SymbolInput { + uri: vscode.Uri; + name: SymbolProviderName; +} + +function symbolInputKey(input: SymbolInput) { + return `${input.name}${input.uri.toString()}`; +} + +const MAX_SYMBOL_CACHE_SIZE = 100; +const symbolCache = new Map(); + +export async function executeSymbolProvider( + input: SymbolInput, +): Promise { + const cacheKey = symbolInputKey(input); + const cached = symbolCache.get(cacheKey); + if (cached) { + return cached; + } + + try { + const symbols = (await vscode.commands.executeCommand( + input.name, + input.uri, + // )) as vscode.DocumentSymbol[] | vscode.SymbolInformation[]; + )) as vscode.DocumentSymbol[]; + + const results: DocumentSymbol[] = []; + + // Handle both possible return types from the symbol provider + if (symbols.length > 0) { + // if ("location" in symbols[0]) { + // // SymbolInformation type + // results.push( + // ...symbols.map((s: vscode.SymbolInformation) => ({ + // filepath: s.location.uri.toString(), + // range: s.location.range, + // })), + // ); + // } else { + // DocumentSymbol type - collect symbols recursively + function collectSymbols( + symbols: vscode.DocumentSymbol[], + uri: vscode.Uri, + ): DocumentSymbol[] { + const result: DocumentSymbol[] = []; + for (const symbol of symbols) { + result.push({ + name: symbol.name, + range: symbol.range, + selectionRange: symbol.selectionRange, + kind: symbol.kind, + }); + + if (symbol.children && symbol.children.length > 0) { + result.push(...collectSymbols(symbol.children, uri)); + } + } + return result; + } + + results.push( + ...collectSymbols(symbols as vscode.DocumentSymbol[], input.uri), + ); + // } + } + + // Add to cache + if (symbolCache.size >= MAX_SYMBOL_CACHE_SIZE) { + // Remove the oldest item from the cache + const oldestKey = symbolCache.keys().next().value; + if (oldestKey) { + symbolCache.delete(oldestKey); + } + } + symbolCache.set(cacheKey, results); + + return results; + } catch (e) { + console.warn(`Error executing ${input.name}:`, e); + return []; + } +} diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 9fa48cd98..fc4eab517 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -67,6 +67,7 @@ export class RecentlyEditedTracker { lines: contents.split("\n"), symbols: getSymbolsForSnippet(contents), }; + this.recentlyEditedRanges[i] = range; return; } } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 3b247f88b..2ffd24418 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -17,7 +17,16 @@ import * as YAML from "yaml"; import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist"; +import { myersDiff } from "core/diff/myers"; +import { + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, +} from "core/nextEdit/constants"; +import { checkFim } from "core/nextEdit/diff/diff"; import { NextEditLoggingService } from "core/nextEdit/NextEditLoggingService"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; +import { CompletionDataForAfterJump } from "./activation/JumpManager"; +import { NextEditWindowManager } from "./activation/NextEditWindowManager"; import { getAutocompleteStatusBarDescription, getAutocompleteStatusBarTitle, @@ -805,6 +814,125 @@ const getCommandsMap: ( "editor.action.inlineSuggest.trigger", ); }, + "continue.showNextEditAfterJump": async ( + data: CompletionDataForAfterJump, + ) => { + // NOTE: This could use some cleanup or abstraction. + // The logic is largely similar to that of completionProvider.ts + // but we don't have access to the class. + + const { completionId, outcome, currentPosition } = data; + + const editor = vscode.window.activeTextEditor; + if (!editor) { + console.log("No active editor when trying to show next edit"); + return; + } + + const documentContent = editor.document.getText(); + + // Calculate the editable region boundaries around the current cursor position/ + const editableRegionStartLine = Math.max( + currentPosition.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, + 0, + ); + const editableRegionEndLine = Math.min( + currentPosition.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN, + editor.document.lineCount - 1, + ); + + // Get the current text in the editable region. + const oldEditRangeSlice = documentContent + .split("\n") + .slice(editableRegionStartLine, editableRegionEndLine + 1) + .join("\n"); + + // Get the suggested new text from the completion outcome. + const newEditRangeSlice = outcome.completion; + + // Skip showing edit if the suggestion is empty. + if (newEditRangeSlice === "") { + const loggingService = NextEditLoggingService.getInstance(); + loggingService.cancelRejectionTimeout(completionId); + return; + } + + // Skip showing edit if the suggestion is identical to current text. + if (oldEditRangeSlice === newEditRangeSlice) { + const loggingService = NextEditLoggingService.getInstance(); + loggingService.cancelRejectionTimeout(completionId); + return; + } + + // Create a cursor position relative to the edit range slice + const relativeCursorPos = { + line: currentPosition.line - editableRegionStartLine, + character: currentPosition.character, + }; + const { isFim, fimText } = checkFim( + oldEditRangeSlice, + newEditRangeSlice, + relativeCursorPos, + ); + + if (isFim) { + if (!fimText) { + console.log("deleteChain from commands.ts: !fimText"); + await NextEditProvider.getInstance().deleteChain(); + } + // For FIM edits, create an inline completion item. + const nextEditCompletionItem = new vscode.InlineCompletionItem( + fimText, + new vscode.Range( + new vscode.Position( + currentPosition.line, + currentPosition.character, + ), + new vscode.Position( + currentPosition.line, + currentPosition.character, + ), + ), + { + title: "Log Next Edit Outcome", + command: "continue.logNextEditOutcomeAccept", + arguments: [completionId, NextEditLoggingService.getInstance()], + }, + ); + + // Show the ghost text using VS Code's inline completion API. + // We need to trigger this manually since we're not in the completion provider. + await vscode.commands.executeCommand( + "editor.action.inlineSuggest.trigger", + { + completions: [nextEditCompletionItem], + position: currentPosition, + }, + ); + } else { + // For more complex edits, we display a diff inside a window. + const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); + if (diffLines.length === 0) { + console.log("deleteChain from commands.ts: diffLines.length === 0"); + await NextEditProvider.getInstance().deleteChain(); + } + + if (NextEditWindowManager.isInstantiated()) { + const windowManager = NextEditWindowManager.getInstance(); + windowManager.updateCurrentCompletionId(completionId); + + await windowManager.showNextEditWindow( + editor, + currentPosition, + editableRegionStartLine, + editableRegionEndLine, + oldEditRangeSlice, + newEditRangeSlice, + diffLines, + ); + } + } + }, }; }; diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index a6c66b310..05debe7e9 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -42,10 +42,20 @@ import { VsCodeIde } from "../VsCodeIde"; import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider"; import { VsCodeMessenger } from "./VsCodeMessenger"; +import { getAst } from "core/autocomplete/util/ast"; +import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker"; +import { + EditableRegionStrategy, + getNextEditableRegion, +} from "core/nextEdit/NextEditEditableRegionCalculator"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { isModelCapableOfNextEdit } from "core/nextEdit/utils"; +import { localPathOrUriToPath } from "core/util/pathToUri"; +import { JumpManager } from "../activation/JumpManager"; import setupNextEditWindowManager, { NextEditWindowManager, } from "../activation/NextEditWindowManager"; +import { GhostTextAcceptanceTracker } from "../autocomplete/GhostTextAcceptanceTracker"; import { getDefinitionsFromLsp } from "../autocomplete/lsp"; import { handleTextDocumentChange } from "../util/editLoggingUtils"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -69,6 +79,18 @@ export class VsCodeExtension { private fileSearch: FileSearch; private uriHandler = new UriEventHandler(); private completionProvider: ContinueCompletionProvider; + // Track whether the user is currently typing + private isTypingSession = false; + private typingTimer: NodeJS.Timeout | null = null; + private lastDocumentChangeTime = 0; + + // Reset typing session after a delay + resetTypingSession = () => { + if (this.typingTimer) clearTimeout(this.typingTimer); + this.typingTimer = setTimeout(() => { + this.isTypingSession = false; + }, 2000); // Typing session considered over after 2 seconds of inactivity + }; constructor(context: vscode.ExtensionContext) { // Register auth provider @@ -175,10 +197,16 @@ export class VsCodeExtension { await setupNextEditWindowManager(context); this.activateNextEdit(); await NextEditWindowManager.freeTabAndEsc(); + + JumpManager.getInstance(); + GhostTextAcceptanceTracker.getInstance(); } else { NextEditWindowManager.clearInstance(); this.deactivateNextEdit(); await NextEditWindowManager.freeTabAndEsc(); + + JumpManager.clearInstance(); + GhostTextAcceptanceTracker.clearInstance(); } if (configLoadInterrupted) { @@ -315,6 +343,12 @@ export class VsCodeExtension { }); vscode.workspace.onDidChangeTextDocument(async (event) => { + if (event.contentChanges.length > 0) { + this.isTypingSession = true; + this.lastDocumentChangeTime = Date.now(); + this.resetTypingSession(); + } + const editInfo = await handleTextDocumentChange( event, this.configHandler, @@ -350,6 +384,18 @@ export class VsCodeExtension { }); }); + vscode.workspace.onDidOpenTextDocument(async (event) => { + console.log("onDidOpenTextDocument"); + const ast = await getAst(event.fileName, event.getText()); + if (ast) { + DocumentHistoryTracker.getInstance().addDocument( + localPathOrUriToPath(event.fileName), + event.getText(), + ast, + ); + } + }); + // When GitHub sign-in status changes, reload config vscode.authentication.onDidChangeSessions(async (e) => { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); @@ -377,6 +423,66 @@ export class VsCodeExtension { } }); + // Listen for editor changes to clean up decorations when editor closes. + vscode.window.onDidChangeVisibleTextEditors(async () => { + // If our active editor is no longer visible, clear decorations. + await NextEditProvider.getInstance().deleteChain(); + }); + + // Listen for selection changes to hide tooltip when cursor moves. + vscode.window.onDidChangeTextEditorSelection(async (e) => { + // Don't delete the chain of edits if: + + // 1. A next edit window was just accepted. + if ( + NextEditWindowManager.isInstantiated() && + NextEditWindowManager.getInstance().hasAccepted() + ) { + return; + } + + // 2. A jump is in progress. + if (JumpManager.getInstance().isJumpInProgress()) { + return; + } + + // 3. A ghost text was just accepted. + // Check if this selection change matches our expected ghost text acceptance. + const wasGhostTextAccepted = + GhostTextAcceptanceTracker.getInstance().checkGhostTextWasAccepted( + e.textEditor.document, + e.selections[0].active, + ); + + if (wasGhostTextAccepted) { + // Ghost text was accepted - don't delete the chain. + return; + } + + // 4. The selection change is part of a typing session + // Check if this selection change is close enough to a document change to be considered typing. + const timeSinceLastDocChange = Date.now() - this.lastDocumentChangeTime; + const ARBITRARY_TYPING_DELAY = 500; + if ( + this.isTypingSession && + timeSinceLastDocChange < ARBITRARY_TYPING_DELAY + ) { + // This selection change is likely due to typing, don't delete the chain. + return; + } + + // Otherwise, delete the chain (for rejection or unrelated movement). + await NextEditProvider.getInstance().deleteChain(); + + NextEditProvider.getInstance().loadNextEditableRegionsInTheCurrentChain( + (await getNextEditableRegion(EditableRegionStrategy.Static, { + cursorPosition: e.selections[0].anchor, + filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), + ide: this.ide, + })) ?? [], + ); + }); + // Refresh index when branch is changed void this.ide.getWorkspaceDirs().then((dirs) => dirs.forEach(async (dir) => { diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 41336cd24..2ecd1c205 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -390,6 +390,14 @@ export class VsCodeMessenger { return await ide.gotoDefinition(msg.data.location); }); + this.onWebviewOrCore("getReferences", async (msg) => { + return await ide.getReferences(msg.data.location); + }); + + this.onWebviewOrCore("getDocumentSymbols", async (msg) => { + return await ide.getDocumentSymbols(msg.data.textDocumentIdentifier); + }); + this.onWebviewOrCore("getFileStats", async (msg) => { return await ide.getFileStats(msg.data.files); }); diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 6f213b302..d8593f7d0 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -111,6 +111,7 @@ export class VsCodeIdeUtils { /** * Read the entire contents of a file from the given URI. + * If there are unsaved changes in an open editor, returns those instead of the file on disk. * * @param uri - The URI of the file to read. * @param ignoreMissingProviders - Optional flag to ignore missing file system providers for unsupported schemes. @@ -124,6 +125,18 @@ export class VsCodeIdeUtils { uri: vscode.Uri, ignoreMissingProviders: boolean = true, ): Promise { + // First check if there's an open document with this URI that might have unsaved changes. + const openDocuments = vscode.workspace.textDocuments; + for (const document of openDocuments) { + if (document.uri.toString() === uri.toString()) { + // Found an open document with this URI. + // Return its current content (including any unsaved changes) as Uint8Array. + const docText = document.getText(); + return Buffer.from(docText, "utf8"); + } + } + + // If no open document found or if it's not dirty, fall back to reading from disk. return await this.fsOperation( uri, async (u) => {