Elffuss BraidHub

kikocis/continue public

8d9577e85559 · 13.7 KiBRawPermalink
1import { ConfigHandler } from "core/config/ConfigHandler";
2import { DataLogger } from "core/data/log";
3import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
4import {
5 FromCoreProtocol,
6 FromWebviewProtocol,
7 ToCoreProtocol,
8} from "core/protocol";
9import { ToWebviewFromCoreProtocol } from "core/protocol/coreWebview";
10import { ToIdeFromWebviewOrCoreProtocol } from "core/protocol/ide";
11import { ToIdeFromCoreProtocol } from "core/protocol/ideCore";
12import { InProcessMessenger, Message } from "core/protocol/messenger";
13import {
14 CORE_TO_WEBVIEW_PASS_THROUGH,
15 WEBVIEW_TO_CORE_PASS_THROUGH,
16} from "core/protocol/passThrough";
17import { stripImages } from "core/util/messageContent";
18import * as vscode from "vscode";
19
20import { ApplyManager } from "../apply";
21import { VerticalDiffManager } from "../diff/vertical/manager";
22import { addCurrentSelectionToEdit } from "../quickEdit/AddCurrentSelection";
23import EditDecorationManager from "../quickEdit/EditDecorationManager";
24import {
25 getControlPlaneSessionInfo,
26 WorkOsAuthProvider,
27} from "../stubs/WorkOsAuthProvider";
28import { handleLLMError } from "../util/errorHandling";
29import { showTutorial } from "../util/tutorial";
30import { getExtensionUri } from "../util/vscode";
31import { VsCodeIde } from "../VsCodeIde";
32import { VsCodeWebviewProtocol } from "../webviewProtocol";
33
34import { VsCodeExtension } from "./VsCodeExtension";
35
36type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol &
37 ToWebviewFromCoreProtocol;
38
39/**
40 * A shared messenger class between Core and Webview
41 * so we don't have to rewrite some of the handlers
42 */
43export class VsCodeMessenger {
44 onWebview<T extends keyof FromWebviewProtocol>(
45 messageType: T,
46 handler: (
47 message: Message<FromWebviewProtocol[T][0]>,
48 ) => Promise<FromWebviewProtocol[T][1]> | FromWebviewProtocol[T][1],
49 ): void {
50 void this.webviewProtocol.on(messageType, handler);
51 }
52
53 onCore<T extends keyof ToIdeOrWebviewFromCoreProtocol>(
54 messageType: T,
55 handler: (
56 message: Message<ToIdeOrWebviewFromCoreProtocol[T][0]>,
57 ) =>
58 | Promise<ToIdeOrWebviewFromCoreProtocol[T][1]>
59 | ToIdeOrWebviewFromCoreProtocol[T][1],
60 ): void {
61 this.inProcessMessenger.externalOn(messageType, handler);
62 }
63
64 onWebviewOrCore<T extends keyof ToIdeFromWebviewOrCoreProtocol>(
65 messageType: T,
66 handler: (
67 message: Message<ToIdeFromWebviewOrCoreProtocol[T][0]>,
68 ) =>
69 | Promise<ToIdeFromWebviewOrCoreProtocol[T][1]>
70 | ToIdeFromWebviewOrCoreProtocol[T][1],
71 ): void {
72 this.onWebview(messageType, handler);
73 this.onCore(messageType, handler);
74 }
75
76 constructor(
77 private readonly inProcessMessenger: InProcessMessenger<
78 ToCoreProtocol,
79 FromCoreProtocol
80 >,
81 private readonly webviewProtocol: VsCodeWebviewProtocol,
82 private readonly ide: VsCodeIde,
83 private readonly verticalDiffManagerPromise: Promise<VerticalDiffManager>,
84 private readonly configHandlerPromise: Promise<ConfigHandler>,
85 private readonly workOsAuthProvider: WorkOsAuthProvider,
86 private readonly editDecorationManager: EditDecorationManager,
87 private readonly context: vscode.ExtensionContext,
88 private readonly vsCodeExtension: VsCodeExtension,
89 ) {
90 /** WEBVIEW ONLY LISTENERS **/
91 this.onWebview("showFile", (msg) => {
92 this.ide.openFile(msg.data.filepath);
93 });
94
95 this.onWebview("vscode/openMoveRightMarkdown", (msg) => {
96 vscode.commands.executeCommand(
97 "markdown.showPreview",
98 vscode.Uri.joinPath(
99 getExtensionUri(),
100 "media",
101 "move-chat-panel-right.md",
102 ),
103 );
104 });
105
106 this.onWebview("toggleDevTools", (msg) => {
107 vscode.commands.executeCommand("continue.viewLogs");
108 });
109 this.onWebview("reloadWindow", (msg) => {
110 vscode.commands.executeCommand("workbench.action.reloadWindow");
111 });
112 this.onWebview("focusEditor", (msg) => {
113 vscode.commands.executeCommand("workbench.action.focusActiveEditorGroup");
114 });
115
116 this.onWebview("acceptDiff", async ({ data: { filepath, streamId } }) => {
117 await vscode.commands.executeCommand(
118 "continue.acceptDiff",
119 filepath,
120 streamId,
121 );
122 });
123
124 this.onWebview("rejectDiff", async ({ data: { filepath, streamId } }) => {
125 await vscode.commands.executeCommand(
126 "continue.rejectDiff",
127 filepath,
128 streamId,
129 );
130 });
131
132 this.onWebview("applyToFile", async ({ data }) => {
133 const [verticalDiffManager, configHandler] = await Promise.all([
134 verticalDiffManagerPromise,
135 configHandlerPromise,
136 ]);
137
138 const applyManager = new ApplyManager(
139 this.ide,
140 webviewProtocol,
141 verticalDiffManager,
142 configHandler,
143 );
144
145 await applyManager.applyToFile(data);
146 });
147
148 this.onWebview("showTutorial", async (msg) => {
149 await showTutorial(this.ide);
150 });
151
152 this.onWebview(
153 "overwriteFile",
154 async ({ data: { prevFileContent, filepath } }) => {
155 if (prevFileContent === null) {
156 // TODO: Delete the file
157 return;
158 }
159
160 await this.ide.openFile(filepath);
161
162 // Get active text editor
163 const editor = vscode.window.activeTextEditor;
164
165 if (!editor) {
166 vscode.window.showErrorMessage("No active editor to apply edits to");
167 return;
168 }
169
170 editor.edit((builder) =>
171 builder.replace(
172 new vscode.Range(
173 editor.document.positionAt(0),
174 editor.document.positionAt(editor.document.getText().length),
175 ),
176 prevFileContent,
177 ),
178 );
179 },
180 );
181
182 this.onWebview("insertAtCursor", async (msg) => {
183 const editor = vscode.window.activeTextEditor;
184 if (editor === undefined || !editor.selection) {
185 return;
186 }
187
188 editor.edit((editBuilder) => {
189 editBuilder.replace(
190 new vscode.Range(editor.selection.start, editor.selection.end),
191 msg.data.text,
192 );
193 });
194 });
195 this.onWebview("edit/addCurrentSelection", async (msg) => {
196 const verticalDiffManager = await this.verticalDiffManagerPromise;
197 await addCurrentSelectionToEdit({
198 args: undefined,
199 editDecorationManager,
200 webviewProtocol: this.webviewProtocol,
201 verticalDiffManager,
202 });
203 });
204 this.onWebview("edit/sendPrompt", async (msg) => {
205 const prompt = msg.data.prompt;
206 const { start, end } = msg.data.range.range;
207 const verticalDiffManager = await verticalDiffManagerPromise;
208
209 const configHandler = await configHandlerPromise;
210 const { config } = await configHandler.loadConfig();
211
212 if (!config) {
213 throw new Error("Edit: Failed to load config");
214 }
215
216 const model =
217 config?.selectedModelByRole.edit ?? config?.selectedModelByRole.chat;
218
219 if (!model) {
220 throw new Error("No Edit or Chat model selected");
221 }
222
223 const fileAfterEdit = await verticalDiffManager.streamEdit({
224 input: stripImages(prompt),
225 llm: model,
226 streamId: EDIT_MODE_STREAM_ID,
227 range: new vscode.Range(
228 new vscode.Position(start.line, start.character),
229 new vscode.Position(end.line, end.character),
230 ),
231 rulesToInclude: config.rules,
232 isApply: false,
233 });
234
235 // Log dev data
236 await DataLogger.getInstance().logDevData({
237 name: "editInteraction",
238 data: {
239 prompt: stripImages(prompt),
240 completion: fileAfterEdit ?? "",
241 modelProvider: model.underlyingProviderName,
242 modelName: model.title ?? "",
243 modelTitle: model.title ?? "",
244 filepath: msg.data.range.filepath,
245 },
246 });
247
248 return fileAfterEdit;
249 });
250
251 this.onWebview("edit/clearDecorations", async (msg) => {
252 editDecorationManager.clear();
253 });
254
255 /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
256 WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
257 this.onWebview(messageType, async (msg) => {
258 return await this.inProcessMessenger.externalRequest(
259 messageType,
260 msg.data,
261 msg.messageId,
262 );
263 });
264 });
265
266 /** PASS THROUGH FROM CORE TO WEBVIEW AND BACK **/
267 CORE_TO_WEBVIEW_PASS_THROUGH.forEach((messageType) => {
268 this.onCore(messageType, async (msg) => {
269 return this.webviewProtocol.request(messageType, msg.data);
270 });
271 });
272
273 /** CORE ONLY LISTENERS **/
274 // None right now
275
276 /** BOTH CORE AND WEBVIEW **/
277 this.onWebviewOrCore("readRangeInFile", async (msg) => {
278 return await vscode.workspace
279 .openTextDocument(msg.data.filepath)
280 .then((document) => {
281 const start = new vscode.Position(0, 0);
282 const end = new vscode.Position(5, 0);
283 const range = new vscode.Range(start, end);
284
285 const contents = document.getText(range);
286 return contents;
287 });
288 });
289
290 this.onWebviewOrCore("getIdeSettings", async (msg) => {
291 return ide.getIdeSettings();
292 });
293 this.onWebviewOrCore("getDiff", async (msg) => {
294 return ide.getDiff(msg.data.includeUnstaged);
295 });
296 this.onWebviewOrCore("getTerminalContents", async (msg) => {
297 return ide.getTerminalContents();
298 });
299 this.onWebviewOrCore("getDebugLocals", async (msg) => {
300 return ide.getDebugLocals(Number(msg.data.threadIndex));
301 });
302 this.onWebviewOrCore("getAvailableThreads", async (msg) => {
303 return ide.getAvailableThreads();
304 });
305 this.onWebviewOrCore("getTopLevelCallStackSources", async (msg) => {
306 return ide.getTopLevelCallStackSources(
307 msg.data.threadIndex,
308 msg.data.stackDepth,
309 );
310 });
311 this.onWebviewOrCore("getWorkspaceDirs", async (msg) => {
312 return ide.getWorkspaceDirs();
313 });
314 this.onWebviewOrCore("writeFile", async (msg) => {
315 return ide.writeFile(msg.data.path, msg.data.contents);
316 });
317 this.onWebviewOrCore("showVirtualFile", async (msg) => {
318 return ide.showVirtualFile(msg.data.name, msg.data.content);
319 });
320 this.onWebviewOrCore("openFile", async (msg) => {
321 return ide.openFile(msg.data.path);
322 });
323 this.onWebviewOrCore("runCommand", async (msg) => {
324 await ide.runCommand(msg.data.command);
325 });
326 this.onWebviewOrCore("getSearchResults", async (msg) => {
327 return ide.getSearchResults(msg.data.query, msg.data.maxResults);
328 });
329 this.onWebviewOrCore("getFileResults", async (msg) => {
330 return ide.getFileResults(msg.data.pattern, msg.data.maxResults);
331 });
332 this.onWebviewOrCore("subprocess", async (msg) => {
333 return ide.subprocess(msg.data.command, msg.data.cwd);
334 });
335 this.onWebviewOrCore("getProblems", async (msg) => {
336 return ide.getProblems(msg.data.filepath);
337 });
338 this.onWebviewOrCore("getBranch", async (msg) => {
339 const { dir } = msg.data;
340 return ide.getBranch(dir);
341 });
342 this.onWebviewOrCore("getOpenFiles", async (msg) => {
343 return ide.getOpenFiles();
344 });
345 this.onWebviewOrCore("getCurrentFile", async () => {
346 return ide.getCurrentFile();
347 });
348 this.onWebviewOrCore("getPinnedFiles", async (msg) => {
349 return ide.getPinnedFiles();
350 });
351 this.onWebviewOrCore("showLines", async (msg) => {
352 const { filepath, startLine, endLine } = msg.data;
353 return ide.showLines(filepath, startLine, endLine);
354 });
355 this.onWebviewOrCore("showToast", (msg) => {
356 this.ide.showToast(...msg.data);
357 });
358 this.onWebviewOrCore("getControlPlaneSessionInfo", async (msg) => {
359 return getControlPlaneSessionInfo(
360 msg.data.silent,
361 msg.data.useOnboarding,
362 );
363 });
364 this.onWebviewOrCore("logoutOfControlPlane", async (msg) => {
365 const sessions = await this.workOsAuthProvider.getSessions();
366 await Promise.all(
367 sessions.map((session) => workOsAuthProvider.removeSession(session.id)),
368 );
369 vscode.commands.executeCommand(
370 "setContext",
371 "continue.isSignedInToControlPlane",
372 false,
373 );
374 });
375 this.onWebviewOrCore("saveFile", async (msg) => {
376 return await ide.saveFile(msg.data.filepath);
377 });
378 this.onWebviewOrCore("readFile", async (msg) => {
379 return await ide.readFile(msg.data.filepath);
380 });
381 this.onWebviewOrCore("openUrl", (msg) => {
382 vscode.env.openExternal(vscode.Uri.parse(msg.data));
383 });
384
385 this.onWebviewOrCore("fileExists", async (msg) => {
386 return await ide.fileExists(msg.data.filepath);
387 });
388
389 this.onWebviewOrCore("gotoDefinition", async (msg) => {
390 return await ide.gotoDefinition(msg.data.location);
391 });
392
393 this.onWebviewOrCore("getReferences", async (msg) => {
394 return await ide.getReferences(msg.data.location);
395 });
396
397 this.onWebviewOrCore("getDocumentSymbols", async (msg) => {
398 return await ide.getDocumentSymbols(msg.data.textDocumentIdentifier);
399 });
400
401 this.onWebviewOrCore("getFileStats", async (msg) => {
402 return await ide.getFileStats(msg.data.files);
403 });
404
405 this.onWebviewOrCore("getGitRootPath", async (msg) => {
406 return await ide.getGitRootPath(msg.data.dir);
407 });
408
409 this.onWebviewOrCore("listDir", async (msg) => {
410 return await ide.listDir(msg.data.dir);
411 });
412
413 this.onWebviewOrCore("getRepoName", async (msg) => {
414 return await ide.getRepoName(msg.data.dir);
415 });
416
417 this.onWebviewOrCore("getTags", async (msg) => {
418 return await ide.getTags(msg.data);
419 });
420
421 this.onWebviewOrCore("getIdeInfo", async (msg) => {
422 return await ide.getIdeInfo();
423 });
424
425 this.onWebviewOrCore("isTelemetryEnabled", async (msg) => {
426 return await ide.isTelemetryEnabled();
427 });
428
429 this.onWebviewOrCore("getUniqueId", async (msg) => {
430 return await ide.getUniqueId();
431 });
432
433 this.onWebviewOrCore("reportError", async (msg) => {
434 await handleLLMError(msg.data);
435 });
436 }
437}