Elffuss BraidHub

kikocis/continue public

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