Elffuss BraidHub

kikocis/continue public

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