Elffuss BraidHub

kikocis/continue public

eca53d6fa452 · 5.7 KiBRawPermalink
1import { ConfigHandler } from "core/config/ConfigHandler";
2import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock";
3import { getUriPathBasename } from "core/util/uri";
4import * as vscode from "vscode";
5
6import { ApplyToFilePayload } from "core";
7import { myersDiff } from "core/diff/myers";
8import { generateLines } from "core/diff/util";
9import { ApplyAbortManager } from "core/edit/applyAbortManager";
10import { VerticalDiffManager } from "../diff/vertical/manager";
11import { VsCodeIde } from "../VsCodeIde";
12import { VsCodeWebviewProtocol } from "../webviewProtocol";
13
14/**
15 * Handles applying text/code to files including diff generation and streaming
16 */
17export class ApplyManager {
18 constructor(
19 private readonly ide: VsCodeIde,
20 private readonly webviewProtocol: VsCodeWebviewProtocol,
21 private readonly verticalDiffManager: VerticalDiffManager,
22 private readonly configHandler: ConfigHandler,
23 ) {}
24
25 async applyToFile({
26 streamId,
27 filepath,
28 text,
29 toolCallId,
30 isSearchAndReplace,
31 }: ApplyToFilePayload) {
32 if (filepath) {
33 await this.ensureFileOpen(filepath);
34 }
35
36 const { activeTextEditor } = vscode.window;
37 if (!activeTextEditor) {
38 void vscode.window.showErrorMessage("No active editor to apply edits to");
39 return;
40 }
41
42 // Capture the original file content before applying changes
43 const originalFileContent = activeTextEditor.document.getText();
44
45 await this.webviewProtocol.request("updateApplyState", {
46 streamId,
47 status: "streaming",
48 fileContent: text,
49 originalFileContent,
50 toolCallId,
51 });
52
53 try {
54 const hasExistingDocument = !!activeTextEditor.document.getText().trim();
55
56 if (hasExistingDocument) {
57 // Currently `isSearchAndReplace` will always provide a full file rewrite
58 // as the contents of `text`, so we can just instantly apply
59 if (isSearchAndReplace) {
60 const diffLinesGenerator = generateLines(
61 myersDiff(activeTextEditor.document.getText(), text),
62 );
63
64 await this.verticalDiffManager.streamDiffLines(
65 diffLinesGenerator,
66 true,
67 streamId,
68 toolCallId,
69 );
70 } else {
71 await this.handleExistingDocument(
72 activeTextEditor,
73 text,
74 streamId,
75 toolCallId,
76 );
77 }
78 } else {
79 await this.handleEmptyDocument(
80 activeTextEditor,
81 text,
82 streamId,
83 toolCallId,
84 );
85 }
86 } finally {
87 await this.webviewProtocol.request("updateApplyState", {
88 streamId,
89 status: "done",
90 toolCallId,
91 });
92 }
93 }
94
95 private async ensureFileOpen(filepath: string): Promise<void> {
96 const fileExists = await this.ide.fileExists(filepath);
97 if (!fileExists) {
98 await this.ide.writeFile(filepath, "");
99 await this.ide.openFile(filepath);
100 }
101 await this.ide.openFile(filepath);
102 }
103
104 private async handleEmptyDocument(
105 editor: vscode.TextEditor,
106 text: string,
107 streamId: string,
108 toolCallId?: string,
109 ) {
110 await editor.edit((builder) =>
111 builder.insert(new vscode.Position(0, 0), text),
112 );
113
114 await this.webviewProtocol.request("updateApplyState", {
115 streamId,
116 status: "closed",
117 numDiffs: 0,
118 fileContent: text,
119 toolCallId,
120 });
121 }
122
123 private async handleExistingDocument(
124 editor: vscode.TextEditor,
125 text: string,
126 streamId: string,
127 toolCallId?: string,
128 ) {
129 const { config } = await this.configHandler.loadConfig();
130 if (!config) {
131 void vscode.window.showErrorMessage("Config not loaded");
132 return;
133 }
134
135 const llm =
136 config.selectedModelByRole.apply ?? config.selectedModelByRole.chat;
137 if (!llm) {
138 void vscode.window.showErrorMessage(
139 `No model with roles "apply" or "chat" found in config.`,
140 );
141 return;
142 }
143
144 const fileUri = editor.document.uri.toString();
145 const abortManager = ApplyAbortManager.getInstance();
146 const abortController = abortManager.get(fileUri);
147
148 const { isInstantApply, diffLinesGenerator } = await applyCodeBlock(
149 editor.document.getText(),
150 text,
151 getUriPathBasename(fileUri),
152 llm,
153 abortController,
154 );
155
156 if (isInstantApply) {
157 await this.verticalDiffManager.streamDiffLines(
158 diffLinesGenerator,
159 isInstantApply,
160 streamId,
161 toolCallId,
162 );
163 } else {
164 await this.handleNonInstantDiff(
165 editor,
166 text,
167 llm,
168 streamId,
169 this.verticalDiffManager,
170 toolCallId,
171 );
172 }
173 }
174
175 /**
176 * Creates a prompt for applying code edits
177 */
178 private getApplyPrompt(text: string): string {
179 return `The following code was suggested as an edit:\n\`\`\`\n${text}\n\`\`\`\nPlease apply it to the previous code.`;
180 }
181
182 private async handleNonInstantDiff(
183 editor: vscode.TextEditor,
184 text: string,
185 llm: any,
186 streamId: string,
187 verticalDiffManager: VerticalDiffManager,
188 toolCallId?: string,
189 ) {
190 const { config } = await this.configHandler.loadConfig();
191 if (!config) {
192 void vscode.window.showErrorMessage("Config not loaded");
193 return;
194 }
195
196 const prompt = this.getApplyPrompt(text);
197 const fullEditorRange = new vscode.Range(
198 0,
199 0,
200 editor.document.lineCount - 1,
201 editor.document.lineAt(editor.document.lineCount - 1).text.length,
202 );
203 const rangeToApplyTo = editor.selection.isEmpty
204 ? fullEditorRange
205 : editor.selection;
206
207 await verticalDiffManager.streamEdit({
208 input: prompt,
209 llm,
210 streamId,
211 range: rangeToApplyTo,
212 newCode: text,
213 toolCallId,
214 rulesToInclude: undefined, // No rules for apply
215 });
216 }
217}