Elffuss BraidHub

kikocis/continue public

6c9c9d0b91ee · 13.9 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
110 this.onWebview("reloadWindow", (msg) => {
111 vscode.commands.executeCommand("workbench.action.reloadWindow");
112 });
113 this.onWebview("focusEditor", (msg) => {
114 vscode.commands.executeCommand("workbench.action.focusActiveEditorGroup");
115 });
116
117 this.onWebview("acceptDiff", async ({ data: { filepath, streamId } }) => {
118 await vscode.commands.executeCommand(
119 "continue.acceptDiff",
120 filepath,
121 streamId,
122 );
123 });
124
125 this.onWebview("rejectDiff", async ({ data: { filepath, streamId } }) => {
126 await vscode.commands.executeCommand(
127 "continue.rejectDiff",
128 filepath,
129 streamId,
130 );
131 });
132
133 this.onWebview("applyToFile", async ({ data }) => {
134 const [verticalDiffManager, configHandler] = await Promise.all([
135 verticalDiffManagerPromise,
136 configHandlerPromise,
137 ]);
138
139 const applyManager = new ApplyManager(
140 this.ide,
141 webviewProtocol,
142 verticalDiffManager,
143 configHandler,
144 );
145
146 await applyManager.applyToFile(data);
147 });
148
149 this.onWebview("showTutorial", async (msg) => {
150 await showTutorial(this.ide);
151 });
152
153 this.onWebview(
154 "overwriteFile",
155 async ({ data: { prevFileContent, filepath } }) => {
156 if (prevFileContent === null) {
157 // TODO: Delete the file
158 return;
159 }
160
161 await this.ide.openFile(filepath);
162
163 // Get active text editor
164 const editor = vscode.window.activeTextEditor;
165
166 if (!editor) {
167 vscode.window.showErrorMessage("No active editor to apply edits to");
168 return;
169 }
170
171 editor.edit((builder) =>
172 builder.replace(
173 new vscode.Range(
174 editor.document.positionAt(0),
175 editor.document.positionAt(editor.document.getText().length),
176 ),
177 prevFileContent,
178 ),
179 );
180 },
181 );
182
183 this.onWebview("insertAtCursor", async (msg) => {
184 const editor = vscode.window.activeTextEditor;
185 if (editor === undefined || !editor.selection) {
186 return;
187 }
188
189 editor.edit((editBuilder) => {
190 editBuilder.replace(
191 new vscode.Range(editor.selection.start, editor.selection.end),
192 msg.data.text,
193 );
194 });
195 });
196 this.onWebview("edit/addCurrentSelection", async (msg) => {
197 const verticalDiffManager = await this.verticalDiffManagerPromise;
198 await addCurrentSelectionToEdit({
199 args: undefined,
200 editDecorationManager,
201 webviewProtocol: this.webviewProtocol,
202 verticalDiffManager,
203 });
204 });
205 this.onWebview("edit/sendPrompt", async (msg) => {
206 const prompt = msg.data.prompt;
207 const { start, end } = msg.data.range.range;
208 const verticalDiffManager = await verticalDiffManagerPromise;
209
210 const configHandler = await configHandlerPromise;
211 const { config } = await configHandler.loadConfig();
212
213 if (!config) {
214 throw new Error("Edit: Failed to load config");
215 }
216
217 const model =
218 config?.selectedModelByRole.edit ?? config?.selectedModelByRole.chat;
219
220 if (!model) {
221 throw new Error("No Edit or Chat model selected");
222 }
223
224 const fileAfterEdit = await verticalDiffManager.streamEdit({
225 input: stripImages(prompt),
226 llm: model,
227 streamId: EDIT_MODE_STREAM_ID,
228 range: new vscode.Range(
229 new vscode.Position(start.line, start.character),
230 new vscode.Position(end.line, end.character),
231 ),
232 rulesToInclude: config.rules,
233 isApply: false,
234 });
235
236 // Log dev data
237 await DataLogger.getInstance().logDevData({
238 name: "editInteraction",
239 data: {
240 prompt: stripImages(prompt),
241 completion: fileAfterEdit ?? "",
242 modelProvider: model.underlyingProviderName,
243 modelName: model.title ?? "",
244 modelTitle: model.title ?? "",
245 filepath: msg.data.range.filepath,
246 },
247 });
248
249 return fileAfterEdit;
250 });
251
252 this.onWebview("edit/clearDecorations", async (msg) => {
253 editDecorationManager.clear();
254 });
255
256 this.onWebview("session/share", async (msg) => {
257 await vscode.commands.executeCommand(
258 "continue.shareSession",
259 msg.data.sessionId,
260 );
261 });
262
263 /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
264 WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
265 this.onWebview(messageType, async (msg) => {
266 return await this.inProcessMessenger.externalRequest(
267 messageType,
268 msg.data,
269 msg.messageId,
270 );
271 });
272 });
273
274 /** PASS THROUGH FROM CORE TO WEBVIEW AND BACK **/
275 CORE_TO_WEBVIEW_PASS_THROUGH.forEach((messageType) => {
276 this.onCore(messageType, async (msg) => {
277 return this.webviewProtocol.request(messageType, msg.data);
278 });
279 });
280
281 /** CORE ONLY LISTENERS **/
282 // None right now
283
284 /** BOTH CORE AND WEBVIEW **/
285 this.onWebviewOrCore("readRangeInFile", async (msg) => {
286 return await vscode.workspace
287 .openTextDocument(msg.data.filepath)
288 .then((document) => {
289 const start = new vscode.Position(0, 0);
290 const end = new vscode.Position(5, 0);
291 const range = new vscode.Range(start, end);
292
293 const contents = document.getText(range);
294 return contents;
295 });
296 });
297
298 this.onWebviewOrCore("getIdeSettings", async (msg) => {
299 return ide.getIdeSettings();
300 });
301 this.onWebviewOrCore("getDiff", async (msg) => {
302 return ide.getDiff(msg.data.includeUnstaged);
303 });
304 this.onWebviewOrCore("getTerminalContents", async (msg) => {
305 return ide.getTerminalContents();
306 });
307 this.onWebviewOrCore("getDebugLocals", async (msg) => {
308 return ide.getDebugLocals(Number(msg.data.threadIndex));
309 });
310 this.onWebviewOrCore("getAvailableThreads", async (msg) => {
311 return ide.getAvailableThreads();
312 });
313 this.onWebviewOrCore("getTopLevelCallStackSources", async (msg) => {
314 return ide.getTopLevelCallStackSources(
315 msg.data.threadIndex,
316 msg.data.stackDepth,
317 );
318 });
319 this.onWebviewOrCore("getWorkspaceDirs", async (msg) => {
320 return ide.getWorkspaceDirs();
321 });
322 this.onWebviewOrCore("writeFile", async (msg) => {
323 return ide.writeFile(msg.data.path, msg.data.contents);
324 });
325 this.onWebviewOrCore("showVirtualFile", async (msg) => {
326 return ide.showVirtualFile(msg.data.name, msg.data.content);
327 });
328 this.onWebviewOrCore("openFile", async (msg) => {
329 return ide.openFile(msg.data.path);
330 });
331 this.onWebviewOrCore("runCommand", async (msg) => {
332 await ide.runCommand(msg.data.command);
333 });
334 this.onWebviewOrCore("getSearchResults", async (msg) => {
335 return ide.getSearchResults(msg.data.query, msg.data.maxResults);
336 });
337 this.onWebviewOrCore("getFileResults", async (msg) => {
338 return ide.getFileResults(msg.data.pattern, msg.data.maxResults);
339 });
340 this.onWebviewOrCore("subprocess", async (msg) => {
341 return ide.subprocess(msg.data.command, msg.data.cwd);
342 });
343 this.onWebviewOrCore("getProblems", async (msg) => {
344 return ide.getProblems(msg.data.filepath);
345 });
346 this.onWebviewOrCore("getBranch", async (msg) => {
347 const { dir } = msg.data;
348 return ide.getBranch(dir);
349 });
350 this.onWebviewOrCore("getOpenFiles", async (msg) => {
351 return ide.getOpenFiles();
352 });
353 this.onWebviewOrCore("getCurrentFile", async () => {
354 return ide.getCurrentFile();
355 });
356 this.onWebviewOrCore("getPinnedFiles", async (msg) => {
357 return ide.getPinnedFiles();
358 });
359 this.onWebviewOrCore("showLines", async (msg) => {
360 const { filepath, startLine, endLine } = msg.data;
361 return ide.showLines(filepath, startLine, endLine);
362 });
363 this.onWebviewOrCore("showToast", (msg) => {
364 this.ide.showToast(...msg.data);
365 });
366 this.onWebviewOrCore("getControlPlaneSessionInfo", async (msg) => {
367 return getControlPlaneSessionInfo(
368 msg.data.silent,
369 msg.data.useOnboarding,
370 );
371 });
372 this.onWebviewOrCore("logoutOfControlPlane", async (msg) => {
373 const sessions = await this.workOsAuthProvider.getSessions();
374 await Promise.all(
375 sessions.map((session) => workOsAuthProvider.removeSession(session.id)),
376 );
377 vscode.commands.executeCommand(
378 "setContext",
379 "continue.isSignedInToControlPlane",
380 false,
381 );
382 });
383 this.onWebviewOrCore("saveFile", async (msg) => {
384 return await ide.saveFile(msg.data.filepath);
385 });
386 this.onWebviewOrCore("readFile", async (msg) => {
387 return await ide.readFile(msg.data.filepath);
388 });
389 this.onWebviewOrCore("openUrl", (msg) => {
390 vscode.env.openExternal(vscode.Uri.parse(msg.data));
391 });
392
393 this.onWebviewOrCore("fileExists", async (msg) => {
394 return await ide.fileExists(msg.data.filepath);
395 });
396
397 this.onWebviewOrCore("gotoDefinition", async (msg) => {
398 return await ide.gotoDefinition(msg.data.location);
399 });
400
401 this.onWebviewOrCore("getReferences", async (msg) => {
402 return await ide.getReferences(msg.data.location);
403 });
404
405 this.onWebviewOrCore("getDocumentSymbols", async (msg) => {
406 return await ide.getDocumentSymbols(msg.data.textDocumentIdentifier);
407 });
408
409 this.onWebviewOrCore("getFileStats", async (msg) => {
410 return await ide.getFileStats(msg.data.files);
411 });
412
413 this.onWebviewOrCore("getGitRootPath", async (msg) => {
414 return await ide.getGitRootPath(msg.data.dir);
415 });
416
417 this.onWebviewOrCore("listDir", async (msg) => {
418 return await ide.listDir(msg.data.dir);
419 });
420
421 this.onWebviewOrCore("getRepoName", async (msg) => {
422 return await ide.getRepoName(msg.data.dir);
423 });
424
425 this.onWebviewOrCore("getTags", async (msg) => {
426 return await ide.getTags(msg.data);
427 });
428
429 this.onWebviewOrCore("getIdeInfo", async (msg) => {
430 return await ide.getIdeInfo();
431 });
432
433 this.onWebviewOrCore("isTelemetryEnabled", async (msg) => {
434 return await ide.isTelemetryEnabled();
435 });
436
437 this.onWebviewOrCore("getUniqueId", async (msg) => {
438 return await ide.getUniqueId();
439 });
440
441 this.onWebviewOrCore("reportError", async (msg) => {
442 await handleLLMError(msg.data);
443 });
444 }
445}