| 1 | import { ConfigHandler } from "core/config/ConfigHandler"; |
| 2 | import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; |
| 3 | import { getUriPathBasename } from "core/util/uri"; |
| 4 | import * as vscode from "vscode"; |
| 5 | |
| 6 | import { ApplyToFilePayload } from "core"; |
| 7 | import { myersDiff } from "core/diff/myers"; |
| 8 | import { generateLines } from "core/diff/util"; |
| 9 | import { ApplyAbortManager } from "core/edit/applyAbortManager"; |
| 10 | import { streamDiffLines } from "core/edit/streamDiffLines"; |
| 11 | import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; |
| 12 | import { getMarkdownLanguageTagForFile } from "core/util"; |
| 13 | import { VerticalDiffManager } from "../diff/vertical/manager"; |
| 14 | import { VsCodeIde } from "../VsCodeIde"; |
| 15 | import { VsCodeWebviewProtocol } from "../webviewProtocol"; |
| 16 | |
| 17 | /** |
| 18 | * Handles applying text/code to files including diff generation and streaming |
| 19 | */ |
| 20 | export class ApplyManager { |
| 21 | constructor( |
| 22 | private readonly ide: VsCodeIde, |
| 23 | private readonly webviewProtocol: VsCodeWebviewProtocol, |
| 24 | private readonly verticalDiffManager: VerticalDiffManager, |
| 25 | private readonly configHandler: ConfigHandler, |
| 26 | ) {} |
| 27 | |
| 28 | async applyToFile({ |
| 29 | streamId, |
| 30 | filepath, |
| 31 | text, |
| 32 | toolCallId, |
| 33 | isSearchAndReplace, |
| 34 | }: ApplyToFilePayload) { |
| 35 | if (filepath) { |
| 36 | await this.ensureFileOpen(filepath); |
| 37 | } |
| 38 | |
| 39 | const { activeTextEditor } = vscode.window; |
| 40 | if (!activeTextEditor) { |
| 41 | void vscode.window.showErrorMessage("No active editor to apply edits to"); |
| 42 | return; |
| 43 | } |
| 44 | |
| 45 | // Capture the original file content before applying changes |
| 46 | const originalFileContent = activeTextEditor.document.getText(); |
| 47 | |
| 48 | await this.webviewProtocol.request("updateApplyState", { |
| 49 | streamId, |
| 50 | status: "streaming", |
| 51 | fileContent: text, |
| 52 | originalFileContent, |
| 53 | toolCallId, |
| 54 | }); |
| 55 | |
| 56 | const hasExistingDocument = !!activeTextEditor.document.getText().trim(); |
| 57 | if (hasExistingDocument) { |
| 58 | // Currently `isSearchAndReplace` will always provide a full file rewrite |
| 59 | // as the contents of `text`, so we can just instantly apply |
| 60 | if (isSearchAndReplace) { |
| 61 | const diffLinesGenerator = generateLines( |
| 62 | myersDiff(activeTextEditor.document.getText(), text), |
| 63 | ); |
| 64 | |
| 65 | await this.verticalDiffManager.streamDiffLines( |
| 66 | diffLinesGenerator, |
| 67 | true, |
| 68 | streamId, |
| 69 | toolCallId, |
| 70 | ); |
| 71 | } else { |
| 72 | await this.handleExistingDocument( |
| 73 | activeTextEditor, |
| 74 | text, |
| 75 | streamId, |
| 76 | toolCallId, |
| 77 | ); |
| 78 | } |
| 79 | } else { |
| 80 | await this.handleEmptyDocument( |
| 81 | activeTextEditor, |
| 82 | text, |
| 83 | streamId, |
| 84 | toolCallId, |
| 85 | ); |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | private async ensureFileOpen(filepath: string): Promise<void> { |
| 90 | const fileExists = await this.ide.fileExists(filepath); |
| 91 | if (!fileExists) { |
| 92 | await this.ide.writeFile(filepath, ""); |
| 93 | await this.ide.openFile(filepath); |
| 94 | } |
| 95 | await this.ide.openFile(filepath); |
| 96 | } |
| 97 | |
| 98 | private modelIsTooFastForStreaming(model: string): boolean { |
| 99 | return [/mercury/].some((r) => r.test(model)); |
| 100 | } |
| 101 | |
| 102 | private async handleEmptyDocument( |
| 103 | editor: vscode.TextEditor, |
| 104 | text: string, |
| 105 | streamId: string, |
| 106 | toolCallId?: string, |
| 107 | ) { |
| 108 | await editor.edit((builder) => |
| 109 | builder.insert(new vscode.Position(0, 0), text), |
| 110 | ); |
| 111 | |
| 112 | await this.webviewProtocol.request("updateApplyState", { |
| 113 | streamId, |
| 114 | status: "closed", |
| 115 | numDiffs: 0, |
| 116 | fileContent: text, |
| 117 | toolCallId, |
| 118 | }); |
| 119 | } |
| 120 | |
| 121 | private async handleExistingDocument( |
| 122 | editor: vscode.TextEditor, |
| 123 | text: string, |
| 124 | streamId: string, |
| 125 | toolCallId?: string, |
| 126 | ) { |
| 127 | const { config } = await this.configHandler.loadConfig(); |
| 128 | if (!config) { |
| 129 | void vscode.window.showErrorMessage("Config not loaded"); |
| 130 | return; |
| 131 | } |
| 132 | |
| 133 | const llm = |
| 134 | config.selectedModelByRole.apply ?? config.selectedModelByRole.chat; |
| 135 | if (!llm) { |
| 136 | void vscode.window.showErrorMessage( |
| 137 | `No model with roles "apply" or "chat" found in config.`, |
| 138 | ); |
| 139 | return; |
| 140 | } |
| 141 | |
| 142 | const fileUri = editor.document.uri.toString(); |
| 143 | const abortManager = ApplyAbortManager.getInstance(); |
| 144 | const abortController = abortManager.get(fileUri); |
| 145 | |
| 146 | const { isInstantApply, diffLinesGenerator } = await applyCodeBlock( |
| 147 | editor.document.getText(), |
| 148 | text, |
| 149 | getUriPathBasename(fileUri), |
| 150 | llm, |
| 151 | abortController, |
| 152 | ); |
| 153 | |
| 154 | if (isInstantApply) { |
| 155 | await this.verticalDiffManager.streamDiffLines( |
| 156 | diffLinesGenerator, |
| 157 | isInstantApply, |
| 158 | streamId, |
| 159 | toolCallId, |
| 160 | ); |
| 161 | } else { |
| 162 | await this.handleNonInstantDiff( |
| 163 | editor, |
| 164 | text, |
| 165 | llm, |
| 166 | streamId, |
| 167 | this.verticalDiffManager, |
| 168 | toolCallId, |
| 169 | !this.modelIsTooFastForStreaming(llm.model), |
| 170 | ); |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /** |
| 175 | * Creates a prompt for applying code edits |
| 176 | */ |
| 177 | private getApplyPrompt(text: string): string { |
| 178 | return `The following code was suggested as an edit:\n\`\`\`\n${text}\n\`\`\`\nPlease apply it to the previous code.`; |
| 179 | } |
| 180 | |
| 181 | /** |
| 182 | * Calculates prefix and suffix for a given range, shared between streaming and non-streaming modes |
| 183 | */ |
| 184 | private calculatePrefixSuffix( |
| 185 | editor: vscode.TextEditor, |
| 186 | range: vscode.Range, |
| 187 | llm: any, |
| 188 | ): { prefix: string; suffix: string; rangeContent: string } { |
| 189 | const rangeContent = editor.document.getText(range); |
| 190 | |
| 191 | const prefix = pruneLinesFromTop( |
| 192 | editor.document.getText( |
| 193 | new vscode.Range(new vscode.Position(0, 0), range.start), |
| 194 | ), |
| 195 | llm.contextLength / 4, |
| 196 | llm.model, |
| 197 | ); |
| 198 | const suffix = pruneLinesFromBottom( |
| 199 | editor.document.getText( |
| 200 | new vscode.Range( |
| 201 | range.end, |
| 202 | new vscode.Position(editor.document.lineCount, 0), |
| 203 | ), |
| 204 | ), |
| 205 | llm.contextLength / 4, |
| 206 | llm.model, |
| 207 | ); |
| 208 | |
| 209 | return { prefix, suffix, rangeContent }; |
| 210 | } |
| 211 | |
| 212 | private async handleNonInstantDiff( |
| 213 | editor: vscode.TextEditor, |
| 214 | text: string, |
| 215 | llm: any, |
| 216 | streamId: string, |
| 217 | verticalDiffManager: VerticalDiffManager, |
| 218 | toolCallId?: string, |
| 219 | streaming: boolean = true, |
| 220 | ) { |
| 221 | const { config } = await this.configHandler.loadConfig(); |
| 222 | if (!config) { |
| 223 | void vscode.window.showErrorMessage("Config not loaded"); |
| 224 | return; |
| 225 | } |
| 226 | |
| 227 | const prompt = this.getApplyPrompt(text); |
| 228 | const fullEditorRange = new vscode.Range( |
| 229 | 0, |
| 230 | 0, |
| 231 | editor.document.lineCount - 1, |
| 232 | editor.document.lineAt(editor.document.lineCount - 1).text.length, |
| 233 | ); |
| 234 | const rangeToApplyTo = editor.selection.isEmpty |
| 235 | ? fullEditorRange |
| 236 | : editor.selection; |
| 237 | |
| 238 | if (streaming) { |
| 239 | await verticalDiffManager.streamEdit({ |
| 240 | input: prompt, |
| 241 | llm, |
| 242 | streamId, |
| 243 | range: rangeToApplyTo, |
| 244 | newCode: text, |
| 245 | toolCallId, |
| 246 | rulesToInclude: undefined, // No rules for apply |
| 247 | isApply: true, |
| 248 | }); |
| 249 | } else { |
| 250 | // Non-streaming: accumulate LLM output, then apply via Myers diff |
| 251 | const finalContent = await this.generateAppliedContent( |
| 252 | editor, |
| 253 | prompt, |
| 254 | llm, |
| 255 | rangeToApplyTo, |
| 256 | text, |
| 257 | ); |
| 258 | |
| 259 | if (finalContent) { |
| 260 | const diffLinesGenerator = generateLines( |
| 261 | myersDiff(editor.document.getText(), finalContent), |
| 262 | ); |
| 263 | |
| 264 | await verticalDiffManager.streamDiffLines( |
| 265 | diffLinesGenerator, |
| 266 | true, // Apply instantly since we accumulated all content |
| 267 | streamId, |
| 268 | toolCallId, |
| 269 | ); |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | /** |
| 275 | * Generates the final applied content by accumulating all LLM output |
| 276 | * Similar to streamEdit but collects all output before applying |
| 277 | */ |
| 278 | private async generateAppliedContent( |
| 279 | editor: vscode.TextEditor, |
| 280 | prompt: string, |
| 281 | llm: any, |
| 282 | range: vscode.Range, |
| 283 | newCode: string, |
| 284 | ): Promise<string | undefined> { |
| 285 | const fileUri = editor.document.uri.toString(); |
| 286 | const { prefix, suffix, rangeContent } = this.calculatePrefixSuffix( |
| 287 | editor, |
| 288 | range, |
| 289 | llm, |
| 290 | ); |
| 291 | |
| 292 | const abortManager = ApplyAbortManager.getInstance(); |
| 293 | const abortController = abortManager.get(fileUri); |
| 294 | |
| 295 | try { |
| 296 | const streamedLines: string[] = []; |
| 297 | |
| 298 | // Use streamDiffLines to get the LLM output |
| 299 | const stream = streamDiffLines( |
| 300 | { |
| 301 | highlighted: rangeContent, |
| 302 | prefix, |
| 303 | suffix, |
| 304 | input: prompt, |
| 305 | language: getMarkdownLanguageTagForFile(fileUri), |
| 306 | type: "apply", |
| 307 | newCode, |
| 308 | includeRulesInSystemMessage: false, |
| 309 | modelTitle: llm.title ?? llm.model, |
| 310 | }, |
| 311 | llm, |
| 312 | abortController, |
| 313 | undefined, |
| 314 | undefined, |
| 315 | ); |
| 316 | |
| 317 | // Accumulate all the streamed content |
| 318 | for await (const line of stream) { |
| 319 | if (abortController.signal.aborted) { |
| 320 | return undefined; |
| 321 | } |
| 322 | if (line.type === "new" || line.type === "same") { |
| 323 | streamedLines.push(line.line); |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | // Return the complete file content |
| 328 | return `${prefix}${streamedLines.join("\n")}${suffix}`; |
| 329 | } catch (error) { |
| 330 | console.error("Error generating applied content:", error); |
| 331 | return undefined; |
| 332 | } |
| 333 | } |
| 334 | } |