Merge branch 'main' into pe/consolidate-stepcontainer

This commit is contained in:
Patrick Erichsen 2025-04-14 09:56:34 -07:00
commit 96b927e597
8 changed files with 230 additions and 127 deletions

View file

@ -3,9 +3,8 @@ import { generateLines } from "../../diff/util";
import { supportedLanguages } from "../../util/treeSitter";
import { getUriFileExtension } from "../../util/uri";
import { deterministicApplyLazyEdit } from "./deterministic";
import { streamLazyApply } from "./streamLazyApply";
import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply";
import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply";
function canUseInstantApply(filename: string) {
const fileExtension = getUriFileExtension(filename);
@ -17,22 +16,21 @@ export async function applyCodeBlock(
newFile: string,
filename: string,
llm: ILLM,
fastLlm: ILLM,
): Promise<[boolean, AsyncGenerator<DiffLine>]> {
// This was buggy, removed for now, maybe forever
if (false && canUseInstantApply(filename)) {
const diffLines = await deterministicApplyLazyEdit(
oldFile,
newFile,
filename,
);
// if (canUseInstantApply(filename)) {
// const diffLines = await deterministicApplyLazyEdit(
// oldFile,
// newFile,
// filename,
// );
// Fall back to LLM method if we couldn't apply deterministically
if (diffLines !== undefined) {
const diffGenerator = generateLines(diffLines!);
return [true, diffGenerator];
}
}
// // Fall back to LLM method if we couldn't apply deterministically
// if (diffLines !== undefined) {
// const diffGenerator = generateLines(diffLines!);
// return [true, diffGenerator];
// }
// }
// If the code block is a diff
if (isUnifiedDiffFormat(newFile)) {
@ -45,5 +43,5 @@ export async function applyCodeBlock(
}
}
return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)];
return [false, streamLazyApply(oldFile, filename, newFile, llm)];
}

View file

@ -16,7 +16,6 @@ export async function* streamLazyApply(
filename: string,
newCode: string,
llm: ILLM,
fastLlm: ILLM,
): AsyncGenerator<DiffLine> {
const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName);
if (!promptFactory) {
@ -39,7 +38,7 @@ export async function* streamLazyApply(
oldCode,
linesBefore,
linesAfter,
fastLlm,
llm,
)) {
yield line;
}

View file

