Elffuss BraidHub

kikocis/continue public

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