Elffuss BraidHub

kikocis/continue public

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