@ -0,0 +1,182 @@
import { ConfigHandler } from "core/config/ConfigHandler";
import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock";
import { getUriPathBasename } from "core/util/uri";
import * as vscode from "vscode";
import { VerticalDiffManager } from "../diff/vertical/manager";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
export interface ApplyToFileOptions {
streamId: string;
filepath?: string;
text: string;
toolCallId?: string;
}
/**
* Handles applying text/code to files including diff generation and streaming
*/
export class ApplyManager {
constructor(
private readonly ide: VsCodeIde,
private readonly webviewProtocol: VsCodeWebviewProtocol,
private readonly verticalDiffManager: VerticalDiffManager,
private readonly configHandler: ConfigHandler,
) {}
async applyToFile({
streamId,
filepath,
text,
toolCallId,
}: ApplyToFileOptions) {
await this.webviewProtocol.request("updateApplyState", {
streamId,
status: "streaming",
fileContent: text,
toolCallId,
});
if (filepath) {
await this.ensureFileOpen(filepath);
}
const { activeTextEditor } = vscode.window;
if (!activeTextEditor) {
vscode.window.showErrorMessage("No active editor to apply edits to");
return;
}
const hasExistingDocument = !!activeTextEditor.document.getText().trim();
if (hasExistingDocument) {
await this.handleExistingDocument(
activeTextEditor,
text,
streamId,
toolCallId,
);
} else {
await this.handleEmptyDocument(
activeTextEditor,
text,
streamId,
toolCallId,
);
}
}
private async ensureFileOpen(filepath: string): Promise<void> {
const fileExists = await this.ide.fileExists(filepath);
if (!fileExists) {
await this.ide.writeFile(filepath, "");
await this.ide.openFile(filepath);
}
await this.ide.openFile(filepath);
}
private async handleEmptyDocument(
editor: vscode.TextEditor,
text: string,
streamId: string,
toolCallId?: string,
) {
await editor.edit((builder) =>
builder.insert(new vscode.Position(0, 0), text),
);
await this.webviewProtocol.request("updateApplyState", {
streamId,
status: "closed",
numDiffs: 0,
fileContent: text,
toolCallId,
});
}
private async handleExistingDocument(
editor: vscode.TextEditor,
text: string,
streamId: string,
toolCallId?: string,
) {
const { config } = await this.configHandler.loadConfig();
if (!config) {
vscode.window.showErrorMessage("Config not loaded");
return;
}
const llm =
config.selectedModelByRole.apply ?? config.selectedModelByRole.chat;
if (!llm) {
vscode.window.showErrorMessage(
`No model with roles "apply" or "chat" found in config.`,
);
return;
}
const [instant, diffLines] = await applyCodeBlock(
editor.document.getText(),
text,
getUriPathBasename(editor.document.uri.toString()),
llm,
);
if (instant) {
await this.verticalDiffManager.streamDiffLines(
diffLines,
instant,
streamId,
toolCallId,
);
} else {
await this.handleNonInstantDiff(
editor,
text,
llm,
streamId,
this.verticalDiffManager,
toolCallId,
);
}
}
/**
* Creates a prompt for applying code edits
*/
private getApplyPrompt(text: string): string {
return `The following code was suggested as an edit:\n\`\`\`\n${text}\n\`\`\`\nPlease apply it to the previous code.`;
}
private async handleNonInstantDiff(
editor: vscode.TextEditor,
text: string,
llm: any,
streamId: string,
verticalDiffManager: VerticalDiffManager,
toolCallId?: string,
) {
const prompt = this.getApplyPrompt(text);
const fullEditorRange = new vscode.Range(
0,
0,
editor.document.lineCount - 1,
editor.document.lineAt(editor.document.lineCount - 1).text.length,
);
const rangeToApplyTo = editor.selection.isEmpty
? fullEditorRange
: editor.selection;
await verticalDiffManager.streamEdit(
prompt,
llm,
streamId,
undefined,
undefined,
rangeToApplyTo,
text,
toolCallId,
);
}
}

View file

@ -0,0 +1 @@
export * from "./ApplyManager";

View file

@ -0,0 +1,15 @@
import { ILLM } from "core";
export const FAST_APPLY_MODELS: Array<ILLM["model"]> = ["Fast-Apply"];
/**
* Checks against model names, which can include proxy prefixes
* such as `continuedev/hub`
* @param llm
* @returns
*/
export function isFastApplyModel(llm: ILLM): boolean {
return FAST_APPLY_MODELS?.some((fastApplyModel) =>
llm.model.toLowerCase().includes(fastApplyModel.toLowerCase())
);
}

View file

