Elffuss BraidHub

kikocis/continue public

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