Elffuss BraidHub

kikocis/continue public

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