@ -6,6 +6,7 @@ import { getMarkdownLanguageTagForFile } from "core/util";
import * as URI from "uri-js";
import * as vscode from "vscode";
import { isFastApplyModel } from "../../apply/utils";
import EditDecorationManager from "../../quickEdit/EditDecorationManager";
import { handleLLMError } from "../../util/errorHandling";
import { VsCodeWebviewProtocol } from "../../webviewProtocol";
@ -345,6 +346,7 @@ export class VerticalDiffManager {
startLine,
endLine,
{
instant: isFastApplyModel(llm),
input,
onStatusUpdate: (status, numDiffs, fileContent) =>
streamId &&

View file

@ -1,6 +1,4 @@
import { ConfigHandler } from "core/config/ConfigHandler";
import { getModelByRole } from "core/config/util";
import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock";
import {
FromCoreProtocol,
FromWebviewProtocol,
@ -15,9 +13,9 @@ import {
WEBVIEW_TO_CORE_PASS_THROUGH,
} from "core/protocol/passThrough";
import { stripImages } from "core/util/messageContent";
import { getUriPathBasename } from "core/util/uri";
import * as vscode from "vscode";
import { ApplyManager } from "../apply";
import { VerticalDiffManager } from "../diff/vertical/manager";
import EditDecorationManager from "../quickEdit/EditDecorationManager";
import {
@ -29,14 +27,13 @@ import { getExtensionUri } from "../util/vscode";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol &
ToWebviewFromCoreProtocol;
/**
* A shared messenger class between Core and Webview
* so we don't have to rewrite some of the handlers
*/
type TODO = any;
type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol &
ToWebviewFromCoreProtocol;
export class VsCodeMessenger {
onWebview<T extends keyof FromWebviewProtocol>(
messageType: T,
@ -128,110 +125,19 @@ export class VsCodeMessenger {
});
this.onWebview("applyToFile", async ({ data }) => {
webviewProtocol.request("updateApplyState", {
streamId: data.streamId,
status: "streaming",
fileContent: data.text,
toolCallId: data.toolCallId,
});
const [verticalDiffManager, configHandler] = await Promise.all([
verticalDiffManagerPromise,
configHandlerPromise,
]);
if (data.filepath) {
const fileExists = await this.ide.fileExists(data.filepath);
if (!fileExists) {
await this.ide.writeFile(data.filepath, "");
await this.ide.openFile(data.filepath);
}
await this.ide.openFile(data.filepath);
}
// Get active text editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage("No active editor to apply edits to");
return;
}
// If document is empty, insert at 0,0 and finish
if (!editor.document.getText().trim()) {
editor.edit((builder) =>
builder.insert(new vscode.Position(0, 0), data.text),
);
void webviewProtocol.request("updateApplyState", {
streamId: data.streamId,
status: "closed",
numDiffs: 0,
fileContent: data.text,
toolCallId: data.toolCallId,
});
return;
}
// Get LLM from config
const configHandler = await configHandlerPromise;
const { config } = await configHandler.loadConfig();
if (!config) {
vscode.window.showErrorMessage("Config not loaded");
return;
}
let llm =
config.selectedModelByRole.apply ?? config.selectedModelByRole.chat;
if (!llm) {
vscode.window.showErrorMessage(
`No model with roles "apply" or "chat" found in config.`,
);
return;
}
const fastLlm = getModelByRole(config, "repoMapFileSelection") ?? llm;
// Generate the diff and pass through diff manager
const [instant, diffLines] = await applyCodeBlock(
editor.document.getText(),
data.text,
getUriPathBasename(editor.document.uri.toString()),
llm,
fastLlm,
const applyManager = new ApplyManager(
this.ide,
webviewProtocol,
verticalDiffManager,
configHandler,
);
const verticalDiffManager = await this.verticalDiffManagerPromise;
if (instant) {
await verticalDiffManager.streamDiffLines(
diffLines,
instant,
data.streamId,
data.toolCallId,
);
} else {
const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`;
const fullEditorRange = new vscode.Range(
0,
0,
editor.document.lineCount - 1,
editor.document.lineAt(editor.document.lineCount - 1).text.length,
);
const rangeToApplyTo = editor.selection.isEmpty
? fullEditorRange
: editor.selection;
await verticalDiffManager.streamEdit(
prompt,
llm,
data.streamId,
undefined,
undefined,
rangeToApplyTo,
data.text,
data.toolCallId,
);
}
await applyManager.applyToFile(data);
});
this.onWebview("showTutorial", async (msg) => {

View file

@ -60,7 +60,7 @@ export function ExploreBlocksButton(props: { blockType: string }) {
}}
>
<div className="flex items-center justify-center gap-1">
<Icon className="h-2.5 w-2.5 pr-1" />
<Icon className="h-3 w-3 pr-1" />
<span className="text-[11px]">{text}</span>
</div>
</GhostButton>