From e5708fcb822946ed3f1f2af025f20482c4e6f6eb Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Mon, 28 Jul 2025 15:08:54 -0700 Subject: [PATCH] refactor: clean up --- .../NextEditEditableRegionCalculator.ts | 6 +- core/nextEdit/NextEditPrefetchQueue.ts | 135 --------- core/nextEdit/NextEditProvider.ts | 272 +----------------- .../templating/NextEditPromptEngine.ts | 124 ++++---- core/nextEdit/types.ts | 3 +- core/util/PrefetchQueue.ts | 86 ------ .../GhostTextAcceptanceTracker.ts | 94 +----- .../src/autocomplete/completionProvider.ts | 75 ++--- .../vscode/src/extension/VsCodeExtension.ts | 22 +- 9 files changed, 108 insertions(+), 709 deletions(-) delete mode 100644 core/nextEdit/NextEditPrefetchQueue.ts delete mode 100644 core/util/PrefetchQueue.ts diff --git a/core/nextEdit/NextEditEditableRegionCalculator.ts b/core/nextEdit/NextEditEditableRegionCalculator.ts index 04c5247c3..a4dc04794 100644 --- a/core/nextEdit/NextEditEditableRegionCalculator.ts +++ b/core/nextEdit/NextEditEditableRegionCalculator.ts @@ -343,17 +343,15 @@ async function staticRerankJump(ctx: { // Static jump relies purely on static analysis // to determine where to edit next. async function staticJump(ctx: { - fileContent: string; cursorPosition: { line: number; character: number }; filepath: string; ide: IDE; }): Promise { try { - const { fileContent, cursorPosition, filepath, ide } = ctx; - if (!fileContent || !cursorPosition || !filepath || !ide) { + const { cursorPosition, filepath, ide } = ctx; + if (!cursorPosition || !filepath || !ide) { console.warn( "Missing required context for static jump:", - !fileContent, !cursorPosition, !filepath, !ide, diff --git a/core/nextEdit/NextEditPrefetchQueue.ts b/core/nextEdit/NextEditPrefetchQueue.ts deleted file mode 100644 index 54a43bc29..000000000 --- a/core/nextEdit/NextEditPrefetchQueue.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { ILLM, Position, RangeInFile } from ".."; -import { HelperVars } from "../autocomplete/util/HelperVars"; -import { findChangedLineRanges, myersDiff } from "../diff/myers"; -import { PrefetchQueue } from "../util/PrefetchQueue"; -import { applyCompletionToFile } from "./diff/diff"; -import { EditableRegionStrategy } from "./NextEditEditableRegionCalculator"; -import { NextEditOutcome } from "./types"; - -export class NextEditPrefetchQueue extends PrefetchQueue< - NextEditOutcome, - RangeInFile, - { - helper: HelperVars; - diffContext: string; - llm: ILLM; - token: AbortSignal; - startTime: number; - newCursorPos: Position; - editableRegionStrategy: EditableRegionStrategy; - } -> { - async initialize(): Promise { - const firstPromise = this.fetchFunction(undefined, undefined, this.other); - this.promiseQueue.push(firstPromise); - - const firstData = await firstPromise; - if (this.resourceQueue.length > 0) { - const resource = this.resourceQueue.shift()!; - const nextPromise = this.fetchFunction(firstData, resource, this.other); - this.promiseQueue.push(nextPromise); - } - - if (this.other?.editableRegionStrategy === EditableRegionStrategy.Naive) { - // Get the response from fetchFunction and compare with firstData to identify changed regions - const resource = - this.resourceQueue.length > 0 ? this.resourceQueue[0] : undefined; - const secondPromise = this.fetchFunction(firstData, resource, this.other); - const secondData = await secondPromise; - // console.log(secondData?.completion); - - // if (secondPromise) { - // Process this in the background - // secondPromise - // .then((secondData) => { - - if (firstData && secondData) { - // Use myersDiff to find differences between the two completions - // const firstCompletionLines = firstData.completion.split("\n"); - // const secondCompletionLines = secondData.completion.split("\n"); - - // TODO: this should be comparing old file and new file, not the completions. - // Compare the file after first completion is merged, - // and compare the file after first and second completion is merged. - const appliedFirst = applyCompletionToFile( - this.other.helper.fileContents, - firstData.completion, - firstData.editableRegionStartLine, - ); - // const appliedFirstAndSecond = applyCompletionToFile( - // appliedFirst, - // secondData.completion, - // secondData.editableRegionStartLine, - // ); - const diffLines = myersDiff(appliedFirst, secondData.completion); - - // Track chunks of differences - console.log(diffLines, appliedFirst, secondData.completion); - const changedLineRanges = findChangedLineRanges(diffLines); - changedLineRanges.forEach((change) => { - // Inclusive, zero-based line numbers. - const chunk = { - startLine: change.startLine, - endLine: change.endLine, - }; - console.log("chunk:", chunk); - const chunkOutcome: NextEditOutcome = { - ...firstData, - uniqueId: `${firstData.uniqueId}-chunk-${chunk.startLine}-${chunk.endLine}`, - editableRegionStartLine: chunk.startLine, - editableRegionEndLine: chunk.endLine, - }; - - this.promiseQueue.push(Promise.resolve(chunkOutcome)); - }); - } - } - } - - async pop(): Promise { - if (this.promiseQueue.length === 0) { - return undefined; - } - - if (this.other?.editableRegionStrategy === EditableRegionStrategy.Naive) { - // The queue should already be preloaded. - // We don't need to make extra calls to the model - // because we assume that the items already in the queue - // are the only items in this chain of edit. - const currentPromise = this.promiseQueue.shift()!; - - if (this.promiseQueue.length === 0) { - // NextEditProvider.currentEditChainId = null; - } - - return await currentPromise; - } - - // Get and remove the first promise from the queue - const currentPromise = this.promiseQueue.shift()!; - const currentData = await currentPromise; - - // If we have resources left, prefetch the next item - if (this.resourceQueue.length > 0) { - // Get the most recently added promise (now at the end of the queue) - const previousPromise = - this.promiseQueue.length > 0 - ? this.promiseQueue[this.promiseQueue.length - 1] - : Promise.resolve(currentData); - - // Create new promise based on the previous one and next resource - const resource = this.resourceQueue.shift()!; - const nextPromise = previousPromise.then((data) => - this.fetchFunction(data, resource, this.other), - ); - - this.promiseQueue.push(nextPromise); - } else if (this.promiseQueue.length === 0) { - // No more items in the queue and no more resources - // NextEditProvider.currentEditChainId = null; - } - - // console.log("currentData:", currentData); - return currentData; - } -} diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index b8512cd4e..f266b27bf 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -1,15 +1,7 @@ import * as path from "path"; import { v4 as uuidv4 } from "uuid"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { - BranchAndDir, - ChatMessage, - IDE, - ILLM, - Position, - Range, - RangeInFile, -} 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"; @@ -26,7 +18,6 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; -import { myersDiff } from "../diff/myers.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { @@ -34,17 +25,13 @@ import { NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, } from "./constants.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; -import { - calculateFinalCursorPosition, - getOffsetPositionAtLastNewLine, -} from "./diff/diff.js"; +import { calculateFinalCursorPosition } from "./diff/diff.js"; import { DocumentAstTracker } from "./DocumentHistoryTracker.js"; import { EditableRegionStrategy, getNextEditableRegion, } from "./NextEditEditableRegionCalculator.js"; import { NextEditLoggingService } from "./NextEditLoggingService.js"; -import { NextEditPrefetchQueue } from "./NextEditPrefetchQueue.js"; import { renderDefaultSystemPrompt, renderDefaultUserPrompt, @@ -56,7 +43,6 @@ import { PromptMetadata, RecentlyEditedRange, } from "./types.js"; -// import { renderPrompt } from "./templating/NextEditPromptEngine.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -81,8 +67,6 @@ export class NextEditProvider { private endpointType: "default" | "fineTuned"; private diffContext: string = ""; private promptMetadata: PromptMetadata | null = null; - private prefetchQueue: NextEditPrefetchQueue; - // private refQueue: RangeInFile[] = []; private currentEditChainId: string | null = null; private previousRequest: AutocompleteInput | null = null; private previousCompletions: NextEditOutcome[] = []; @@ -101,121 +85,6 @@ export class NextEditProvider { this.contextRetrievalService = new ContextRetrievalService(this.ide); this.endpointType = endpointType; this.loggingService = NextEditLoggingService.getInstance(); - - const fetchFunction = async ( - previousData: NextEditOutcome | undefined, - resource: RangeInFile | undefined, - other?: { - helper: HelperVars; - diffContext: string; - llm: ILLM; - token: AbortSignal; - startTime: number; - newCursorPos: Position; - editableRegionStrategy: EditableRegionStrategy; - }, - ) => { - if (!other) return undefined; - // console.log("previousData:", previousData?.completion); - // render prompt - // TODO: this has to set the editable region properly. - // console.log("fetchfunction - previousData:", previousData?.completion); - const promptMetadata = await renderPrompt( - other.helper, - other.diffContext, - other.editableRegionStrategy, - previousData, - resource, - ); - this.promptMetadata = promptMetadata; - // console.log("prompt:", promptMetadata.prompt); - // call llm.chat - const msg = await other.llm.chat([promptMetadata.prompt], other.token); - // built and return outcome - if (typeof msg.content === "string") { - if (msg.content === "") return undefined; - // NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined - const nextCompletion = replaceEscapedCharacters( - msg.content.split("<|editable_region_start|>\n")[1], - ).replace(/\n$/, ""); - - const currCursorPos = other.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, - other.helper.fileLines.length - 1, - ); - const oldEditRangeSlice = other.helper.fileContents - .split("\n") - .slice(editableRegionStartLine, editableRegionEndLine + 1) - .join("\n"); - - // 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 newEditRangeSlice = nextCompletion; - 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, - }; - - // TODO: if editable region strategy is naive, then we need to split the prediction up into regions. Also potentially filling up the prefetch queue. - - const outcomeNext: NextEditOutcome = { - elapsed: Date.now() - other.startTime, - modelProvider: other.llm.underlyingProviderName, - modelName: other.llm.model + ":zetaDataset", - completionOptions: null, - // filepath: helper.filepath, - completionId: other.helper.input.completionId, - gitRepo: await this.ide.getRepoName(other.helper.filepath), - uniqueId: await this.ide.getUniqueId(), - timestamp: Date.now(), - fileUri: other.helper.filepath, - workspaceDirUri: - other.helper.workspaceUris[0] ?? - path.dirname(other.helper.filepath), - fileContentsBeforeAccept: other.helper.fileContents, - prompt: this.promptMetadata!.prompt.content, - userEdits: this.promptMetadata!.userEdits, - userExcerpts: this.promptMetadata!.userExcerpts, - originalEditableRange: oldEditRangeSlice, - completion: nextCompletion, - cursorPosition: other.helper.pos, - finalCursorPosition: finalCursorPos, - editableRegionStartLine, - editableRegionEndLine, - ...other.helper.options, - }; - return outcomeNext; - } else { - return undefined; - } - }; - - this.prefetchQueue = new NextEditPrefetchQueue( - fetchFunction, - [], - undefined, - ); } public static initialize( @@ -350,9 +219,9 @@ export class NextEditProvider { this.nextEditableRegionsInTheCurrentChain = []; if (this.previousRequest) { - const fileContent = - // await fs.readFile(localPathOrUriToPath(this.previousRequest.filepath) - (await this.ide.readFile(this.previousRequest.filepath)).toString(); + const fileContent = ( + await this.ide.readFile(this.previousRequest.filepath) + ).toString(); const ast = await getAst(this.previousRequest.filepath, fileContent); if (ast) { DocumentAstTracker.getInstance().pushAst( @@ -452,10 +321,8 @@ export class NextEditProvider { }); const promptMetadata = await renderPrompt( helper, - // this.diffContext, historyDiff ?? this.diffContext, EditableRegionStrategy.Naive, - // input.recentlyEditedRanges, ); this.promptMetadata = promptMetadata; @@ -509,7 +376,6 @@ export class NextEditProvider { fileUri: helper.filepath, workspaceDirUri: helper.workspaceUris[0] ?? path.dirname(helper.filepath), - fileContentsBeforeAccept: helper.fileContents, prompt: prompts.join("\n"), userEdits: "", userExcerpts: "", @@ -546,8 +412,6 @@ export class NextEditProvider { ).replace(/\n$/, "") : ""; - // this.previousCompletions.push(nextCompletion); - const currCursorPos = helper.pos; const editableRegionStartLine = Math.max( currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, @@ -566,7 +430,6 @@ export class NextEditProvider { helper.pos, editableRegionStartLine, oldEditRangeSlice, - // "", nextCompletion, ); @@ -583,7 +446,6 @@ export class NextEditProvider { fileUri: helper.filepath, workspaceDirUri: helper.workspaceUris[0] ?? path.dirname(helper.filepath), - fileContentsBeforeAccept: helper.fileContents, prompt: this.promptMetadata!.prompt.content, userEdits: this.promptMetadata!.userEdits, userExcerpts: this.promptMetadata!.userExcerpts, @@ -632,32 +494,18 @@ export class NextEditProvider { }, token: AbortSignal | undefined, ) { - // TODO: - // If we don't have a precomputed list of next editable regions already, compute it. - // Store this list as a class attribute. - // Pop the frontmost RangeInFile and use that to build an input. try { const previousOutcome = this.getPreviousCompletion(); if (!previousOutcome) { return undefined; } - // TODO: This is actually getting the contents after the user typed something. - // we need the file before the user has typed anything. - // console.log("previousOutcome:", previousOutcome.fileContentsBeforeAccept); - // console.log("previousCursorPosition:", previousOutcome.cursorPosition); - const fileContent = previousOutcome.fileContentsBeforeAccept; const filepath = localPathOrUriToPath(previousOutcome.fileUri); - console.log( - "number of next editable regions:", - this.nextEditableRegionsInTheCurrentChain.length, - ); + // If we don't have a precomputed list of next editable regions already, compute and load it. if (this.nextEditableRegionsInTheCurrentChain.length === 0) { - console.log("empty next editable regions list"); this.loadNextEditableRegionsInTheCurrentChain( (await getNextEditableRegion(EditableRegionStrategy.Static, { - fileContent, cursorPosition: previousOutcome.cursorPosition, filepath, ide: this.ide, @@ -670,6 +518,7 @@ export class NextEditProvider { } } + // Use the frontmost RangeInFile to build an input. const input = await this.buildAutocompleteInputFromChain( previousOutcome, this.nextEditableRegionsInTheCurrentChain[0], // this will be shifted after debouncer check @@ -715,117 +564,10 @@ export class NextEditProvider { } public loadNextEditableRegionsInTheCurrentChain(regions: RangeInFile[]) { - console.log("regions after load:", regions.length); this.nextEditableRegionsInTheCurrentChain = regions; } public shiftNextEditableRegionsInTheCurrentChain() { - console.log("shift", this.nextEditableRegionsInTheCurrentChain.length); this.nextEditableRegionsInTheCurrentChain.shift(); } - - public async provideNextEditPrediction( - input: AutocompleteInput, - token: AbortSignal | undefined, - ) { - try { - if (this.currentEditChainId) { - return await this.prefetchQueue.pop(); - } - - // Create abort signal if not given - if (!token) { - const controller = this.loggingService.createAbortController( - input.completionId, - ); - token = controller.signal; - } - const startTime = Date.now(); - const options = await this._getAutocompleteOptions(); - - // Debounce - if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { - return undefined; - } - - const llm = await this._prepareLlm(); - if (!llm) { - return undefined; - } - - if (llm.promptTemplates?.autocomplete) { - options.template = llm.promptTemplates.autocomplete as string; - } - - const helper = await HelperVars.create( - input, - options, - llm.model, - this.ide, - ); - - if (await shouldPrefilter(helper, this.ide)) { - return undefined; - } - - // this.currentEditChainId = randomUUID(); - - this.prefetchQueue.loadOther({ - helper, - diffContext: this.diffContext, - llm, - token, - startTime, - newCursorPos: helper.pos, - editableRegionStrategy: EditableRegionStrategy.Naive, - }); - - const [snippetPayload, workspaceDirs] = await Promise.all([ - getAllSnippetsWithoutRace({ - helper, - ide: this.ide, - getDefinitionsFromLsp: this.getDefinitionsFromLsp, - contextRetrievalService: this.contextRetrievalService, - }), - this.ide.getWorkspaceDirs(), - ]); - - // TODO: Get the references. - const refQueue = await this.ide.getReferences({ - filepath: helper.filepath, - position: helper.pos, - }); - - const { config } = await this.configHandler.loadConfig(); - const branches = await Promise.all( - workspaceDirs.map((dir) => this.ide.getBranch(dir)), - ); - const tags: BranchAndDir[] = workspaceDirs.map((directory, i) => ({ - directory, - branch: branches[i], - })); - // const chunks = await getTopRelevantCodeChunks( - // ` add(number) { - // this.result += number; - // return this; - // }`, - // { - // ide: this.ide, - // llm: llm, - // config: config!, - // tags: tags, - // // filterDirectory: getUriPathBasename(helper.workspaceUris[0]), - // }, - // ); - // console.log("chunks:", JSON.stringify(chunks, null, 2)); - - this.prefetchQueue.loadResource(refQueue); - await this.prefetchQueue.initialize(); - return await this.prefetchQueue.pop(); - } catch (e: any) { - this.onError(e); - } finally { - this.loggingService.deleteAbortController(input.completionId); - } - } } diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 01a18ac7f..d6cd8dacf 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -9,11 +9,7 @@ import { NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; -import { createDiff, DiffFormatType } from "../context/diffFormatting"; -import { - EditableRegionStrategy, - getNextEditableRegion, -} from "../NextEditEditableRegionCalculator"; +import { EditableRegionStrategy } from "../NextEditEditableRegionCalculator"; import { NextEditOutcome, NextEditTemplate, @@ -94,67 +90,67 @@ export async function renderPrompt( // TODO: apply prevOutcome to existing content. we will need the line range. // Also display the diff between existing content and applied content. // NOTE: This only runs in fetchFunction. - if (prevOutcome) { - // console.log("renderPrompt prevOutcome:", prevOutcome.completion); - // console.log( - // "beforeInsert:", - // helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), - // ); - // console.log("toInsert: ", prevOutcome?.completion.split("\n")); - // console.log( - // "afterInsert:", - // helper.fileLines.slice(prevOutcome?.editableRegionEndLine), - // ); - let appliedContent = [ - ...helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), - ...(prevOutcome?.completion.split("\n") ?? []), - ...helper.fileLines.slice(prevOutcome?.editableRegionEndLine), - ]; - // console.log("helper.fileContents:", helper.fileContents); - // NOTE: I'm not sure, but <|user_cursor_is_here|> is somehow being added to appliedContent. - // The individual parts don't contain this. - // console.log("appliedContent:", appliedContent); - appliedContent = appliedContent.filter( - (line) => !line.includes(USER_CURSOR_IS_HERE_TOKEN), - ); - // Given a previous response, we need to calculate where the cursor would be. - // I think it's a good idea to calculate this in the response. + // if (prevOutcome) { + // // console.log("renderPrompt prevOutcome:", prevOutcome.completion); + // // console.log( + // // "beforeInsert:", + // // helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), + // // ); + // // console.log("toInsert: ", prevOutcome?.completion.split("\n")); + // // console.log( + // // "afterInsert:", + // // helper.fileLines.slice(prevOutcome?.editableRegionEndLine), + // // ); + // let appliedContent = [ + // ...helper.fileLines.slice(0, prevOutcome?.editableRegionStartLine), + // ...(prevOutcome?.completion.split("\n") ?? []), + // ...helper.fileLines.slice(prevOutcome?.editableRegionEndLine), + // ]; + // // console.log("helper.fileContents:", helper.fileContents); + // // NOTE: I'm not sure, but <|user_cursor_is_here|> is somehow being added to appliedContent. + // // The individual parts don't contain this. + // // console.log("appliedContent:", appliedContent); + // appliedContent = appliedContent.filter( + // (line) => !line.includes(USER_CURSOR_IS_HERE_TOKEN), + // ); + // // Given a previous response, we need to calculate where the cursor would be. + // // I think it's a good idea to calculate this in the response. - // TODO: handle cases where there are more than one next editable region. - // NOTE: we might set it so that we receive the next editable region as an argument. - const editableRegion = await getNextEditableRegion(editableRegionStrategy, { - fileLines: appliedContent, - filepath: helper.filepath, - }); + // // TODO: handle cases where there are more than one next editable region. + // // NOTE: we might set it so that we receive the next editable region as an argument. + // const editableRegion = await getNextEditableRegion(editableRegionStrategy, { + // fileLines: appliedContent, + // filepath: helper.filepath, + // }); - // console.log("appliedContent:", appliedContent); - // console.log("startLine:", editableRegion?.range.start.line); - editedCodeWithTokens = insertTokens( - appliedContent, - prevOutcome.finalCursorPosition, - editableRegion && editableRegion[0]?.range.start.line !== undefined - ? editableRegion[0].range.start.line - : undefined, - editableRegion && editableRegion[0]?.range.end.line !== undefined - ? editableRegion[0].range.end.line - : undefined, - ); - // console.log("new editedCodeWithTokens:", editedCodeWithTokens); - userEdits = createDiff({ - beforeContent: helper.fileContents, - afterContent: appliedContent.join("\n"), - filePath: helper.filepath, - diffType: DiffFormatType.Unified, - contextLines: 3, - }); - userEdits = userEdits.replace(USER_CURSOR_IS_HERE_TOKEN, ""); - // console.log("new userDiff:", userEdits); - } else { - editedCodeWithTokens = insertTokens( - helper.fileContents.split("\n"), - helper.pos, - ); - } + // // console.log("appliedContent:", appliedContent); + // // console.log("startLine:", editableRegion?.range.start.line); + // editedCodeWithTokens = insertTokens( + // appliedContent, + // prevOutcome.finalCursorPosition, + // editableRegion && editableRegion[0]?.range.start.line !== undefined + // ? editableRegion[0].range.start.line + // : undefined, + // editableRegion && editableRegion[0]?.range.end.line !== undefined + // ? editableRegion[0].range.end.line + // : undefined, + // ); + // // console.log("new editedCodeWithTokens:", editedCodeWithTokens); + // userEdits = createDiff({ + // beforeContent: helper.fileContents, + // afterContent: appliedContent.join("\n"), + // filePath: helper.filepath, + // diffType: DiffFormatType.Unified, + // contextLines: 3, + // }); + // userEdits = userEdits.replace(USER_CURSOR_IS_HERE_TOKEN, ""); + // // console.log("new userDiff:", userEdits); + // } else { + editedCodeWithTokens = insertTokens( + helper.fileContents.split("\n"), + helper.pos, + ); + // } const tv: TemplateVars = { userEdits, diff --git a/core/nextEdit/types.ts b/core/nextEdit/types.ts index e4ae1f328..26e2b156a 100644 --- a/core/nextEdit/types.ts +++ b/core/nextEdit/types.ts @@ -47,10 +47,9 @@ export interface NextEditOutcome extends TabAutocompleteOptions { // New for Next Edit. fileUri: string; workspaceDirUri: string; - fileContentsBeforeAccept: string; prompt: string; userEdits: string; - userExcerpts: string; // For now, this is the same as fileContentsBeforeAccept, but that assumption should not be relied on. + userExcerpts: string; originalEditableRange: string; completion: string; cursorPosition: { line: number; character: number }; diff --git a/core/util/PrefetchQueue.ts b/core/util/PrefetchQueue.ts deleted file mode 100644 index 91a240dcc..000000000 --- a/core/util/PrefetchQueue.ts +++ /dev/null @@ -1,86 +0,0 @@ -export class PrefetchQueue { - protected promiseQueue: Promise[] = []; - protected resourceQueue: R[]; - protected other: O | undefined; - protected fetchFunction: ( - previousData: T | undefined, - resource: R | undefined, - other: O | undefined, - ) => Promise; - - constructor( - fetchFunction: ( - previousData: T | undefined, - resource: R | undefined, - other: O | undefined, - ) => Promise, - resources: R[], - other: O | undefined, - ) { - this.fetchFunction = fetchFunction; - this.resourceQueue = [...resources]; - this.other = other; - } - - loadResource(resources: R[]) { - this.resourceQueue = [...this.resourceQueue, ...resources]; - } - - loadOther(other: O) { - this.other = other; - } - - async initialize(): Promise { - // Get the first response (no resource needed) - const firstPromise = this.fetchFunction(undefined, undefined, this.other); - this.promiseQueue.push(firstPromise); - - // Prefetch the next item using the first resource - const firstData = await firstPromise; - if (this.resourceQueue.length > 0) { - const resource = this.resourceQueue.shift()!; - const nextPromise = this.fetchFunction(firstData, resource, this.other); - this.promiseQueue.push(nextPromise); - } - } - - async pop(): Promise { - if (this.promiseQueue.length === 0) { - return undefined; - } - - // Get and remove the first promise from the queue - const currentPromise = this.promiseQueue.shift()!; - const currentData = await currentPromise; - - // If we have resources left, prefetch the next item - if (this.resourceQueue.length > 0) { - // Get the most recently added promise (now at the end of the queue) - const previousPromise = - this.promiseQueue.length > 0 - ? this.promiseQueue[this.promiseQueue.length - 1] - : Promise.resolve(currentData); - - // Create new promise based on the previous one and next resource - const resource = this.resourceQueue.shift()!; - const nextPromise = previousPromise.then((data) => - this.fetchFunction(data, resource, this.other), - ); - - this.promiseQueue.push(nextPromise); - } else if (this.promiseQueue.length === 0) { - // No more items in the queue and no more resources - } - - console.log("currentData:", currentData); - return currentData; - } - - hasNext(): boolean { - return this.promiseQueue.length > 0; - } - - getRemainingResourceCount(): number { - return this.resourceQueue.length; - } -} diff --git a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts index 610a3c7fe..f40047c4f 100644 --- a/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts +++ b/extensions/vscode/src/autocomplete/GhostTextAcceptanceTracker.ts @@ -1,83 +1,3 @@ -// export class CompletionAcceptanceTracker { -// private static instance: CompletionAcceptanceTracker; -// private acceptedCompletionIds: Set = new Set(); - -// static getInstance(): CompletionAcceptanceTracker { -// if (!CompletionAcceptanceTracker.instance) { -// CompletionAcceptanceTracker.instance = new CompletionAcceptanceTracker(); -// } -// return CompletionAcceptanceTracker.instance; -// } - -// markGhostTextAccepted(completionId: string) { -// this.acceptedCompletionIds.add(completionId); - -// // Keep a reasonable history size -// if (this.acceptedCompletionIds.size > 1) { -// // Remove the oldest item (using the fact that Sets maintain insertion order) -// const oldestId = this.acceptedCompletionIds.values().next().value; -// if (oldestId) { -// this.acceptedCompletionIds.delete(oldestId); -// } -// } -// } - -// wasCompletionAccepted(completionId: string): boolean { -// return this.acceptedCompletionIds.has(completionId); -// } - -// // Add a method to check if the most recent completion was accepted -// wasRecentCompletionAccepted(): boolean { -// return this.acceptedCompletionIds.size > 0; -// } -// } -// In completionAcceptanceTracker.ts -// export class CompletionAcceptanceTracker { -// private static instance: CompletionAcceptanceTracker; -// private acceptedCompletionIds: Set = new Set(); -// private currentCompletionId: string | null = null; - -// static getInstance(): CompletionAcceptanceTracker { -// if (!CompletionAcceptanceTracker.instance) { -// CompletionAcceptanceTracker.instance = new CompletionAcceptanceTracker(); -// } -// return CompletionAcceptanceTracker.instance; -// } - -// setCurrentCompletionId(completionId: string) { -// this.currentCompletionId = completionId; -// } - -// markGhostTextAccepted(completionId: string) { -// console.log("mark"); -// this.acceptedCompletionIds.add(completionId); - -// // Keep a reasonable history size -// if (this.acceptedCompletionIds.size > 1) { -// // Remove the oldest item (using the fact that Sets maintain insertion order) -// const oldestId = this.acceptedCompletionIds.values().next().value; -// if (oldestId) { -// this.acceptedCompletionIds.delete(oldestId); -// } -// } -// } - -// wasCompletionAccepted(completionId: string): boolean { -// return this.acceptedCompletionIds.has(completionId); -// } - -// isCurrentCompletionAccepted(): boolean { -// return ( -// this.currentCompletionId !== null && -// this.acceptedCompletionIds.has(this.currentCompletionId) -// ); -// } - -// clearCurrentCompletionId() { -// this.currentCompletionId = null; -// } -// } -// New file: extensions/vscode/src/activation/GhostTextAcceptanceTracker.ts import * as vscode from "vscode"; export interface ExpectedGhostTextAcceptance { @@ -142,26 +62,26 @@ export class GhostTextAcceptanceTracker { ): boolean { if (!this.expectedAcceptance) return false; - // Check document match + // Check document match. if (this.expectedAcceptance.documentUri !== document.uri.toString()) { return false; } - // Check document version (must be newer) + // Check document version (must be newer). if (document.version <= this.expectedAcceptance.documentVersion) { return false; } - // Check if cursor is at expected end position + // 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 + // The cursor is where we'd expect after accepting the ghost text. - // Verify text was inserted (optional additional check) + // Verify text was inserted (optional additional check). const startPos = new vscode.Position( this.expectedAcceptance.startLine, this.expectedAcceptance.startCharacter, @@ -174,12 +94,12 @@ export class GhostTextAcceptanceTracker { const actualText = document.getText(actualRange); if (actualText === expectedText) { - // Clear the expectation + // Clear the expectation. this.expectedAcceptance = null; return true; } } catch (error) { - // Range might be invalid, just fall through + // Range might be invalid, just fall through. } } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 4919377c9..5e22b5c7e 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"; @@ -72,8 +70,6 @@ export class ContinueCompletionProvider public recentlyVisitedRanges: RecentlyVisitedRangesService; public recentlyEditedTracker: RecentlyEditedTracker; - private oldFileContent: string = ""; - private isNextEditActive: boolean = false; public activateNextEdit() { @@ -140,14 +136,6 @@ export class ContinueCompletionProvider token: vscode.CancellationToken, //@ts-ignore ): ProviderResult { - console.log("================================================"); - console.log( - "editor.inlineSuggest.enabled:", - vscode.workspace - .getConfiguration() - .get("editor.inlineSuggest.enabled"), - ); - // console.log("trigger!!", token.isCancellationRequested); const enableTabAutocomplete = getStatusBarStatus() === StatusBarStatus.Enabled; if (token.isCancellationRequested || !enableTabAutocomplete) { @@ -247,15 +235,9 @@ export class ContinueCompletionProvider const recentlyVisitedRanges = this.recentlyVisitedRanges.getSnippets(); let recentlyEditedRanges = await this.recentlyEditedTracker.getRecentlyEditedRanges(); - // console.log("one:", JSON.stringify(recentlyEditedRanges, null, 2)); - console.log( - this.nextEditProvider.chainExists() - ? "chain is alive" - : "chain is not alive", - ); if (this.nextEditProvider.chainExists()) { - // If the user has accepted the previous completion, the chain of edits is alive. + // 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( @@ -288,6 +270,7 @@ export class ContinueCompletionProvider }; setupStatusBar(undefined, true); + // Check if editChainId exists or needs to be refreshed. if (this.isNextEditActive) { outcome = await this.nextEditProvider.provideInlineCompletionItems( @@ -295,17 +278,16 @@ export class ContinueCompletionProvider signal, false, ); - console.log("outcome.completion:"); - console.log(outcome?.completion); + if (!outcome || !outcome.completion) { - // TODO: At this point we assume that the user typed something "whole". - // AKA, the user's edit was good enough to start an edit chain. - // We actually started the chain before getting the outcome. This makes logical sense. - // Then all we need to do is to calculate next editable region. + // 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(); - // console.log("two:", JSON.stringify(recentlyEditedRanges, null, 2)); + outcome = await this.nextEditProvider.provideInlineCompletionItemsWithChain( { @@ -321,6 +303,7 @@ export class ContinueCompletionProvider ); } } else { + // Handle autocomplete request. outcome = await this.completionProvider.provideInlineCompletionItems( input, signal, @@ -329,21 +312,8 @@ export class ContinueCompletionProvider } } - this.oldFileContent = document.getText(); - - // TODO: fix type of outcome to be a union between NextEditOutcome and AutocompleteOutcome. - // const outcome: AutocompleteOutcome | NextEditOutcome | undefined = this - // .isNextEditActive - // ? await this.nextEditProvider.provideInlineCompletionItems( - // input, - // signal, - // ) - // : 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; } @@ -374,8 +344,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. if (this.isNextEditActive) { this.nextEditProvider.markDisplayed( completionId, @@ -394,7 +364,6 @@ export class ContinueCompletionProvider let range = new vscode.Range(startPos, startPos); let completionText = outcome.completion; - // NOTE: This seems like an autocomplete logic. const isSingleLineCompletion = outcome.completion.split("\n").length <= 1; if (isSingleLineCompletion) { @@ -445,14 +414,14 @@ export class ContinueCompletionProvider const currCursorPos = editor.selection.active; if (this.isNextEditActive) { - console.log(this.nextEditProvider.getChain().length); - 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, @@ -461,7 +430,7 @@ export class ContinueCompletionProvider // If a jump was just suggested, don't show ghost text yet. if (this.jumpManager.isJumpInProgress()) { - // Store this completion for later use when jump is complete. + // Store this completion to be rendered after jump is complete. this.jumpManager.setCompletionAfterJump({ completionId: completionId, outcome: outcome as NextEditOutcome, @@ -516,8 +485,6 @@ export class ContinueCompletionProvider newEditRangeSlice, relativeCursorPos, ); - console.log("isFim:", isFim); - console.log("fimText:", fimText); if (isFim) { if (!fimText) { @@ -526,9 +493,12 @@ export class ContinueCompletionProvider return undefined; } - // const completionId = input.completionId; - // 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, @@ -544,10 +514,9 @@ export class ContinueCompletionProvider { title: "Log Next Edit Outcome", command: "continue.logNextEditOutcomeAccept", - arguments: [completionId, this.nextEditLoggingService], // TODO: this may have to be this.completionProvider. + arguments: [completionId, this.nextEditLoggingService], }, ); - console.log(nextEditCompletionItem); return [nextEditCompletionItem]; } diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 776c59843..94bf619df 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -419,20 +419,15 @@ export class VsCodeExtension { } }); - // TODO: check if next edit provider's chain id is cleared properly. // 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. - // console.log( - // "deleteChain from VsCodeExtension.ts: onDidChangeVisibleTextEditors", - // ); await NextEditProvider.getInstance().deleteChain(); }); // Listen for selection changes to hide tooltip when cursor moves. vscode.window.onDidChangeTextEditorSelection(async (e) => { - // console.log("move detected"); - // Don't delete the chain if: + // Don't delete the chain of edits if: // 1. A next edit window was just accepted. if ( @@ -461,21 +456,22 @@ export class VsCodeExtension { } // 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 + // Check if this selection change is close enough to a document change to be considered typing. const timeSinceLastDocChange = Date.now() - this.lastDocumentChangeTime; - if (this.isTypingSession && timeSinceLastDocChange < 500) { - // This selection change is likely due to typing, don't delete the chain + 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). - console.log( - "deleteChain from VsCodeExtension.ts: onDidChangeTextEditorSelection", - ); await NextEditProvider.getInstance().deleteChain(); + NextEditProvider.getInstance().loadNextEditableRegionsInTheCurrentChain( (await getNextEditableRegion(EditableRegionStrategy.Static, { - fileContent: e.textEditor.document.getText(), cursorPosition: e.selections[0].anchor, filepath: localPathOrUriToPath(e.textEditor.document.uri.toString()), ide: this.ide,