diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index dc491b055..c9abec151 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -1,14 +1,9 @@ import { ContextItemWithId, ILLM, SlashCommand } from "../.."; import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../../util"; - -interface RangeInFileWithContents { - filepath: string; - range: { - start: { line: number; character: number }; - end: { line: number; character: number }; - }; - contents: string; -} +import { + RangeInFileWithContents, + contextItemToRangeInFileWithContents, +} from "../util"; const PROMPT = `Take the file prefix and suffix into account, but only rewrite the code_to_edit as specified in the user_request. The code you write in modified_code_to_edit will replace the code between the code_to_edit tags. Do NOT preface your answer or write anything other than code. The tag should be written to indicate the end of the modified code section. Do not ever use nested tags. @@ -205,33 +200,10 @@ function lineToBeIgnored(line: string, isFirstLine: boolean = false): boolean { ); } -export function contextItemToRangeInFileWithContents( - item: ContextItemWithId -): RangeInFileWithContents { - const lines = item.name.split("(")[1].split(")")[0].split("-"); - - const rif: RangeInFileWithContents = { - filepath: item.description, - range: { - start: { - line: parseInt(lines[0]) - 1, - character: 0, - }, - end: { - line: parseInt(lines[1]), - character: 0, - }, - }, - contents: item.content, - }; - - return rif; -} - const EditSlashCommand: SlashCommand = { name: "edit", description: "Edit highlighted code", - run: async function* ({ ide, llm, input, history, contextItems }) { + run: async function* ({ ide, llm, input, history, contextItems, params }) { const contextItemToEdit = contextItems.find( (item: ContextItemWithId) => item.editing && item.id.providerTitle === "code" diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index 0c95060f5..ca0907674 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -6,6 +6,7 @@ import EditSlashCommand from "./edit"; import HttpSlashCommand from "./http"; import ShareSlashCommand from "./share"; import StackOverflowSlashCommand from "./stackOverflow"; +import VerticalEditSlashCommand from "./verticalEdit"; export default [ DraftIssueCommand, @@ -16,4 +17,5 @@ export default [ CommentSlashCommand, HttpSlashCommand, CommitMessageCommand, + VerticalEditSlashCommand, ]; diff --git a/core/commands/slash/verticalEdit.ts b/core/commands/slash/verticalEdit.ts new file mode 100644 index 000000000..84a013a26 --- /dev/null +++ b/core/commands/slash/verticalEdit.ts @@ -0,0 +1,84 @@ +import { ContextItemWithId, ILLM, SlashCommand } from "../.."; +import { DiffLine, streamDiff } from "../../diff/diffLines"; +import { streamLines } from "../../diff/util"; +import { gptEditPrompt } from "../../llm/templates/edit"; +import { renderPromptTemplate } from "../../util"; +import { + RangeInFileWithContents, + contextItemToRangeInFileWithContents, +} from "../util"; + +function shouldRemoveLineBeforeStart(line: string): boolean { + return line.startsWith("```"); +} + +async function* filterLines( + rawLines: AsyncGenerator +): AsyncGenerator { + let seenValidLine = false; + for await (const line of rawLines) { + if (!seenValidLine) { + if (shouldRemoveLineBeforeStart(line)) { + continue; + } else { + seenValidLine = true; + } + } + yield line; + } +} + +function constructPrompt(oldLines: string[], llm: ILLM, input: string): string { + const template = llm.promptTemplates?.edit ?? gptEditPrompt; + const rendered = renderPromptTemplate(template, [], { + userInput: input, + codeToEdit: oldLines.join("\n"), + }); + return typeof rendered === "string" + ? rendered + : rendered[rendered.length - 1].content; +} + +export function streamDiffLines( + oldLines: string[], + llm: ILLM, + input: string +): AsyncGenerator { + const prompt = constructPrompt(oldLines, llm, input); + + const completion = llm.streamComplete(prompt); + const newLines = filterLines(streamLines(completion)); + const diffLineGenerator = streamDiff(oldLines, newLines); + return diffLineGenerator; +} + +const VerticalEditSlashCommand: SlashCommand = { + name: "verticalEdit", + description: "Edit highlighted code with vertical diff", + run: async function* ({ ide, llm, input, contextItems }) { + const contextItemToEdit = contextItems.find( + (item: ContextItemWithId) => + item.editing && item.id.providerTitle === "code" + ); + + if (!contextItemToEdit) { + yield "Highlight the code that you want to edit first"; + return; + } + + const rif: RangeInFileWithContents = + contextItemToRangeInFileWithContents(contextItemToEdit); + const oldLines = rif.contents.split("\n"); + const startLine = rif.range.start.line; + const endLine = rif.range.end.line; + const filepath = rif.filepath; + + const diffLineGenerator = streamDiffLines(oldLines, llm, input); + + for await (const diffLine of diffLineGenerator) { + await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine); + } + }, +}; + +export default VerticalEditSlashCommand; diff --git a/core/commands/util.ts b/core/commands/util.ts new file mode 100644 index 000000000..17e0151f0 --- /dev/null +++ b/core/commands/util.ts @@ -0,0 +1,33 @@ +import { ContextItemWithId } from ".."; + +export interface RangeInFileWithContents { + filepath: string; + range: { + start: { line: number; character: number }; + end: { line: number; character: number }; + }; + contents: string; +} + +export function contextItemToRangeInFileWithContents( + item: ContextItemWithId +): RangeInFileWithContents { + const lines = item.name.split("(")[1].split(")")[0].split("-"); + + const rif: RangeInFileWithContents = { + filepath: item.description, + range: { + start: { + line: parseInt(lines[0]) - 1, + character: 0, + }, + end: { + line: parseInt(lines[1]), + character: 0, + }, + }, + contents: item.content, + }; + + return rif; +} diff --git a/core/diff/diffLines.ts b/core/diff/diffLines.ts index 6fc3e1768..7124d9aba 100644 --- a/core/diff/diffLines.ts +++ b/core/diff/diffLines.ts @@ -14,7 +14,7 @@ export type DiffLine = DiffLineNew | DiffLineOldOrSame; /** * https://blog.jcoglan.com/2017/02/12/the-myers-diff-algorithm-part-1/ */ -async function* streamDiff( +export async function* streamDiff( oldLines: string[], newLines: AsyncGenerator ): AsyncGenerator { diff --git a/core/ide/filesystem.ts b/core/ide/filesystem.ts index 9092c6c1c..174cbcc00 100644 --- a/core/ide/filesystem.ts +++ b/core/ide/filesystem.ts @@ -1,5 +1,6 @@ import * as fs from "fs"; import { IDE, SerializedContinueConfig } from ".."; +import { DiffLine } from "../diff/diffLines"; import { getConfigJsonPath, getConfigTsPath, @@ -90,6 +91,15 @@ class FileSystemIde implements IDE { return Promise.resolve(); } + async verticalDiffUpdate( + filepath: string, + startLine: number, + endLine: number, + diffLine: DiffLine + ) { + return Promise.resolve(); + } + getOpenFiles(): Promise { return Promise.resolve([]); } diff --git a/core/ide/index.ts b/core/ide/index.ts index 7386615d7..9867f4827 100644 --- a/core/ide/index.ts +++ b/core/ide/index.ts @@ -1,3 +1,4 @@ +import { DiffLine } from "../diff/diffLines"; import { IDE, SerializedContinueConfig } from "../index"; import { ideRequest } from "./messaging"; async function r(messageType: string, options: any = {}) { @@ -69,6 +70,15 @@ export class ExtensionIde implements IDE { await r("showDiff", { filepath, newContents, stepIndex }); } + async verticalDiffUpdate( + filepath: string, + startLine: number, + endLine: number, + diffLine: DiffLine + ) { + await r("diffLine", { filepath, startLine, endLine, diffLine }); + } + getOpenFiles(): Promise { return r("getOpenFiles"); } diff --git a/core/index.d.ts b/core/index.d.ts index 9aca642c1..d4e2ef44e 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -248,6 +248,12 @@ export interface IDE { newContents: string, stepIndex: number ): Promise; + verticalDiffUpdate( + filepath: string, + startLine: number, + endLine: number, + diffLine: DiffLine + ): Promise; getOpenFiles(): Promise; } diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index c2d763a5d..62552fbc4 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -16,6 +16,19 @@ Here is the edit requested: Here is the code after editing:`; +const gptEditPrompt = `\ +You will be asked to rewrite a section of code to fulfill a user request. Here is the code you will rewrite: + +\`\`\` +{{{codeToEdit}}} +\`\`\` + +Here is the user request: + +{{{userInput}}} + +Now rewrite the code to perfectly satisfy the user request. Your output should include nothing but the code. No code block, no English explanation, no start/end tags. Here it is:`; + const codellamaInfillEditPrompt = "{{filePrefix}}{{fileSuffix}}"; const codellamaEditPrompt = `[CODE] @@ -101,6 +114,7 @@ export { codellamaEditPrompt, codellamaInfillEditPrompt, deepseekEditPrompt, + gptEditPrompt, openchatEditPrompt, phindEditPrompt, simplestEditPrompt, diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index d8e0a4455..279272208 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -81,9 +81,9 @@ "title": "Reject Diff" }, { - "command": "continue.quickTextEntry", + "command": "continue.quickEdit", "category": "Continue", - "title": "Quick Text Entry" + "title": "Quick Edit" }, { "command": "continue.toggleAuxiliaryBar", @@ -156,7 +156,7 @@ "key": "shift+ctrl+backspace" }, { - "command": "continue.quickTextEntry", + "command": "continue.quickEdit", "mac": "cmd+shift+l", "key": "ctrl+shift+l" }, diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 02045c263..5213f51b6 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -6,6 +6,7 @@ import * as vscode from "vscode"; import { ideProtocolClient } from "./activation/activate"; import { debugPanelWebview, getSidebarContent } from "./debugPanel"; import { acceptDiffCommand, rejectDiffCommand } from "./diff/horizontal"; +import { streamEdit } from "./diff/verticalPerLine"; function addHighlightedCodeToContext(edit: boolean) { const editor = vscode.window.activeTextEditor; @@ -105,20 +106,13 @@ const commandsMap: { [command: string]: (...args: any) => any } = { "continue.toggleAuxiliaryBar": () => { vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); }, - "continue.quickTextEntry": async () => { - addHighlightedCodeToContext(true); + "continue.quickEdit": async () => { const text = await vscode.window.showInputBox({ - placeHolder: "Ask a question or enter a slash command", - title: "Continue Quick Input", + placeHolder: "Describe how to edit the highlighted code", + title: "Continue Quick Edit", }); if (text) { - debugPanelWebview?.postMessage({ - type: "userInput", - input: text, - }); - if (!text.startsWith("/edit")) { - vscode.commands.executeCommand("continue.continueGUIView.focus"); - } + await streamEdit(text); } }, "continue.viewLogs": async () => { diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index 237b2d0d1..cb08febe2 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -10,7 +10,6 @@ import * as io from "socket.io-client"; import * as vscode from "vscode"; import { ideProtocolClient, windowId } from "./activation/activate"; import { getContinueServerUrl } from "./bridge"; -import { verticalPerLineDiffManager } from "./diff/verticalPerLine"; import historyManager from "./history"; import { VsCodeIde } from "./ideProtocol"; import { configHandler, llmFromTitle } from "./loadConfig"; @@ -354,15 +353,9 @@ export function getSidebarContent( endLine: number; } = data.message; - const diffHandler = - verticalPerLineDiffManager.getOrCreateVerticalPerLineDiffHandler( - filepath, - startLine, - endLine - ); - if (diffHandler) { - await diffHandler.handleDiffLine(diffLine); - } + respond( + await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine) + ); break; } case "getOpenFiles": { diff --git a/extensions/vscode/src/diff/verticalPerLine.ts b/extensions/vscode/src/diff/verticalPerLine.ts index b791edc5e..43a50e57d 100644 --- a/extensions/vscode/src/diff/verticalPerLine.ts +++ b/extensions/vscode/src/diff/verticalPerLine.ts @@ -1,5 +1,7 @@ +import { streamDiffLines } from "core/commands/slash/verticalEdit"; import { DiffLine } from "core/diff/diffLines"; import * as vscode from "vscode"; +import { llmFromTitle } from "../loadConfig"; const redDecorationType = vscode.window.createTextEditorDecorationType({ isWholeLine: true, @@ -183,3 +185,40 @@ class VerticalPerLineDiffManager { } export const verticalPerLineDiffManager = new VerticalPerLineDiffManager(); + +export async function streamEdit(input: string) { + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + + const filepath = editor.document.uri.fsPath; + const startLine = editor.selection.start.line; + const endLine = editor.selection.end.line; + + const diffHandler = + verticalPerLineDiffManager.getOrCreateVerticalPerLineDiffHandler( + filepath, + startLine, + endLine + ); + + if (diffHandler) { + const selectedRange = new vscode.Range( + editor.selection.start, + editor.selection.end + ); + const rangeContent = editor.document.getText(selectedRange); + const llm = await llmFromTitle(); + + for await (const diffLine of streamDiffLines( + rangeContent.split("\n"), + llm, + input + )) { + await diffHandler.handleDiffLine(diffLine); + } + } + + // Shortcuts to accept / reject +} diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index 7de36964f..ce799aa57 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -16,6 +16,8 @@ import { intermediateToFinalConfig, serializedToIntermediateConfig, } from "core/config/load"; +import { DiffLine } from "core/diff/diffLines"; +import { verticalPerLineDiffManager } from "./diff/verticalPerLine"; import mergeJson from "./util/merge"; async function buildConfigTs(browser: boolean) { @@ -208,6 +210,23 @@ class VsCodeIde implements IDE { await ideProtocolClient.showDiff(filepath, newContents, stepIndex); } + async verticalDiffUpdate( + filepath: string, + startLine: number, + endLine: number, + diffLine: DiffLine + ) { + const diffHandler = + verticalPerLineDiffManager.getOrCreateVerticalPerLineDiffHandler( + filepath, + startLine, + endLine + ); + if (diffHandler) { + await diffHandler.handleDiffLine(diffLine); + } + } + async getOpenFiles(): Promise { return await ideProtocolClient.getOpenFiles(); } diff --git a/extensions/vscode/src/loadConfig.ts b/extensions/vscode/src/loadConfig.ts index 6fb668778..d3eceecb6 100644 --- a/extensions/vscode/src/loadConfig.ts +++ b/extensions/vscode/src/loadConfig.ts @@ -22,9 +22,11 @@ class VsCodeConfigHandler { export const configHandler = new VsCodeConfigHandler(); -export async function llmFromTitle(title: string): Promise { +export async function llmFromTitle(title?: string): Promise { let config = await configHandler.loadConfig(new VsCodeIde()); - let llm = config.models.find((llm) => llm.title === title); + let llm = title + ? config.models.find((llm) => llm.title === title) + : config.models[0]; if (!llm) { // Try to reload config configHandler.reloadConfig();