Elffuss BraidHub

kikocis/continue public

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