Elffuss BraidHub

kikocis/continue public

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