Elffuss BraidHub

kikocis/continue public

54ea0739010d · 29.2 KiBRawPermalink
1/* eslint-disable @typescript-eslint/naming-convention */
2import * as fs from "node:fs";
3
4import { ContextMenuConfig, ILLM, ModelInstaller } from "core";
5import { CompletionProvider } from "core/autocomplete/CompletionProvider";
6import { ConfigHandler } from "core/config/ConfigHandler";
7import { ContinueServerClient } from "core/continueServer/stubs/client";
8import { EXTENSION_NAME } from "core/control-plane/env";
9import { Core } from "core/core";
10import { LOCAL_DEV_DATA_VERSION } from "core/data/log";
11import { walkDirAsync } from "core/indexing/walkDir";
12import { isModelInstaller } from "core/llm";
13import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
14import { startLocalOllama } from "core/util/ollamaHelper";
15import {
16 getConfigJsonPath,
17 getConfigYamlPath,
18 getDevDataFilePath,
19} from "core/util/paths";
20import { Telemetry } from "core/util/posthog";
21import readLastLines from "read-last-lines";
22import * as vscode from "vscode";
23import * as YAML from "yaml";
24
25import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist";
26
27import {
28 getAutocompleteStatusBarDescription,
29 getAutocompleteStatusBarTitle,
30 getStatusBarStatus,
31 getStatusBarStatusFromQuickPickItemLabel,
32 quickPickStatusText,
33 setupStatusBar,
34 StatusBarStatus,
35} from "./autocomplete/statusBar";
36import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider";
37import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider";
38import { VerticalDiffManager } from "./diff/vertical/manager";
39import EditDecorationManager from "./quickEdit/EditDecorationManager";
40import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick";
41import {
42 addCodeToContextFromRange,
43 addEntireFileToContext,
44 addHighlightedCodeToContext,
45} from "./util/addCode";
46import { Battery } from "./util/battery";
47import { getMetaKeyLabel } from "./util/util";
48import { openEditorAndRevealRange } from "./util/vscode";
49import { VsCodeIde } from "./VsCodeIde";
50
51let fullScreenPanel: vscode.WebviewPanel | undefined;
52
53function getFullScreenTab() {
54 const tabs = vscode.window.tabGroups.all.flatMap((tabGroup) => tabGroup.tabs);
55 return tabs.find((tab) =>
56 (tab.input as any)?.viewType?.endsWith("continue.continueGUIView"),
57 );
58}
59
60type TelemetryCaptureParams = Parameters<typeof Telemetry.capture>;
61
62/**
63 * Helper method to add the `isCommandEvent` to all telemetry captures
64 */
65function captureCommandTelemetry(
66 commandName: TelemetryCaptureParams[0],
67 properties: TelemetryCaptureParams[1] = {},
68) {
69 Telemetry.capture(commandName, { isCommandEvent: true, ...properties });
70}
71
72function focusGUI() {
73 const fullScreenTab = getFullScreenTab();
74 if (fullScreenTab) {
75 // focus fullscreen
76 fullScreenPanel?.reveal();
77 } else {
78 // focus sidebar
79 vscode.commands.executeCommand("continue.continueGUIView.focus");
80 // vscode.commands.executeCommand("workbench.action.focusAuxiliaryBar");
81 }
82}
83
84function hideGUI() {
85 const fullScreenTab = getFullScreenTab();
86 if (fullScreenTab) {
87 // focus fullscreen
88 fullScreenPanel?.dispose();
89 } else {
90 // focus sidebar
91 vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
92 // vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar");
93 }
94}
95
96async function processDiff(
97 action: "accept" | "reject",
98 sidebar: ContinueGUIWebviewViewProvider,
99 ide: VsCodeIde,
100 core: Core,
101 verticalDiffManager: VerticalDiffManager,
102 newFileUri?: string,
103 streamId?: string,
104 toolCallId?: string,
105) {
106 captureCommandTelemetry(`${action}Diff`);
107
108 const currentFile = await ide.getCurrentFile();
109
110 let newOrCurrentUri = newFileUri;
111 if (!newOrCurrentUri) {
112 newOrCurrentUri = currentFile?.path;
113 }
114 if (!newOrCurrentUri) {
115 console.warn(
116 `No file provided or current file open while attempting to resolve diff`,
117 );
118 return;
119 }
120
121 await ide.openFile(newOrCurrentUri);
122
123 // Clear vertical diffs depending on action
124 verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
125 if (action === "reject") {
126 core.invoke("cancelApply", undefined);
127 }
128
129 if (streamId) {
130 const fileContent = await ide.readFile(newOrCurrentUri);
131
132 await sidebar.webviewProtocol.request("updateApplyState", {
133 fileContent,
134 filepath: newOrCurrentUri,
135 streamId,
136 status: "closed",
137 numDiffs: 0,
138 toolCallId,
139 });
140 }
141
142 // Save the file
143 await ide.saveFile(newOrCurrentUri);
144}
145
146function waitForSidebarReady(
147 sidebar: ContinueGUIWebviewViewProvider,
148 timeout: number,
149 interval: number,
150): Promise<boolean> {
151 return new Promise((resolve) => {
152 const startTime = Date.now();
153
154 const checkReadyState = () => {
155 if (sidebar.isReady) {
156 resolve(true);
157 } else if (Date.now() - startTime >= timeout) {
158 resolve(false); // Timed out
159 } else {
160 setTimeout(checkReadyState, interval);
161 }
162 };
163
164 checkReadyState();
165 });
166}
167
168// Copy everything over from extension.ts
169const getCommandsMap: (
170 ide: VsCodeIde,
171 extensionContext: vscode.ExtensionContext,
172 sidebar: ContinueGUIWebviewViewProvider,
173 consoleView: ContinueConsoleWebviewViewProvider,
174 configHandler: ConfigHandler,
175 verticalDiffManager: VerticalDiffManager,
176 continueServerClientPromise: Promise<ContinueServerClient>,
177 battery: Battery,
178 quickEdit: QuickEdit,
179 core: Core,
180 editDecorationManager: EditDecorationManager,
181) => { [command: string]: (...args: any) => any } = (
182 ide,
183 extensionContext,
184 sidebar,
185 consoleView,
186 configHandler,
187 verticalDiffManager,
188 continueServerClientPromise,
189 battery,
190 quickEdit,
191 core,
192 editDecorationManager,
193) => {
194 /**
195 * Streams an inline edit to the vertical diff manager.
196 *
197 * This function retrieves the configuration, determines the appropriate model title,
198 * increments the FTC count, and then streams an edit to the
199 * vertical diff manager.
200 *
201 * @param promptName - The key for the prompt in the context menu configuration.
202 * @param fallbackPrompt - The prompt to use if the configured prompt is not available.
203 * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made.
204 * @param [range] - Optional. The range to edit if provided.
205 * @returns
206 */
207 async function streamInlineEdit(
208 promptName: keyof ContextMenuConfig,
209 fallbackPrompt: string,
210 onlyOneInsertion?: boolean,
211 range?: vscode.Range,
212 ) {
213 const { config } = await configHandler.loadConfig();
214 if (!config) {
215 throw new Error("Config not loaded");
216 }
217
218 const llm =
219 config.selectedModelByRole.edit ?? config.selectedModelByRole.chat;
220
221 if (!llm) {
222 throw new Error("No edit or chat model selected");
223 }
224
225 void sidebar.webviewProtocol.request("incrementFtc", undefined);
226
227 await verticalDiffManager.streamEdit({
228 input:
229 config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt,
230 llm,
231 onlyOneInsertion,
232 range,
233 rulesToInclude: config.rules,
234 });
235 }
236
237 return {
238 "continue.acceptDiff": async (newFileUri?: string, streamId?: string) =>
239 processDiff(
240 "accept",
241 sidebar,
242 ide,
243 core,
244 verticalDiffManager,
245 newFileUri,
246 streamId,
247 ),
248
249 "continue.rejectDiff": async (newFileUri?: string, streamId?: string) =>
250 processDiff(
251 "reject",
252 sidebar,
253 ide,
254 core,
255 verticalDiffManager,
256 newFileUri,
257 streamId,
258 ),
259 "continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => {
260 captureCommandTelemetry("acceptVerticalDiffBlock");
261 verticalDiffManager.acceptRejectVerticalDiffBlock(true, fileUri, index);
262 },
263 "continue.rejectVerticalDiffBlock": (fileUri?: string, index?: number) => {
264 captureCommandTelemetry("rejectVerticalDiffBlock");
265 verticalDiffManager.acceptRejectVerticalDiffBlock(false, fileUri, index);
266 },
267 "continue.quickFix": async (
268 range: vscode.Range,
269 diagnosticMessage: string,
270 ) => {
271 captureCommandTelemetry("quickFix");
272
273 const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`;
274
275 addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt);
276
277 vscode.commands.executeCommand("continue.continueGUIView.focus");
278 },
279 // Passthrough for telemetry purposes
280 "continue.defaultQuickAction": async (args: QuickEditShowParams) => {
281 captureCommandTelemetry("defaultQuickAction");
282 vscode.commands.executeCommand("continue.focusEdit", args);
283 },
284 "continue.customQuickActionSendToChat": async (
285 prompt: string,
286 range: vscode.Range,
287 ) => {
288 captureCommandTelemetry("customQuickActionSendToChat");
289
290 addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt);
291
292 vscode.commands.executeCommand("continue.continueGUIView.focus");
293 },
294 "continue.customQuickActionStreamInlineEdit": async (
295 prompt: string,
296 range: vscode.Range,
297 ) => {
298 captureCommandTelemetry("customQuickActionStreamInlineEdit");
299
300 streamInlineEdit("docstring", prompt, false, range);
301 },
302 "continue.codebaseForceReIndex": async () => {
303 core.invoke("index/forceReIndex", undefined);
304 },
305 "continue.rebuildCodebaseIndex": async () => {
306 core.invoke("index/forceReIndex", { shouldClearIndexes: true });
307 },
308 "continue.docsIndex": async () => {
309 core.invoke("context/indexDocs", { reIndex: false });
310 },
311 "continue.docsReIndex": async () => {
312 core.invoke("context/indexDocs", { reIndex: true });
313 },
314 "continue.focusContinueInput": async () => {
315 const isContinueInputFocused = await sidebar.webviewProtocol.request(
316 "isContinueInputFocused",
317 undefined,
318 false,
319 );
320
321 // This is a temporary fix—sidebar.webviewProtocol.request is blocking
322 // when the GUI hasn't yet been setup and we should instead be
323 // immediately throwing an error, or returning a Result object
324 focusGUI();
325 if (!sidebar.isReady) {
326 const isReady = await waitForSidebarReady(sidebar, 5000, 100);
327 if (!isReady) {
328 return;
329 }
330 }
331
332 const historyLength = await sidebar.webviewProtocol.request(
333 "getWebviewHistoryLength",
334 undefined,
335 false,
336 );
337
338 if (isContinueInputFocused) {
339 if (historyLength === 0) {
340 hideGUI();
341 } else {
342 void sidebar.webviewProtocol?.request(
343 "focusContinueInputWithNewSession",
344 undefined,
345 false,
346 );
347 }
348 } else {
349 focusGUI();
350 sidebar.webviewProtocol?.request(
351 "focusContinueInputWithNewSession",
352 undefined,
353 false,
354 );
355 void addHighlightedCodeToContext(sidebar.webviewProtocol);
356 }
357 },
358 "continue.focusContinueInputWithoutClear": async () => {
359 const isContinueInputFocused = await sidebar.webviewProtocol.request(
360 "isContinueInputFocused",
361 undefined,
362 false,
363 );
364
365 // This is a temporary fix—sidebar.webviewProtocol.request is blocking
366 // when the GUI hasn't yet been setup and we should instead be
367 // immediately throwing an error, or returning a Result object
368 focusGUI();
369 if (!sidebar.isReady) {
370 const isReady = await waitForSidebarReady(sidebar, 5000, 100);
371 if (!isReady) {
372 return;
373 }
374 }
375
376 if (isContinueInputFocused) {
377 hideGUI();
378 } else {
379 focusGUI();
380
381 sidebar.webviewProtocol?.request(
382 "focusContinueInputWithoutClear",
383 undefined,
384 );
385
386 void addHighlightedCodeToContext(sidebar.webviewProtocol);
387 }
388 },
389 // QuickEditShowParams are passed from CodeLens, temp fix
390 // until we update to new params specific to Edit
391 "continue.focusEdit": async (args?: QuickEditShowParams) => {
392 captureCommandTelemetry("focusEdit");
393 focusGUI();
394 sidebar.webviewProtocol?.request("focusEdit", undefined);
395 },
396 "continue.exitEditMode": async () => {
397 captureCommandTelemetry("exitEditMode");
398 editDecorationManager.clear();
399 void sidebar.webviewProtocol?.request("exitEditMode", undefined);
400 },
401 "continue.writeCommentsForCode": async () => {
402 captureCommandTelemetry("writeCommentsForCode");
403
404 streamInlineEdit(
405 "comment",
406 "Write comments for this code. Do not change anything about the code itself.",
407 );
408 },
409 "continue.writeDocstringForCode": async () => {
410 captureCommandTelemetry("writeDocstringForCode");
411
412 streamInlineEdit(
413 "docstring",
414 "Write a docstring for this code. Do not change anything about the code itself.",
415 true,
416 );
417 },
418 "continue.fixCode": async () => {
419 captureCommandTelemetry("fixCode");
420
421 streamInlineEdit(
422 "fix",
423 "Fix this code. If it is already 100% correct, simply rewrite the code.",
424 );
425 },
426 "continue.optimizeCode": async () => {
427 captureCommandTelemetry("optimizeCode");
428 streamInlineEdit("optimize", "Optimize this code");
429 },
430 "continue.fixGrammar": async () => {
431 captureCommandTelemetry("fixGrammar");
432 streamInlineEdit(
433 "fixGrammar",
434 "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.",
435 );
436 },
437 "continue.clearConsole": async () => {
438 consoleView.clearLog();
439 },
440 "continue.viewLogs": async () => {
441 captureCommandTelemetry("viewLogs");
442 vscode.commands.executeCommand("workbench.action.toggleDevTools");
443 },
444 "continue.debugTerminal": async () => {
445 captureCommandTelemetry("debugTerminal");
446
447 const terminalContents = await ide.getTerminalContents();
448
449 vscode.commands.executeCommand("continue.continueGUIView.focus");
450
451 sidebar.webviewProtocol?.request("userInput", {
452 input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`,
453 });
454 },
455 "continue.hideInlineTip": () => {
456 vscode.workspace
457 .getConfiguration(EXTENSION_NAME)
458 .update("showInlineTip", false, vscode.ConfigurationTarget.Global);
459 },
460
461 // Commands without keyboard shortcuts
462 "continue.addModel": () => {
463 captureCommandTelemetry("addModel");
464
465 vscode.commands.executeCommand("continue.continueGUIView.focus");
466 sidebar.webviewProtocol?.request("addModel", undefined);
467 },
468 "continue.newSession": () => {
469 sidebar.webviewProtocol?.request("newSession", undefined);
470 },
471 "continue.viewHistory": () => {
472 vscode.commands.executeCommand("continue.navigateTo", "/history", true);
473 },
474 "continue.focusContinueSessionId": async (
475 sessionId: string | undefined,
476 ) => {
477 if (!sessionId) {
478 sessionId = await vscode.window.showInputBox({
479 prompt: "Enter the Session ID",
480 });
481 }
482 void sidebar.webviewProtocol?.request("focusContinueSessionId", {
483 sessionId,
484 });
485 },
486 "continue.applyCodeFromChat": () => {
487 void sidebar.webviewProtocol.request("applyCodeFromChat", undefined);
488 },
489 "continue.toggleFullScreen": async () => {
490 focusGUI();
491
492 const sessionId = await sidebar.webviewProtocol.request(
493 "getCurrentSessionId",
494 undefined,
495 );
496 // Check if full screen is already open by checking open tabs
497 const fullScreenTab = getFullScreenTab();
498
499 if (fullScreenTab && fullScreenPanel) {
500 // Full screen open, but not focused - focus it
501 fullScreenPanel.reveal();
502 return;
503 }
504
505 // Clear the sidebar to prevent overwriting changes made in fullscreen
506 vscode.commands.executeCommand("continue.newSession");
507
508 // Full screen not open - open it
509 captureCommandTelemetry("openFullScreen");
510
511 // Create the full screen panel
512 let panel = vscode.window.createWebviewPanel(
513 "continue.continueGUIView",
514 "Continue",
515 vscode.ViewColumn.One,
516 {
517 retainContextWhenHidden: true,
518 enableScripts: true,
519 },
520 );
521 fullScreenPanel = panel;
522
523 // Add content to the panel
524 panel.webview.html = sidebar.getSidebarContent(
525 extensionContext,
526 panel,
527 undefined,
528 undefined,
529 true,
530 );
531
532 const sessionLoader = panel.onDidChangeViewState(() => {
533 vscode.commands.executeCommand("continue.newSession");
534 if (sessionId) {
535 vscode.commands.executeCommand(
536 "continue.focusContinueSessionId",
537 sessionId,
538 );
539 }
540 panel.reveal();
541 sessionLoader.dispose();
542 });
543
544 // When panel closes, reset the webview and focus
545 panel.onDidDispose(
546 () => {
547 sidebar.resetWebviewProtocolWebview();
548 vscode.commands.executeCommand("continue.focusContinueInput");
549 },
550 null,
551 extensionContext.subscriptions,
552 );
553
554 vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow");
555 vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
556 },
557 "continue.openConfigPage": () => {
558 vscode.commands.executeCommand("continue.navigateTo", "/config", false);
559 },
560 "continue.selectFilesAsContext": async (
561 firstUri: vscode.Uri,
562 uris: vscode.Uri[],
563 ) => {
564 if (uris === undefined) {
565 throw new Error("No files were selected");
566 }
567
568 vscode.commands.executeCommand("continue.continueGUIView.focus");
569
570 for (const uri of uris) {
571 // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files)
572 const isDirectory = await vscode.workspace.fs
573 .stat(uri)
574 ?.then((stat) => stat.type === vscode.FileType.Directory);
575 if (isDirectory) {
576 for await (const fileUri of walkDirAsync(uri.toString(), ide, {
577 source: "vscode continue.selectFilesAsContext command",
578 })) {
579 await addEntireFileToContext(
580 vscode.Uri.parse(fileUri),
581 sidebar.webviewProtocol,
582 ide.ideUtils,
583 );
584 }
585 } else {
586 await addEntireFileToContext(
587 uri,
588 sidebar.webviewProtocol,
589 ide.ideUtils,
590 );
591 }
592 }
593 },
594 "continue.logAutocompleteOutcome": (
595 completionId: string,
596 completionProvider: CompletionProvider,
597 ) => {
598 completionProvider.accept(completionId);
599 },
600 "continue.toggleTabAutocompleteEnabled": () => {
601 captureCommandTelemetry("toggleTabAutocompleteEnabled");
602
603 const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
604 const enabled = config.get("enableTabAutocomplete");
605 const pauseOnBattery = config.get<boolean>(
606 "pauseTabAutocompleteOnBattery",
607 );
608 if (!pauseOnBattery || battery.isACConnected()) {
609 config.update(
610 "enableTabAutocomplete",
611 !enabled,
612 vscode.ConfigurationTarget.Global,
613 );
614 } else {
615 if (enabled) {
616 const paused = getStatusBarStatus() === StatusBarStatus.Paused;
617 if (paused) {
618 setupStatusBar(StatusBarStatus.Enabled);
619 } else {
620 config.update(
621 "enableTabAutocomplete",
622 false,
623 vscode.ConfigurationTarget.Global,
624 );
625 }
626 } else {
627 setupStatusBar(StatusBarStatus.Paused);
628 config.update(
629 "enableTabAutocomplete",
630 true,
631 vscode.ConfigurationTarget.Global,
632 );
633 }
634 }
635 },
636 "continue.openTabAutocompleteConfigMenu": async () => {
637 captureCommandTelemetry("openTabAutocompleteConfigMenu");
638
639 const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
640 const quickPick = vscode.window.createQuickPick();
641
642 const { config: continueConfig } = await configHandler.loadConfig();
643 const autocompleteModels =
644 continueConfig?.modelsByRole.autocomplete ?? [];
645 const selected =
646 continueConfig?.selectedModelByRole?.autocomplete?.title ?? undefined;
647
648 // Toggle between Disabled, Paused, and Enabled
649 const pauseOnBattery =
650 config.get<boolean>("pauseTabAutocompleteOnBattery") &&
651 !battery.isACConnected();
652 const currentStatus = getStatusBarStatus();
653
654 let targetStatus: StatusBarStatus | undefined;
655 if (pauseOnBattery) {
656 // Cycle from Disabled -> Paused -> Enabled
657 targetStatus =
658 currentStatus === StatusBarStatus.Paused
659 ? StatusBarStatus.Enabled
660 : currentStatus === StatusBarStatus.Disabled
661 ? StatusBarStatus.Paused
662 : StatusBarStatus.Disabled;
663 } else {
664 // Toggle between Disabled and Enabled
665 targetStatus =
666 currentStatus === StatusBarStatus.Disabled
667 ? StatusBarStatus.Enabled
668 : StatusBarStatus.Disabled;
669 }
670
671 quickPick.items = [
672 {
673 label: "$(gear) Open settings",
674 },
675 {
676 label: "$(comment) Open chat",
677 description: getMetaKeyLabel() + " + L",
678 },
679 {
680 label: "$(screen-full) Open full screen chat",
681 description:
682 getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + M",
683 },
684 {
685 label: quickPickStatusText(targetStatus),
686 description:
687 getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + A",
688 },
689 {
690 label: "$(feedback) Give feedback",
691 },
692 {
693 kind: vscode.QuickPickItemKind.Separator,
694 label: "Switch model",
695 },
696 ...autocompleteModels.map((model) => ({
697 label: getAutocompleteStatusBarTitle(selected, model),
698 description: getAutocompleteStatusBarDescription(selected, model),
699 })),
700 ];
701 quickPick.onDidAccept(() => {
702 const selectedOption = quickPick.selectedItems[0].label;
703 const targetStatus =
704 getStatusBarStatusFromQuickPickItemLabel(selectedOption);
705
706 if (targetStatus !== undefined) {
707 setupStatusBar(targetStatus);
708 config.update(
709 "enableTabAutocomplete",
710 targetStatus === StatusBarStatus.Enabled,
711 vscode.ConfigurationTarget.Global,
712 );
713 } else if (
714 autocompleteModels.some((model) => model.title === selectedOption)
715 ) {
716 if (core.configHandler.currentProfile?.profileDescription.id) {
717 core.invoke("config/updateSelectedModel", {
718 profileId:
719 core.configHandler.currentProfile?.profileDescription.id,
720 role: "autocomplete",
721 title: selectedOption,
722 });
723 }
724 } else if (selectedOption === "$(feedback) Give feedback") {
725 vscode.commands.executeCommand("continue.giveAutocompleteFeedback");
726 } else if (selectedOption === "$(comment) Open chat") {
727 vscode.commands.executeCommand("continue.focusContinueInput");
728 } else if (selectedOption === "$(screen-full) Open full screen chat") {
729 vscode.commands.executeCommand("continue.toggleFullScreen");
730 } else if (selectedOption === "$(gear) Open settings") {
731 vscode.commands.executeCommand("continue.navigateTo", "/config");
732 }
733
734 quickPick.dispose();
735 });
736 quickPick.show();
737 },
738 "continue.giveAutocompleteFeedback": async () => {
739 const feedback = await vscode.window.showInputBox({
740 ignoreFocusOut: true,
741 prompt:
742 "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.",
743 });
744 if (feedback) {
745 const client = await continueServerClientPromise;
746 const completionsPath = getDevDataFilePath(
747 "autocomplete",
748 LOCAL_DEV_DATA_VERSION,
749 );
750
751 const lastLines = await readLastLines.read(completionsPath, 2);
752 client.sendFeedback(feedback, lastLines);
753 }
754 },
755 "continue.navigateTo": (path: string, toggle: boolean) => {
756 sidebar.webviewProtocol?.request("navigateTo", { path, toggle });
757 focusGUI();
758 },
759 "continue.startLocalOllama": () => {
760 startLocalOllama(ide);
761 },
762 "continue.installModel": async (
763 modelName: string,
764 llmProvider: ILLM | undefined,
765 ) => {
766 try {
767 if (!isModelInstaller(llmProvider)) {
768 const msg = llmProvider
769 ? `LLM provider '${llmProvider.providerName}' does not support installing models`
770 : "Missing LLM Provider";
771 throw new Error(msg);
772 }
773 await installModelWithProgress(modelName, llmProvider);
774 } catch (e) {
775 const message = e instanceof Error ? e.message : String(e);
776 vscode.window.showErrorMessage(
777 `Failed to install '${modelName}': ${message}`,
778 );
779 }
780 },
781 "continue.convertConfigJsonToConfigYaml": async () => {
782 const configJson = fs.readFileSync(getConfigJsonPath(), "utf-8");
783 const parsed = JSON.parse(configJson);
784 const configYaml = convertJsonToYamlConfig(parsed);
785
786 const configYamlPath = getConfigYamlPath();
787 fs.writeFileSync(configYamlPath, YAML.stringify(configYaml));
788
789 // Open config.yaml
790 await openEditorAndRevealRange(
791 vscode.Uri.file(configYamlPath),
792 undefined,
793 undefined,
794 false,
795 );
796
797 vscode.window
798 .showInformationMessage(
799 "Your config.json has been converted to the new config.yaml format. If you need to switch back to config.json, you can delete or rename config.yaml.",
800 "Read the docs",
801 )
802 .then((selection) => {
803 if (selection === "Read the docs") {
804 vscode.env.openExternal(
805 vscode.Uri.parse("https://docs.continue.dev/yaml-migration"),
806 );
807 }
808 });
809 },
810 };
811};
812
813const registerCopyBufferService = (
814 context: vscode.ExtensionContext,
815 core: Core,
816) => {
817 const typeDisposable = vscode.commands.registerCommand(
818 "editor.action.clipboardCopyAction",
819 async (arg) => doCopy(typeDisposable),
820 );
821
822 async function doCopy(typeDisposable: any) {
823 typeDisposable.dispose(); // must dispose to avoid endless loops
824
825 await vscode.commands.executeCommand("editor.action.clipboardCopyAction");
826
827 const clipboardText = await vscode.env.clipboard.readText();
828
829 if (clipboardText) {
830 core.invoke("clipboardCache/add", {
831 content: clipboardText,
832 });
833 }
834
835 await context.workspaceState.update("continue.copyBuffer", {
836 text: clipboardText,
837 copiedAt: new Date().toISOString(),
838 });
839
840 // re-register to continue intercepting copy commands
841 typeDisposable = vscode.commands.registerCommand(
842 "editor.action.clipboardCopyAction",
843 async () => doCopy(typeDisposable),
844 );
845 context.subscriptions.push(typeDisposable);
846 }
847
848 context.subscriptions.push(typeDisposable);
849};
850
851async function installModelWithProgress(
852 modelName: string,
853 modelInstaller: ModelInstaller,
854) {
855 return vscode.window.withProgress(
856 {
857 location: vscode.ProgressLocation.Notification,
858 title: `Installing model '${modelName}'`,
859 cancellable: true,
860 },
861 async (windowProgress, token) => {
862 let currentProgress: number = 0;
863 const progressWrapper = (
864 details: string,
865 worked?: number,
866 total?: number,
867 ) => {
868 let increment = 0;
869 if (worked && total) {
870 const progressValue = Math.round((worked / total) * 100);
871 increment = progressValue - currentProgress;
872 currentProgress = progressValue;
873 }
874 windowProgress.report({ message: details, increment });
875 };
876 const abortController = new AbortController();
877 token.onCancellationRequested(() => {
878 console.log(`Pulling ${modelName} model was cancelled`);
879 abortController.abort();
880 });
881 await modelInstaller.installModel(
882 modelName,
883 abortController.signal,
884 progressWrapper,
885 );
886 },
887 );
888}
889
890export function registerAllCommands(
891 context: vscode.ExtensionContext,
892 ide: VsCodeIde,
893 extensionContext: vscode.ExtensionContext,
894 sidebar: ContinueGUIWebviewViewProvider,
895 consoleView: ContinueConsoleWebviewViewProvider,
896 configHandler: ConfigHandler,
897 verticalDiffManager: VerticalDiffManager,
898 continueServerClientPromise: Promise<ContinueServerClient>,
899 battery: Battery,
900 quickEdit: QuickEdit,
901 core: Core,
902 editDecorationManager: EditDecorationManager,
903) {
904 for (const [command, callback] of Object.entries(
905 getCommandsMap(
906 ide,
907 extensionContext,
908 sidebar,
909 consoleView,
910 configHandler,
911 verticalDiffManager,
912 continueServerClientPromise,
913 battery,
914 quickEdit,
915 core,
916 editDecorationManager,
917 ),
918 )) {
919 context.subscriptions.push(
920 vscode.commands.registerCommand(command, callback),
921 );
922 }
923
924 try {
925 registerCopyBufferService(context, core);
926 } catch (e: any) {
927 //Non-critical error, it needs to be intercepted and not prevent the extension from starting
928 console.log("Error registering CopyBufferService: ", e);
929 Telemetry.capture(
930 "vscode_extension_copy_buffer_failure",
931 {
932 stack: extractMinimalStackTraceInfo(e.stack),
933 message: e.message,
934 },
935 false,
936 true,
937 );
938 }
939}