Elffuss BraidHub

kikocis/continue public

bd86bc3e9206 · 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";
33import { VsCodeExtension } from "./VsCodeExtension";
34
35type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol &
36 ToWebviewFromCoreProtocol;
37
38/**
39 * A shared messenger class between Core and Webview
40 * so we don't have to rewrite some of the handlers
41 */
42export class VsCodeMessenger {
43 onWebview<T extends keyof FromWebviewProtocol>(
44 messageType: T,
45 handler: (
46 message: Message<FromWebviewProtocol[T][0]>,
47 ) => Promise<FromWebviewProtocol[T][1]> | FromWebviewProtocol[T][1],
48 ): void {
49 void this.webviewProtocol.on(messageType, handler);
50 }
51
52 onCore<T extends keyof ToIdeOrWebviewFromCoreProtocol>(
53 messageType: T,
54 handler: (
55 message: Message<ToIdeOrWebviewFromCoreProtocol[T][0]>,
56 ) =>
57 | Promise<ToIdeOrWebviewFromCoreProtocol[T][1]>
58 | ToIdeOrWebviewFromCoreProtocol[T][1],
59 ): void {
60 this.inProcessMessenger.externalOn(messageType, handler);
61 }
62
63 onWebviewOrCore<T extends keyof ToIdeFromWebviewOrCoreProtocol>(
64 messageType: T,
65 handler: (
66 message: Message<ToIdeFromWebviewOrCoreProtocol[T][0]>,
67 ) =>
68 | Promise<ToIdeFromWebviewOrCoreProtocol[T][1]>
69 | ToIdeFromWebviewOrCoreProtocol[T][1],
70 ): void {
71 this.onWebview(messageType, handler);
72 this.onCore(messageType, handler);
73 }
74
75 constructor(
76 private readonly inProcessMessenger: InProcessMessenger<
77 ToCoreProtocol,
78 FromCoreProtocol
79 >,
80 private readonly webviewProtocol: VsCodeWebviewProtocol,
81 private readonly ide: VsCodeIde,
82 private readonly verticalDiffManagerPromise: Promise<VerticalDiffManager>,
83 private readonly configHandlerPromise: Promise<ConfigHandler>,
84 private readonly workOsAuthProvider: WorkOsAuthProvider,
85 private readonly editDecorationManager: EditDecorationManager,
86 private readonly context: vscode.ExtensionContext,
87 private readonly vsCodeExtension: VsCodeExtension,
88 ) {
89 /** WEBVIEW ONLY LISTENERS **/
90 this.onWebview("showFile", (msg) => {
91 this.ide.openFile(msg.data.filepath);
92 });
93
94 this.onWebview("vscode/openMoveRightMarkdown", (msg) => {
95 vscode.commands.executeCommand(
96 "markdown.showPreview",
97 vscode.Uri.joinPath(
98 getExtensionUri(),
99 "media",
100 "move-chat-panel-right.md",
101 ),
102 );
103 });
104
105 this.onWebview("toggleDevTools", (msg) => {
106 vscode.commands.executeCommand("continue.viewLogs");
107 });
108 this.onWebview("reloadWindow", (msg) => {
109 vscode.commands.executeCommand("workbench.action.reloadWindow");
110 });
111 this.onWebview("focusEditor", (msg) => {
112 vscode.commands.executeCommand("workbench.action.focusActiveEditorGroup");
113 });
114 this.onWebview("toggleFullScreen", (msg) => {
115 vscode.commands.executeCommand("continue.toggleFullScreen");
116 });
117
118 this.onWebview("acceptDiff", async ({ data: { filepath, streamId } }) => {
119 await vscode.commands.executeCommand(
120 "continue.acceptDiff",
121 filepath,
122 streamId,
123 );
124 });
125
126 this.onWebview("rejectDiff", async ({ data: { filepath, streamId } }) => {
127 await vscode.commands.executeCommand(
128 "continue.rejectDiff",
129 filepath,
130 streamId,
131 );
132 });
133
134 this.onWebview("applyToFile", async ({ data }) => {
135 const [verticalDiffManager, configHandler] = await Promise.all([
136 verticalDiffManagerPromise,
137 configHandlerPromise,
138 ]);
139
140 const applyManager = new ApplyManager(
141 this.ide,
142 webviewProtocol,
143 verticalDiffManager,
144 configHandler,
145 );
146
147 await applyManager.applyToFile(data);
148 });
149
150 this.onWebview("showTutorial", async (msg) => {
151 await showTutorial(this.ide);
152 });
153
154 this.onWebview(
155 "overwriteFile",
156 async ({ data: { prevFileContent, filepath } }) => {
157 if (prevFileContent === null) {
158 // TODO: Delete the file
159 return;
160 }
161
162 await this.ide.openFile(filepath);
163
164 // Get active text editor
165 const editor = vscode.window.activeTextEditor;
166
167 if (!editor) {
168 vscode.window.showErrorMessage("No active editor to apply edits to");
169 return;
170 }
171
172 editor.edit((builder) =>
173 builder.replace(
174 new vscode.Range(
175 editor.document.positionAt(0),
176 editor.document.positionAt(editor.document.getText().length),
177 ),
178 prevFileContent,
179 ),
180 );
181 },
182 );
183
184 this.onWebview("insertAtCursor", async (msg) => {
185 const editor = vscode.window.activeTextEditor;
186 if (editor === undefined || !editor.selection) {
187 return;
188 }
189
190 editor.edit((editBuilder) => {
191 editBuilder.replace(
192 new vscode.Range(editor.selection.start, editor.selection.end),
193 msg.data.text,
194 );
195 });
196 });
197 this.onWebview("edit/addCurrentSelection", async (msg) => {
198 const verticalDiffManager = await this.verticalDiffManagerPromise;
199 await addCurrentSelectionToEdit({
200 args: undefined,
201 editDecorationManager,
202 webviewProtocol: this.webviewProtocol,
203 verticalDiffManager,
204 });
205 });
206 this.onWebview("edit/sendPrompt", async (msg) => {
207 const prompt = msg.data.prompt;
208 const { start, end } = msg.data.range.range;
209 const verticalDiffManager = await verticalDiffManagerPromise;
210
211 const configHandler = await configHandlerPromise;
212 const { config } = await configHandler.loadConfig();
213
214 if (!config) {
215 throw new Error("Edit: Failed to load config");
216 }
217
218 const model =
219 config?.selectedModelByRole.edit ?? config?.selectedModelByRole.chat;
220
221 if (!model) {
222 throw new Error("No Edit or Chat model selected");
223 }
224
225 const fileAfterEdit = await verticalDiffManager.streamEdit({
226 input: stripImages(prompt),
227 llm: model,
228 streamId: EDIT_MODE_STREAM_ID,
229 range: new vscode.Range(
230 new vscode.Position(start.line, start.character),
231 new vscode.Position(end.line, end.character),
232 ),
233 rulesToInclude: config.rules,
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 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("getFileStats", async (msg) => {
394 return await ide.getFileStats(msg.data.files);
395 });
396
397 this.onWebviewOrCore("getGitRootPath", async (msg) => {
398 return await ide.getGitRootPath(msg.data.dir);
399 });
400
401 this.onWebviewOrCore("listDir", async (msg) => {
402 return await ide.listDir(msg.data.dir);
403 });
404
405 this.onWebviewOrCore("getRepoName", async (msg) => {
406 return await ide.getRepoName(msg.data.dir);
407 });
408
409 this.onWebviewOrCore("getTags", async (msg) => {
410 return await ide.getTags(msg.data);
411 });
412
413 this.onWebviewOrCore("getIdeInfo", async (msg) => {
414 return await ide.getIdeInfo();
415 });
416
417 this.onWebviewOrCore("isTelemetryEnabled", async (msg) => {
418 return await ide.isTelemetryEnabled();
419 });
420
421 this.onWebviewOrCore("getWorkspaceConfigs", async (msg) => {
422 return await ide.getWorkspaceConfigs();
423 });
424
425 this.onWebviewOrCore("getUniqueId", async (msg) => {
426 return await ide.getUniqueId();
427 });
428
429 this.onWebviewOrCore("reportError", async (msg) => {
430 await handleLLMError(msg.data);
431 });
432 }
433}