diff --git a/core/core.ts b/core/core.ts index 55c97896e..65f2e4ede 100644 --- a/core/core.ts +++ b/core/core.ts @@ -668,6 +668,8 @@ export class Core { return queue.dequeueProcessed() || null; }); + // NOTE: This is not used unless prefetch is used. + // At this point this is not used because I opted to rely on the model to return multiple diffs than to use prefetching. on("nextEdit/queue/processOne", async (msg) => { console.log("nextEdit/queue/processOne"); const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data; diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index ad6a1afa2..806be4873 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -13,6 +13,10 @@ export enum EditableRegionStrategy { Static = "static", } +/** + * This was an attempt to find next edit locations deterministically. + * I was intending to use this in tandem with the prefetching logic, but we are not using it anymore. + */ export async function getNextEditableRegion( strategy: EditableRegionStrategy, ctx: any, diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts index 9037f218f..ad35db3b9 100644 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ b/core/nextEdit/NextEditPrefetchQueue.ts @@ -10,6 +10,11 @@ export interface ProcessedItem { /** * Keeps a queue of the broken down diffs from a changed editable range, as determined in core/nextEdit/diff.ts */ +/** + * This is where the chain is stored. Think of it as a regular queue, but being a singleton because we need one source of truth for the chain. + * I originally intended this to be a separate data structure to handle prefetching next edit outcomes from the model in the background. + * Due to subpar results, lack of satisfactory next edit location suggestion algorithms and token cost/latency issues, I scratched the idea. + */ export class PrefetchQueue { private static instance: PrefetchQueue | null = null; diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 3d0f5350f..4d9216914 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -19,7 +19,6 @@ import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; import { isSecurityConcern } from "../indexing/ignore.js"; import { modelSupportsNextEdit } from "../llm/autodetect.js"; -import { countTokens } from "../llm/countTokens.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js"; @@ -45,6 +44,14 @@ const ERRORS_TO_IGNORE = [ "operation was aborted", ]; +/** + * This is the next edit analogue to autocomplete's CompletionProvider. + * You will see a lot of similar if not identical methods to CompletionProvider methods. + * All logic used to live inside this class, but that became untenable quickly. + * I moved a lot of the model-specific logic (prompt building, pre/post processing, etc.) to the BaseNextEditProvider and the children inheriting from it. + * Keeping this class around might be a good idea because it handles lots of delicate logic such as abort signals, chains, logging, etc. + * There being a singleton also gives a lot of guarantees about the state of the next edit state machine. + */ export class NextEditProvider { private static instance: NextEditProvider | null = null; @@ -62,7 +69,6 @@ export class NextEditProvider { private currentEditChainId: string | null = null; private previousRequest: AutocompleteInput | null = null; private previousCompletions: NextEditOutcome[] = []; - // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = []; // Model-specific provider instance. private modelProvider: BaseNextEditModelProvider | null = null; @@ -223,14 +229,14 @@ export class NextEditProvider { this.currentEditChainId = null; this.previousCompletions = []; - // TODO: this should be cleaned up in the prefetch queue. - // 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), @@ -253,6 +259,9 @@ export class NextEditProvider { return this.previousCompletions.length === 1; } + /** + * This is the main entry point to this class. + */ public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, @@ -370,6 +379,8 @@ export class NextEditProvider { throw new Error("Model provider not initialized"); } + // NOTE: getAllSnippetsWithoutRace doesn't seem to incur much performance penalties when compared to getAllSnippets. + // Use getAllSnippets if snippet gathering becomes noticably slow. const [snippetPayload, workspaceDirs] = await Promise.all([ getAllSnippetsWithoutRace({ helper, @@ -445,6 +456,9 @@ export class NextEditProvider { } // Send prompts to LLM (using only user prompt for fine-tuned models). + // prompts[1] extracts the user prompt from the system-user prompt pair. + // NOTE: Stream is currently set to false, but this should ideally be a per-model flag. + // Mercury Coder currently does not support streaming. const msg: ChatMessage = await llm.chat([prompts[1]], token, { stream: false, }); @@ -484,7 +498,7 @@ export class NextEditProvider { } if (outcome) { - // Handle NextEditProvider-specific state + // Handle NextEditProvider-specific state. this.previousCompletions.push(outcome); // Mark as displayed for JetBrains @@ -494,97 +508,6 @@ export class NextEditProvider { return outcome; } - private _calculateOptimalEditableRegion( - helper: HelperVars, - heuristic: "fourChars" | "tokenizer" = "tokenizer", - ): { - editableRegionStartLine: number; - editableRegionEndLine: number; - } { - const cursorLine = helper.pos.line; - const fileLines = helper.fileLines; - const MAX_TOKENS = 512; - - // Initialize with cursor line. - let editableRegionStartLine = cursorLine; - let editableRegionEndLine = cursorLine; - - // Get initial content and token count. - let currentContent = fileLines[cursorLine]; - let totalTokens = - heuristic === "tokenizer" - ? countTokens(currentContent, helper.modelName) - : Math.ceil(currentContent.length / 4); - - // Expand outward alternating between adding lines above and below. - let addingAbove = true; - - while (totalTokens < MAX_TOKENS) { - let addedLine = false; - - if (addingAbove) { - // Try to add a line above. - if (editableRegionStartLine > 0) { - editableRegionStartLine--; - const lineContent = fileLines[editableRegionStartLine]; - const lineTokens = - heuristic === "tokenizer" - ? countTokens(lineContent, helper.modelName) - : Math.ceil(lineContent.length / 4); - - totalTokens += lineTokens; - addedLine = true; - } - } else { - // Try to add a line below. - if (editableRegionEndLine < fileLines.length - 1) { - editableRegionEndLine++; - const lineContent = fileLines[editableRegionEndLine]; - const lineTokens = - heuristic === "tokenizer" - ? countTokens(lineContent, helper.modelName) - : Math.ceil(lineContent.length / 4); - - totalTokens += lineTokens; - addedLine = true; - } - } - - // If we can't add in the current direction, try the other. - if (!addedLine) { - // If we're already at both file boundaries, we're done. - if ( - editableRegionStartLine === 0 && - editableRegionEndLine === fileLines.length - 1 - ) { - break; - } - - // If we couldn't add in one direction, force the next attempt in the other direction. - addingAbove = !addingAbove; - continue; - } - - // If we exceeded the token limit, revert the last addition. - if (totalTokens > MAX_TOKENS) { - if (addingAbove) { - editableRegionStartLine++; - } else { - editableRegionEndLine--; - } - break; - } - - // Alternate between adding above and below for balanced context. - addingAbove = !addingAbove; - } - - return { - editableRegionStartLine, - editableRegionEndLine, - }; - } - private async _markDisplayedIfJetBrains( completionId: string, outcome: NextEditOutcome, @@ -595,6 +518,12 @@ export class NextEditProvider { } } + /** + * This is a wrapper around provideInlineCompletionItems. + * This is invoked when we call the model in the background using prefetch. + * It's not currently used anywhere (references are not used either), but I decided to keep it in case we actually need to use prefetch. + * You will see that calls to this method is made from NextEditPrefetchQueue.proecss(), which is wrapped in `if (!this.usingFullFileDiff)`. + */ public async provideInlineCompletionItemsWithChain( ctx: { completionId: string; diff --git a/core/nextEdit/NextEditProvider.vitest.ts b/core/nextEdit/NextEditProvider.vitest.ts deleted file mode 100644 index a86cc8a34..000000000 --- a/core/nextEdit/NextEditProvider.vitest.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; -import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; -import { HelperVars } from "../autocomplete/util/HelperVars.js"; -import { ConfigHandler } from "../config/ConfigHandler.js"; -import { IDE, ILLM } from "../index.js"; -import { NextEditProvider } from "./NextEditProvider.js"; - -// Mock the countTokens function -vi.mock("../llm/countTokens.js", () => ({ - countTokens: (text: string) => { - // Simple mock that counts 1 token per character for predictable tests - return text.length; - }, -})); - -// Create a helper function to set up the test context -function createMockHelper( - fileContents: string, - cursorLine: number, -): HelperVars { - const fileLines = fileContents.split("\n"); - - return { - fileLines, - fileContents, - pos: { line: cursorLine, character: 0 }, - modelName: "gpt-4", - lang: { name: "typescript" }, - filepath: "test/file.ts", - workspaceUris: ["test/workspace"], - options: {}, - input: { completionId: "test-completion-id" }, - } as unknown as HelperVars; -} - -// TODO: Add more tests for other methods. -describe("_calculateOptimalEditableRegion", () => { - let nextEditProvider: NextEditProvider; - let mockConfigHandler: ConfigHandler; - let mockIde: IDE; - let mockGetLlm: () => Promise; - let mockOnError: (e: any) => void; - let mockGetDefinitionsFromLsp: GetLspDefinitionsFunction; - - beforeEach(() => { - // Create comprehensive mocks for all dependencies - mockConfigHandler = { - loadConfig: vi.fn().mockResolvedValue({ config: {} }), - } as unknown as ConfigHandler; - - mockIde = { - readFile: vi.fn().mockResolvedValue(""), - getWorkspaceDirs: vi.fn().mockResolvedValue([]), - getRepoName: vi.fn().mockResolvedValue("test-repo"), - getUniqueId: vi.fn().mockResolvedValue("test-id"), - getIdeInfo: vi.fn().mockResolvedValue({ ideType: "vscode" }), - onDidChangeActiveTextEditor: vi.fn().mockImplementation((callback) => { - // Return a disposable object that does nothing when disposed - return { - dispose: () => {}, - }; - }), - } as unknown as IDE; - - mockGetLlm = vi.fn().mockResolvedValue({ - model: "gpt-4", - providerName: "openai", - underlyingProviderName: "openai", - completionOptions: {}, - chat: vi.fn(), - }); - - mockOnError = vi.fn(); - mockGetDefinitionsFromLsp = vi.fn(); - - // Initialize NextEditProvider with mocked dependencies - nextEditProvider = NextEditProvider.initialize( - mockConfigHandler, - mockIde, - mockGetLlm, - mockOnError, - mockGetDefinitionsFromLsp, - "default", - ); - - // Expose the private method for testing - // This is a bit of a hack, but necessary for testing private methods - (nextEditProvider as any)._calculateOptimalEditableRegion = ( - NextEditProvider.prototype as any - )._calculateOptimalEditableRegion.bind(nextEditProvider); - }); - - // Test cases remain the same as before... - it("should include only the cursor line when it already exceeds token limit", () => { - // Create a mock helper with a very long cursor line (>500 characters) - const longLine = "X".repeat(600); - const helper = createMockHelper(longLine, 0); - - //@ts-ignore - const result = nextEditProvider._calculateOptimalEditableRegion( - helper, - "tokenizer", - ); - - expect(result.editableRegionStartLine).toBe(0); - expect(result.editableRegionEndLine).toBe(0); - }); - - it("should expand symmetrically when possible", () => { - // Create content with identical lines and cursor in the middle - const lines = Array(11).fill("A".repeat(40)).join("\n"); // 11 lines of 40 chars each - const helper = createMockHelper(lines, 5); // Cursor in the middle (line 5) - - //@ts-ignore - const result = nextEditProvider._calculateOptimalEditableRegion( - helper, - "tokenizer", - ); - - // Should expand 5 lines in each direction (total 11 lines) for symmetry - expect(result.editableRegionStartLine).toBe(0); - expect(result.editableRegionEndLine).toBe(10); - }); - - it("should expand asymmetrically when hitting a file boundary", () => { - // Create content with cursor near the top - const lines = Array(20).fill("B".repeat(20)).join("\n"); // 20 lines of 20 chars each - const helper = createMockHelper(lines, 1); // Cursor near the top (line 1) - - //@ts-ignore - const result = nextEditProvider._calculateOptimalEditableRegion( - helper, - "tokenizer", - ); - - // Should include more lines below since it can't expand much above - expect(result.editableRegionStartLine).toBe(0); - // Should include many more lines below to reach token limit - expect(result.editableRegionEndLine).toBeGreaterThan(10); - }); - - it("should handle files with varying line lengths", () => { - // Create content with varying line lengths - const fileContents = [ - "Short line", // 10 chars - "A".repeat(100), // 100 chars - "Medium length line here", // 24 chars - "B".repeat(200), // 200 chars - "Another typical line of code", // 28 chars - ].join("\n"); - - const helper = createMockHelper(fileContents, 2); // Cursor on the medium line - - //@ts-ignore - const result = nextEditProvider._calculateOptimalEditableRegion( - helper, - "tokenizer", - ); - - // Should include all lines since total tokens < 500 - expect(result.editableRegionStartLine).toBe(0); - expect(result.editableRegionEndLine).toBe(4); - }); - - it("should respect the token limit and not include too many lines", () => { - // Create content with many small lines (10 chars each) - const lines = Array(600).fill("C".repeat(10)).join("\n"); - const helper = createMockHelper(lines, 300); // Cursor in the middle - - //@ts-ignore - const result = nextEditProvider._calculateOptimalEditableRegion( - helper, - "tokenizer", - ); - - // Each line is 10 chars = 10 tokens per line with our mock. - // So with 500 token limit, we should get 50 lines total. - // 25 above, 25 below, +1 current - const totalLines = - result.editableRegionEndLine - result.editableRegionStartLine + 1; - expect(totalLines).toBe(51); // Not more than 51 lines (25 above, 25 below, +1 for current line) - }); - - it("should use character approximation when using fourChars heuristic", () => { - // In this test, we're setting up a situation where tiktoken and fourChars would give different results - // Creating 5 lines, each 100 characters - const lines = Array(10).fill("D".repeat(100)).join("\n"); - const helper = createMockHelper(lines, 2); // Cursor in the middle - - // Mock for tiktoken counting (1 char = 1 token) - //@ts-ignore - const tokenizerResult = nextEditProvider._calculateOptimalEditableRegion( - helper, - "tokenizer", - ); - - // Mock for fourChars counting (1 token = 4 chars) - // This should include more lines since each line is counted as 25 tokens instead of 100 - //@ts-ignore - const fourCharsResult = nextEditProvider._calculateOptimalEditableRegion( - helper, - "fourChars", - ); - - // The fourChars approach should include more lines since it estimates fewer tokens per line - expect( - fourCharsResult.editableRegionEndLine - - fourCharsResult.editableRegionStartLine, - ).toBeGreaterThan( - tokenizerResult.editableRegionEndLine - - tokenizerResult.editableRegionStartLine, - ); - }); - - it("should include the entire file if it's within token limit", () => { - // Create a small file - const smallFile = "Small file\nwith just\na few lines\nof text"; - const helper = createMockHelper(smallFile, 1); - - //@ts-ignore - const result = nextEditProvider._calculateOptimalEditableRegion( - helper, - "tokenizer", - ); - - // Should include all lines - expect(result.editableRegionStartLine).toBe(0); - expect(result.editableRegionEndLine).toBe(3); - }); - - it("should prioritize balanced context when token limit allows", () => { - // Create content with alternating long and short lines - const fileContents = [ - "Short", // 5 chars - "E".repeat(80), // 80 chars - "Also short", // 10 chars - "F".repeat(80), // 80 chars - "Another short one", // 17 chars - "G".repeat(80), // 80 chars - "Final short line", // 16 chars - ].join("\n"); - - const helper = createMockHelper(fileContents, 3); // Cursor on the long line (index 3) - - //@ts-ignore - const result = nextEditProvider._calculateOptimalEditableRegion( - helper, - "tokenizer", - ); - - // Should try to include equal number of lines above and below cursor - const linesAbove = result.editableRegionStartLine; - const linesBelow = - helper.fileLines.length - 1 - result.editableRegionEndLine; - - // Difference between lines above and below should be minimal - expect(Math.abs(linesAbove - linesBelow)).toBeLessThanOrEqual(1); - }); -}); diff --git a/core/nextEdit/providers/BaseNextEditProvider.ts b/core/nextEdit/providers/BaseNextEditProvider.ts index af8f77026..2a0bea8ed 100644 --- a/core/nextEdit/providers/BaseNextEditProvider.ts +++ b/core/nextEdit/providers/BaseNextEditProvider.ts @@ -19,6 +19,11 @@ import { } from "../types.js"; import { isWhitespaceOnlyDeletion } from "../utils.js"; +/** + * This class is used as an abstract base class for model-specific providers. + * This and its children are responsible for pre/post processing of prompts and outcomes. + * Different next edit models have very different requirements. + */ export abstract class BaseNextEditModelProvider { protected readonly modelName: string; diff --git a/extensions/vscode/src/activation/JumpManager.ts b/extensions/vscode/src/activation/JumpManager.ts index 2474f1e4e..5290cb4f3 100644 --- a/extensions/vscode/src/activation/JumpManager.ts +++ b/extensions/vscode/src/activation/JumpManager.ts @@ -66,6 +66,12 @@ export interface CompletionDataForAfterJump { currentPosition: vscode.Position; } +/** + * This is how we handle jumps and manage decoration object lifetime. + * There are mainly three states the user can be in: not jumping, jumping in progress, and just jumped. + * This can potentially be an enum for better readability, but there is logic here that relies on + * the _jumpAccepted flag to determine whether we should delete chains. + */ export class JumpManager { private static _instance: JumpManager | undefined; @@ -119,10 +125,6 @@ export class JumpManager { } private _createSvgJumpIcon() { - // if (!this._theme) { - // return; - // } - const baseTextConfig = { y: SVG_CONFIG.getTextY(), "font-family": SVG_CONFIG.getFontFamily(), @@ -130,6 +132,9 @@ export class JumpManager { }; try { + // NOTE: it's critical to use svgBuilder.newInstance. + // svgBuilder holds state of previously created SVGs, + // so you end up with SVGs stacking on top of each other and being interleaved. const builder = svgBuilder.newInstance ? svgBuilder.newInstance() : svgBuilder; @@ -295,15 +300,6 @@ export class JumpManager { 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("editor.foreground"), - // backgroundColor: new vscode.ThemeColor("editorHover.background"), - // margin: `0 0 0 4px`, - // }, - // }); - if (!this._jumpDecoration) { this._createSvgJumpIcon(); // makes both the icon & decoration } diff --git a/extensions/vscode/src/activation/NextEditWindowManager.ts b/extensions/vscode/src/activation/NextEditWindowManager.ts index 1279a95da..1c1da98fd 100644 --- a/extensions/vscode/src/activation/NextEditWindowManager.ts +++ b/extensions/vscode/src/activation/NextEditWindowManager.ts @@ -97,6 +97,11 @@ export const HIDE_NEXT_EDIT_SUGGESTION_COMMAND = export const ACCEPT_NEXT_EDIT_SUGGESTION_COMMAND = "continue.nextEditWindow.acceptNextEditSuggestion"; +/** + * This is where we create SVG windows and deletion decorations for non-FIM next edit suggestions. + * This class controls the decoration object lifetime. + * The syntax highlighting and the actual building of SVG happens inside core/codeRenderer/CodeRenderer.ts. + */ export class NextEditWindowManager { private static instance: NextEditWindowManager | undefined; @@ -492,9 +497,6 @@ export class NextEditWindowManager { this.mostRecentCompletionId = null; } - /** - * Accept the current next edit suggestion by inserting it at cursor position. - */ /** * Accept the current next edit suggestion by inserting it at cursor position. */ @@ -840,15 +842,6 @@ export class NextEditWindowManager { editor: vscode.TextEditor, position: vscode.Position, ): vscode.Position { - // Create a position that's offset spaces to the right of the cursor. - - // const line = editor.document.lineAt(position.line); - // const offsetChar = Math.min( - // position.character + SVG_CONFIG.cursorOffset, - // line.text.length, - // ); - // return new vscode.Position(position.line, offsetChar); - // Place decoration at the end of the current line const line = editor.document.lineAt(position.line); return new vscode.Position(position.line, line.text.length); diff --git a/extensions/vscode/src/activation/SelectionChangeManager.ts b/extensions/vscode/src/activation/SelectionChangeManager.ts index 100a373be..a80cc4439 100644 --- a/extensions/vscode/src/activation/SelectionChangeManager.ts +++ b/extensions/vscode/src/activation/SelectionChangeManager.ts @@ -106,6 +106,8 @@ interface HandlerRegistration { * - After current event is processed, queued events are handled sequentially. * - Ensures all events are processed in the order they were received. * - NOTE: I'm not sure if we even want to queue these events... + * + * Case n: Other cases that I didn't catch. */ export class SelectionChangeManager { private static instance: SelectionChangeManager; diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index add7c315b..d9901a3d0 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -141,6 +141,12 @@ export class ContinueCompletionProvider this.prefetchQueue.initialize(this.usingFullFileDiff); } + /** + * This is the entry point to the autocomplete and next edit logic. + * @param document The text document containing the current cursor position. + * @param position The current cursor position. + * @param context Contextual information about the inline completion request. + */ public async provideInlineCompletionItems( document: vscode.TextDocument, position: vscode.Position, @@ -154,6 +160,11 @@ export class ContinueCompletionProvider // 2. Jumping (chain exists, jump was taken) // 3. Accepting (chain exists, jump is not taken) + /* START OF CONTEXT GATHERING BOILERPLATE */ + + // The code in this block is meant for gathering context for autocomplete and next edit requests. + // e.g. filepath, cursor position, editor, notebook-ness, etc. + const enableTabAutocomplete = getStatusBarStatus() === StatusBarStatus.Enabled; if (token.isCancellationRequested || !enableTabAutocomplete) { @@ -279,12 +290,44 @@ export class ContinueCompletionProvider recentlyEditedRanges, }; + /* END OF CONTEXT GATHERING BOILERPLATE */ + + /* START OF MODEL OUTCOME RECEIVING BLOCK */ + + // Throughout this function, we choose whether we want an autocomplete or a next edit request. + // The conditional logic below is pretty convoluted, so it would be a good idea to refactor. + // The idea was to re-use as much code as possible, but in hindsight I should've just made different functions. + // this.isNextEditActive is the boolean that determines whether we use autocomplete vs. next edit. + + // You will also see mentions of this.usingFullFileDiff. + // This was initially a flag for whether we should let the model output a full file as an output (or to the best of its abilities). + // It ended up becoming a Mercury Coder vs. non-Mercury Coder flag, and is now used to determine whether we should prefetch next edits. + // This is a good place to refactor on. + // In the future, it will be desirable to have a map where we split models into different next edit requirements and capabilities, + // Then use the model's name to retrieve all of its requirements (or better yet, have a model-specific logic inside children class). + + // Prefetching is also a relic of the past. + // Before, I envisioned that we should call the model in the background to get next next edits. + // Due to subpar results, lack of satisfactory next edit location suggestion algorithms and token cost/latency issues, I scratched the idea. + let outcome: AutocompleteOutcome | NextEditOutcome | undefined; // TODO: We can probably decide here if we want to do the jumping logic. // If we aren't going to jump anyways, then we should be not be using the prefetch queue or the jump manager. // It would simplify the logic quite substantially. + // Here, we introduce the concept of jumping and chains. + // Jump and chain are next edit-specific concepts, and autocomplete has nothing to do with it. + // Next edit is rendered to the users in three modes: + // 1. Default. This is the case where the user either hasn't seen a next edit suggestion, or has rejected the previous one. + // We would render either a ghost text or an SVG with deletion decoration. + + // 2. Jumping. This is the case where the user has just accepted a suggestion, and there are more suggestions in the chain to jump to. + // We would render a Jump label suggesting the user to take the jump or reject. + + // 3. Jumped. This is when the user just accepted the jump. + // We grab the next edit suggestion from the chain and render that instead of calling the model. + // Determine why this method was triggered. const isJumping = this.jumpManager.isJumpInProgress(); const chainExists = this.nextEditProvider.chainExists(); @@ -363,8 +406,8 @@ export class ContinueCompletionProvider currentPosition: jumpPosition, }); - // Don't display anything yet. - // This will be handled in Case 2. + // Don't display anything yet. This will be handled in Case 2. + // Recall from above that provideInlineCompletions runs on every cursor movement. return undefined; } } @@ -378,7 +421,6 @@ export class ContinueCompletionProvider } } else { // Case 1: Typing (chain does not exist). - this.nextEditProvider.startChain(); const input: AutocompleteInput = { @@ -397,15 +439,14 @@ export class ContinueCompletionProvider { withChain: false, usingFullFileDiff: this.usingFullFileDiff }, ); - // Start prefetching next edits. - // NOTE: this might be better off not awaited. + // Start prefetching next edits if not using full file diff. + // NOTE: this is better off not awaited. fire and forget. if (!this.usingFullFileDiff) { this.prefetchQueue.process(ctx); } // If initial outcome is null, suggest a jump instead. - // Calling this method again will call it with - // chain active but jump not suggested yet. + // Calling this method again will call it with chain active but jump not suggested yet. if ( !outcome || (!outcome.completion && outcome.diffLines.length === 0) @@ -465,8 +506,8 @@ 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. + // NOTE: It seems like autocomplete relies on this to be considered accepted. if (this.isNextEditActive) { this.nextEditProvider.markDisplayed( completionId, @@ -480,6 +521,15 @@ export class ContinueCompletionProvider } this._lastShownCompletion = outcome; + /* END OF MODEL OUTCOME RECEIVING BLOCK */ + + /* START OF RENDERING BLOCK */ + + // Here we determine how to render the outcome received in the previous block. + // We check whether the outcome is a FIM completion or not. + // If FIM, we render a ghost text, and an SVG + deletion decoration if not. + // If we are using autocomplete instead of next edit, we just render a ghost text. + // Construct the range/text to show const startPos = selectedCompletionInfo?.range.start ?? position; let range = new vscode.Range(startPos, startPos); @@ -536,14 +586,6 @@ export class ContinueCompletionProvider const newEditRangeSlice = completionText; // Get the contents of the old (current) editable region. - // 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, - // editor.document.lineCount - 1, - // ); const editableRegionStartLine = (outcome as NextEditOutcome) .editableRegionStartLine; const editableRegionEndLine = (outcome as NextEditOutcome) @@ -581,10 +623,8 @@ export class ContinueCompletionProvider } // 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. + // Ghost text acceptance can *technically* be acted upon in the command handler for "continue.logNextEditOutcomeAccept". + // However, 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, @@ -640,6 +680,8 @@ export class ContinueCompletionProvider } finally { stopStatusBarLoading(); } + + /* END OF RENDERING BLOCK */ } willDisplay( diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index c6fbc803d..23ced0cc5 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -84,6 +84,12 @@ export class VsCodeExtension { private ARBITRARY_TYPING_DELAY = 2000; + /** + * This is how you turn next edit on or off at the extension level. + * This is called on config reload and autocomplete menu updates. + * This is also the place you want to check to enable/disable next edit during e2e tests, + * because it tends to stain other e2e tests and make them fail. + */ private async updateNextEditState( context: vscode.ExtensionContext, ): Promise { @@ -608,6 +614,8 @@ export class VsCodeExtension { .map((uri) => uri.toString()); this.core.invoke("files/opened", { uris: initialOpenedFilePaths }); + // This is how you would enable/disable next edit in the autocomplete menu. + // See extensions/vscode/src/autocomplete/statusBar.ts. vscode.workspace.onDidChangeConfiguration(async (event) => { if (event.affectsConfiguration(EXTENSION_NAME)) { const settings = await this.ide.getIdeSettings();