Elffuss BraidHub

kikocis/continue public

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