From 64e50ec1fa050e2ac0568c6f04eae7010a03bd9b Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 11 Sep 2024 10:08:20 -0700 Subject: [PATCH] use lazy edit in apply --- core/autocomplete/lineStream.ts | 16 +- core/core.ts | 2 +- core/diff/util.ts | 34 ++-- core/edit/lazy/prompts.ts | 51 +++++ core/edit/lazy/streamLazyApply.ts | 184 ++++++++++++++++++ .../streamDiffLines.ts} | 2 +- .../src/diff/verticalPerLine/manager.ts | 71 ++++++- .../vscode/src/extension/VsCodeMessenger.ts | 39 ++-- 8 files changed, 364 insertions(+), 35 deletions(-) create mode 100644 core/edit/lazy/prompts.ts create mode 100644 core/edit/lazy/streamLazyApply.ts rename core/{util/verticalEdit.ts => edit/streamDiffLines.ts} (98%) diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index e7d3493bd..56d0fb12d 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -1,6 +1,6 @@ import { distance } from "fastest-levenshtein"; -import { LineStream } from "../diff/util"; import { DiffLine } from "../"; +import { LineStream } from "../diff/util"; export type LineFilter = (args: { lines: LineStream; @@ -238,9 +238,10 @@ export async function* stopAtSimilarLine( export async function* stopAtLines( stream: LineStream, fullStop: () => void, + linesToStopAt: string[] = LINES_TO_STOP_AT, ): LineStream { for await (const line of stream) { - if (LINES_TO_STOP_AT.some((stopAt) => line.trim().includes(stopAt))) { + if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) { fullStop(); break; } @@ -382,6 +383,17 @@ export async function* filterEnglishLinesAtEnd(lines: LineStream) { } } +export async function* filterLeadingNewline(lines: LineStream): LineStream { + let firstLine = true; + for await (const line of lines) { + if (firstLine && line.trim() === "") { + firstLine = false; + continue; + } + yield line; + } +} + /** * Removes leading indentation from the first line of a CodeLlama output. * @param {LineStream} lines - The input stream of lines. diff --git a/core/core.ts b/core/core.ts index ad72a44ce..55502b317 100644 --- a/core/core.ts +++ b/core/core.ts @@ -14,6 +14,7 @@ import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFile import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; import { ControlPlaneClient } from "./control-plane/client"; +import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import Ollama from "./llm/llms/Ollama"; @@ -27,7 +28,6 @@ import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; -import { streamDiffLines } from "./util/verticalEdit"; export class Core { // implements IMessenger diff --git a/core/diff/util.ts b/core/diff/util.ts index 0e24ee373..685a29a43 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -93,19 +93,31 @@ export function matchLine( */ export async function* streamLines( streamCompletion: AsyncGenerator, + log: boolean = false, ): LineStream { + let allLines = []; + let buffer = ""; - for await (const update of streamCompletion) { - const chunk = - typeof update === "string" ? update : stripImages(update.content); - buffer += chunk; - const lines = buffer.split("\n"); - buffer = lines.pop() ?? ""; - for (const line of lines) { - yield line; + + try { + for await (const update of streamCompletion) { + const chunk = + typeof update === "string" ? update : stripImages(update.content); + buffer += chunk; + const lines = buffer.split("\n"); + buffer = lines.pop() ?? ""; + for (const line of lines) { + yield line; + allLines.push(line); + } + } + if (buffer.length > 0) { + yield buffer; + allLines.push(buffer); + } + } finally { + if (log) { + console.log("Streamed lines: ", allLines.join("\n")); } } - if (buffer.length > 0) { - yield buffer; - } } diff --git a/core/edit/lazy/prompts.ts b/core/edit/lazy/prompts.ts new file mode 100644 index 000000000..ee2c668c7 --- /dev/null +++ b/core/edit/lazy/prompts.ts @@ -0,0 +1,51 @@ +import { ChatMessage, ModelProvider } from "../.."; +import { dedent } from "../../util"; + +export const UNCHANGED_CODE = "UNCHANGED CODE"; + +type LazyApplyPrompt = ( + oldCode: string, + filename: string, + newCode: string, +) => ChatMessage[]; + +function claude35SonnetLazyApplyPrompt( + ...args: Parameters +): ReturnType { + const userContent = dedent` + ORIGINAL CODE: + \`\`\`${args[1]} + ${args[0]} + \`\`\` + + NEW CODE: + \`\`\` + ${args[2]} + \`\`\` + + Above is a code block containing the original version of a file (ORIGINAL CODE) and below it is a code snippet (NEW CODE) that was suggested as modification to the original file. + + Your task is to apply the NEW CODE to the ORIGINAL CODE and show what the entire file would look like after it is applied. Your response should be a code block containing a new version of the entire file. Whenever any part of the code is the same as before, you may simply indicate this with a comment that says "${UNCHANGED_CODE}" instead of rewriting. You may do this for imports as well if needed. Do not explain your changes either before or after the code block. + `; + + const assistantContent = dedent` + Sure! Here's the modified version of the file after applying the new code: + \`\`\`${args[1]} + `; + + return [ + { role: "user", content: userContent }, + { role: "assistant", content: assistantContent }, + ]; +} + +export function lazyApplyPromptForModel( + model: string, + provider: ModelProvider, +): LazyApplyPrompt | undefined { + if (model.includes("sonnet")) { + return claude35SonnetLazyApplyPrompt; + } + + return undefined; +} diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts new file mode 100644 index 000000000..648a32868 --- /dev/null +++ b/core/edit/lazy/streamLazyApply.ts @@ -0,0 +1,184 @@ +import { + filterLeadingAndTrailingNewLineInsertion, + filterLeadingNewline, + stopAtLines, +} from "../../autocomplete/lineStream.js"; +import { streamDiff } from "../../diff/streamDiff.js"; +import { LineStream, streamLines } from "../../diff/util.js"; +import { DiffLine, ILLM } from "../../index.js"; +import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js"; + +export async function* streamLazyApply( + oldCode: string, + filename: string, + newCode: string, + llm: ILLM, +): AsyncGenerator { + const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName); + if (!promptFactory) { + throw new Error(`Lazy apply not supported for model ${llm.model}`); + } + + const promptMessages = promptFactory(oldCode, filename, newCode); + const lazyCompletion = llm.streamChat(promptMessages); + + // Do find and replace over the lazy edit response + async function replacementFunction( + oldCode: string, + linesBefore: string[], + linesAfter: string[], + ): Promise { + let r = getReplacementByMatching(oldCode, linesBefore, linesAfter); + if (r) { + return r; + } + r = await getReplacementWithLlm(oldCode, linesBefore, linesAfter, llm); + if (r) { + return r; + } + return "// NO REPLACEMENT FOUND"; + } + let lazyCompletionLines = streamLines(lazyCompletion, true); + // Process line output + // lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines); + lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]); + lazyCompletionLines = filterLeadingNewline(lazyCompletionLines); + + // Fill in unchanged code + let lines = streamFillUnchangedCode( + lazyCompletionLines, + oldCode, + replacementFunction, + ); + + // Convert output to diff + const oldLines = oldCode.split(/\r?\n/); + let diffLines = streamDiff(oldLines, lines); + diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines); + for await (const diffLine of diffLines) { + yield diffLine; + } +} + +const BUFFER_LINES_BELOW = 2; +async function* streamFillUnchangedCode( + lines: LineStream, + oldCode: string, + replacementFunction: ( + oldCode: string, + linesBefore: string[], + linesAfter: string[], + ) => Promise, +): LineStream { + const newLines = []; + let buffer = []; + let waitingForBuffer = false; + + for await (const line of lines) { + if (waitingForBuffer) { + buffer.push(line); + + if (buffer.length >= BUFFER_LINES_BELOW) { + // Find the replacement and continue streaming once we have it + const replacement = await replacementFunction( + oldCode, + newLines, + buffer, + ); + for (const replacementLine of replacement.split("\n")) { + yield replacementLine; + newLines.push(replacementLine); + } + + console.log("FOUND REPLACEMENT:\n", replacement); + + // Yield the buffered lines + for (const bufferedLine of buffer) { + yield bufferedLine; + newLines.push(bufferedLine); + } + + waitingForBuffer = false; + buffer = []; + } else { + continue; + } + } + + if (line.includes(UNCHANGED_CODE)) { + // Buffer so we can give the context of BUFFER_LINES_BELOW lines below + waitingForBuffer = true; + // TODO: If the UNCHANGED CODE is at the very top of the file we need to handle a bit differently + } else { + yield line; + newLines.push(line); + } + } + + if (waitingForBuffer) { + // If we're still waiting for a buffer, we've reached the end of the stream + // and we should just look for the replacement with what we have + const replacement = await replacementFunction(oldCode, newLines, buffer); + for (const replacementLine of replacement.split("\n")) { + yield replacementLine; + newLines.push(replacementLine); + } + // Yield the buffered lines + for (const bufferedLine of buffer) { + yield bufferedLine; + newLines.push(bufferedLine); + } + } +} + +const MATCH_LINES_ABOVE = 1; +function getReplacementByMatching( + oldCode: string, + linesBefore: string[], + linesAfter: string[], +): string | undefined { + const oldLines = oldCode.split("\n"); + const linesToMatchAbove = MATCH_LINES_ABOVE; + const linesToMatchBelow = Math.min(BUFFER_LINES_BELOW, linesAfter.length); + + // Get surrounding lines around the gap + const beforeContext = linesBefore.slice(-linesToMatchAbove).join("\n"); + const afterContext = linesAfter.slice(0, linesToMatchBelow).join("\n"); + + // Find the start index in the old code + const startIndex = oldLines.findIndex((line, index) => { + const chunk = oldLines.slice(index, index + linesToMatchAbove).join("\n"); + return chunk === beforeContext; + }); + + if (startIndex === -1) { + return undefined; // Couldn't find matching start + } + + // Find the end index in the old code + const endIndex = oldLines.findIndex((line, index) => { + if (index <= startIndex + linesToMatchBelow) return false; + const chunk = oldLines.slice(index, index + linesToMatchBelow).join("\n"); + return chunk === afterContext; + }); + + if (endIndex === -1) { + return undefined; // Couldn't find matching end + } + + // Extract the replacement code + const replacement = oldLines + .slice(startIndex + linesToMatchAbove, endIndex) + .join("\n"); + + return replacement; +} + +async function getReplacementWithLlm( + oldCode: string, + linesBefore: string[], + linesAfter: string[], + llm: ILLM, +): Promise { + return "// TODO"; +} diff --git a/core/util/verticalEdit.ts b/core/edit/streamDiffLines.ts similarity index 98% rename from core/util/verticalEdit.ts rename to core/edit/streamDiffLines.ts index 34a17ebd4..8448262e1 100644 --- a/core/util/verticalEdit.ts +++ b/core/edit/streamDiffLines.ts @@ -15,7 +15,7 @@ import { LLMFullCompletionOptions, } from "../index.js"; import { gptEditPrompt } from "../llm/templates/edit.js"; -import { Telemetry } from "./posthog.js"; +import { Telemetry } from "../util/posthog.js"; function constructPrompt( prefix: string, diff --git a/extensions/vscode/src/diff/verticalPerLine/manager.ts b/extensions/vscode/src/diff/verticalPerLine/manager.ts index 123832611..c86868dca 100644 --- a/extensions/vscode/src/diff/verticalPerLine/manager.ts +++ b/extensions/vscode/src/diff/verticalPerLine/manager.ts @@ -1,7 +1,9 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; import { getMarkdownLanguageTagForFile } from "core/util"; -import { streamDiffLines } from "core/util/verticalEdit"; + +import { DiffLine } from "core"; +import { streamDiffLines } from "core/edit/streamDiffLines"; import * as vscode from "vscode"; import { VerticalPerLineDiffHandler } from "./handler"; @@ -29,7 +31,7 @@ export class VerticalPerLineDiffManager { filepath: string, startLine: number, endLine: number, - input: string, + input?: string, ) { if (this.filepathToHandler.has(filepath)) { this.filepathToHandler.get(filepath)?.clear(false); @@ -172,6 +174,71 @@ export class VerticalPerLineDiffManager { } } + async streamDiffLines(diffStream: AsyncGenerator) { + vscode.commands.executeCommand("setContext", "continue.diffVisible", true); + + // Get the current editor filepath/range + let editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + const filepath = editor.document.uri.fsPath; + const startLine = 0; + const endLine = editor.document.lineCount - 1; + + // Check for existing handlers in the same file the new one will be created in + const existingHandler = this.getHandlerForFile(filepath); + if (existingHandler) { + existingHandler.clear(false); + } + + await new Promise((resolve) => { + setTimeout(resolve, 200); + }); + + // Create new handler with determined start/end + const diffHandler = this.createVerticalPerLineDiffHandler( + filepath, + startLine, + endLine, + ); + + if (!diffHandler) { + console.warn("Issue occured while creating new vertical diff handler"); + return; + } + + if (editor.selection) { + // Unselect the range + editor.selection = new vscode.Selection( + editor.selection.active, + editor.selection.active, + ); + } + + vscode.commands.executeCommand( + "setContext", + "continue.streamingDiff", + true, + ); + + try { + await diffHandler.run(diffStream); + + // enable a listener for user edits to file while diff is open + this.enableDocumentChangeListener(); + } catch (e) { + this.disableDocumentChangeListener(); + vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + } finally { + vscode.commands.executeCommand( + "setContext", + "continue.streamingDiff", + false, + ); + } + } + /** * Streams an edit to the current document based on user input and model output. * diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index a1bb9e109..a3dd065e7 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -1,4 +1,5 @@ import { ConfigHandler } from "core/config/ConfigHandler"; +import { streamLazyApply } from "core/edit/lazy/streamLazyApply"; import { FromCoreProtocol, FromWebviewProtocol, @@ -11,18 +12,19 @@ import { CORE_TO_WEBVIEW_PASS_THROUGH, WEBVIEW_TO_CORE_PASS_THROUGH, } from "core/protocol/passThrough"; +import { getBasename } from "core/util"; import { InProcessMessenger, Message } from "core/util/messenger"; import { getConfigJsonPath } from "core/util/paths"; import * as fs from "node:fs"; import * as path from "node:path"; import * as vscode from "vscode"; import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager"; -import { VsCodeIde } from "../VsCodeIde"; import { getControlPlaneSessionInfo, WorkOsAuthProvider, } from "../stubs/WorkOsAuthProvider"; import { getExtensionUri } from "../util/vscode"; +import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; /** @@ -124,35 +126,36 @@ export class VsCodeMessenger { }); this.onWebview("applyToCurrentFile", async (msg) => { - // Select the entire current file + // Get active text editor const editor = vscode.window.activeTextEditor; - if (!editor) { vscode.window.showErrorMessage("No active editor to apply edits to"); return; } - if (editor.selection.isEmpty) { - const document = editor.document; - const start = new vscode.Position(0, 0); - const end = new vscode.Position( - document.lineCount - 1, - document.lineAt(document.lineCount - 1).text.length, - ); - editor.selection = new vscode.Selection(start, end); - } - - const verticalDiffManager = await this.verticalDiffManagerPromise; - const prompt = `The following code was suggested as an edit:\n\`\`\`\n${msg.data.text}\n\`\`\`\nPlease apply it to the previous code.`; - + // Get LLM from config const configHandler = await configHandlerPromise; const config = await configHandler.loadConfig(); - const modelTitle = config.experimental?.modelRoles?.applyCodeBlock ?? (await this.webviewProtocol.request("getDefaultModelTitle", undefined)); + const llm = config.models.find((model) => model.title === modelTitle); + if (!llm) { + vscode.window.showErrorMessage( + `Model ${modelTitle} not found in config.`, + ); + return; + } - verticalDiffManager.streamEdit(prompt, modelTitle); + // Generate the diff and pass through diff manager + const diffLines = streamLazyApply( + editor.document.getText(), + getBasename(editor.document.fileName), + msg.data.text, + llm, + ); + const verticalDiffManager = await this.verticalDiffManagerPromise; + verticalDiffManager.streamDiffLines(diffLines); }); this.onWebview("showTutorial", async (msg) => {