Elffuss BraidHub

kikocis/continue public

f6e539b7524c · 29.1 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 [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.toggleTabAutocompleteEnabled": () => {
548 captureCommandTelemetry("toggleTabAutocompleteEnabled");
549
550 const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
551 const enabled = config.get("enableTabAutocomplete");
552 const pauseOnBattery = config.get<boolean>(
553 "pauseTabAutocompleteOnBattery",
554 );
555 if (!pauseOnBattery || battery.isACConnected()) {
556 config.update(
557 "enableTabAutocomplete",
558 !enabled,
559 vscode.ConfigurationTarget.Global,
560 );
561 } else {
562 if (enabled) {
563 const paused = getStatusBarStatus() === StatusBarStatus.Paused;
564 if (paused) {
565 setupStatusBar(StatusBarStatus.Enabled);
566 } else {
567 config.update(
568 "enableTabAutocomplete",
569 false,
570 vscode.ConfigurationTarget.Global,
571 );
572 }
573 } else {
574 setupStatusBar(StatusBarStatus.Paused);
575 config.update(
576 "enableTabAutocomplete",
577 true,
578 vscode.ConfigurationTarget.Global,
579 );
580 }
581 }
582 },
583 "continue.forceAutocomplete": async () => {
584 captureCommandTelemetry("forceAutocomplete");
585
586 // 1. Explicitly hide any existing suggestion. This clears VS Code's cache for the current position.
587 await vscode.commands.executeCommand("editor.action.inlineSuggest.hide");
588
589 // 2. Now trigger a new one. VS Code has no cached suggestion, so it's forced to call our provider.
590 await vscode.commands.executeCommand(
591 "editor.action.inlineSuggest.trigger",
592 );
593 },
594
595 "continue.openTabAutocompleteConfigMenu": async () => {
596 captureCommandTelemetry("openTabAutocompleteConfigMenu");
597
598 const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
599 const quickPick = vscode.window.createQuickPick();
600
601 const { config: continueConfig } = await configHandler.loadConfig();
602 const autocompleteModels =
603 continueConfig?.modelsByRole.autocomplete ?? [];
604 const selected =
605 continueConfig?.selectedModelByRole?.autocomplete?.title ?? undefined;
606
607 // Toggle between Disabled, Paused, and Enabled
608 const pauseOnBattery =
609 config.get<boolean>("pauseTabAutocompleteOnBattery") &&
610 !battery.isACConnected();
611 const currentStatus = getStatusBarStatus();
612
613 let targetStatus: StatusBarStatus | undefined;
614 if (pauseOnBattery) {
615 // Cycle from Disabled -> Paused -> Enabled
616 targetStatus =
617 currentStatus === StatusBarStatus.Paused
618 ? StatusBarStatus.Enabled
619 : currentStatus === StatusBarStatus.Disabled
620 ? StatusBarStatus.Paused
621 : StatusBarStatus.Disabled;
622 } else {
623 // Toggle between Disabled and Enabled
624 targetStatus =
625 currentStatus === StatusBarStatus.Disabled
626 ? StatusBarStatus.Enabled
627 : StatusBarStatus.Disabled;
628 }
629
630 quickPick.items = [
631 {
632 label: "$(gear) Open settings",
633 },
634 {
635 label: "$(comment) Open chat",
636 description: getMetaKeyLabel() + " + L",
637 },
638 {
639 label: "$(screen-full) Open full screen chat",
640 description:
641 getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + M",
642 },
643 {
644 label: quickPickStatusText(targetStatus),
645 description:
646 getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + A",
647 },
648 {
649 kind: vscode.QuickPickItemKind.Separator,
650 label: "Switch model",
651 },
652 ...autocompleteModels.map((model) => ({
653 label: getAutocompleteStatusBarTitle(selected, model),
654 description: getAutocompleteStatusBarDescription(selected, model),
655 })),
656 ];
657 quickPick.onDidAccept(() => {
658 const selectedOption = quickPick.selectedItems[0].label;
659 const targetStatus =
660 getStatusBarStatusFromQuickPickItemLabel(selectedOption);
661
662 if (targetStatus !== undefined) {
663 setupStatusBar(targetStatus);
664 config.update(
665 "enableTabAutocomplete",
666 targetStatus === StatusBarStatus.Enabled,
667 vscode.ConfigurationTarget.Global,
668 );
669 } else if (
670 autocompleteModels.some((model) => model.title === selectedOption)
671 ) {
672 if (core.configHandler.currentProfile?.profileDescription.id) {
673 core.invoke("config/updateSelectedModel", {
674 profileId:
675 core.configHandler.currentProfile?.profileDescription.id,
676 role: "autocomplete",
677 title: selectedOption,
678 });
679 }
680 } else if (selectedOption === "$(comment) Open chat") {
681 vscode.commands.executeCommand("continue.focusContinueInput");
682 } else if (selectedOption === "$(screen-full) Open full screen chat") {
683 vscode.commands.executeCommand("continue.toggleFullScreen");
684 } else if (selectedOption === "$(gear) Open settings") {
685 vscode.commands.executeCommand("continue.navigateTo", "/config");
686 }
687
688 quickPick.dispose();
689 });
690 quickPick.show();
691 },
692 "continue.navigateTo": (path: string, toggle: boolean) => {
693 sidebar.webviewProtocol?.request("navigateTo", { path, toggle });
694 focusGUI();
695 },
696 "continue.startLocalOllama": () => {
697 startLocalOllama(ide);
698 },
699 "continue.installModel": async (
700 modelName: string,
701 llmProvider: ILLM | undefined,
702 ) => {
703 try {
704 if (!isModelInstaller(llmProvider)) {
705 const msg = llmProvider
706 ? `LLM provider '${llmProvider.providerName}' does not support installing models`
707 : "Missing LLM Provider";
708 throw new Error(msg);
709 }
710 await installModelWithProgress(modelName, llmProvider);
711 } catch (e) {
712 const message = e instanceof Error ? e.message : String(e);
713 vscode.window.showErrorMessage(
714 `Failed to install '${modelName}': ${message}`,
715 );
716 }
717 },
718 "continue.convertConfigJsonToConfigYaml": async () => {
719 const configJson = fs.readFileSync(getConfigJsonPath(), "utf-8");
720 const parsed = JSON.parse(configJson);
721 const configYaml = convertJsonToYamlConfig(parsed);
722
723 const configYamlPath = getConfigYamlPath();
724 fs.writeFileSync(configYamlPath, YAML.stringify(configYaml));
725
726 // Open config.yaml
727 await openEditorAndRevealRange(
728 vscode.Uri.file(configYamlPath),
729 undefined,
730 undefined,
731 false,
732 );
733
734 void vscode.window
735 .showInformationMessage(
736 "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.",
737 "Read the docs",
738 )
739 .then(async (selection) => {
740 if (selection === "Read the docs") {
741 await vscode.env.openExternal(
742 vscode.Uri.parse("https://docs.continue.dev/yaml-migration"),
743 );
744 }
745 });
746 },
747 "continue.enterEnterpriseLicenseKey": async () => {
748 captureCommandTelemetry("enterEnterpriseLicenseKey");
749
750 const licenseKey = await vscode.window.showInputBox({
751 prompt: "Enter your enterprise license key",
752 password: true,
753 ignoreFocusOut: true,
754 placeHolder: "License key",
755 });
756
757 if (!licenseKey) {
758 return;
759 }
760
761 try {
762 const isValid = core.invoke("mdm/setLicenseKey", {
763 licenseKey,
764 });
765
766 if (isValid) {
767 void vscode.window.showInformationMessage(
768 "Enterprise license key successfully validated and saved. Reloading window.",
769 );
770 await new Promise((resolve) => setTimeout(resolve, 1000));
771 await vscode.commands.executeCommand("workbench.action.reloadWindow");
772 } else {
773 void vscode.window.showErrorMessage(
774 "Invalid license key. Please check your license key and try again.",
775 );
776 }
777 } catch (error) {
778 void vscode.window.showErrorMessage(
779 `Failed to set enterprise license key: ${error instanceof Error ? error.message : String(error)}`,
780 );
781 }
782 },
783 "continue.forceNextEdit": async () => {
784 captureCommandTelemetry("forceNextEdit");
785
786 // This is basically the same logic as forceAutocomplete.
787 // I'm writing a new command KV pair here in case we diverge in features.
788
789 await vscode.commands.executeCommand("editor.action.inlineSuggest.hide");
790
791 await vscode.commands.executeCommand(
792 "editor.action.inlineSuggest.trigger",
793 );
794 },
795 };
796};
797
798const registerCopyBufferService = (
799 context: vscode.ExtensionContext,
800 core: Core,
801) => {
802 const typeDisposable = vscode.commands.registerCommand(
803 "editor.action.clipboardCopyAction",
804 async (arg) => doCopy(typeDisposable),
805 );
806
807 async function doCopy(typeDisposable: any) {
808 typeDisposable.dispose(); // must dispose to avoid endless loops
809
810 await vscode.commands.executeCommand("editor.action.clipboardCopyAction");
811
812 const clipboardText = await vscode.env.clipboard.readText();
813
814 if (clipboardText) {
815 core.invoke("clipboardCache/add", {
816 content: clipboardText,
817 });
818 }
819
820 await context.workspaceState.update("continue.copyBuffer", {
821 text: clipboardText,
822 copiedAt: new Date().toISOString(),
823 });
824
825 // re-register to continue intercepting copy commands
826 typeDisposable = vscode.commands.registerCommand(
827 "editor.action.clipboardCopyAction",
828 async () => doCopy(typeDisposable),
829 );
830 context.subscriptions.push(typeDisposable);
831 }
832
833 context.subscriptions.push(typeDisposable);
834};
835
836async function installModelWithProgress(
837 modelName: string,
838 modelInstaller: ModelInstaller,
839) {
840 return vscode.window.withProgress(
841 {
842 location: vscode.ProgressLocation.Notification,
843 title: `Installing model '${modelName}'`,
844 cancellable: true,
845 },
846 async (windowProgress, token) => {
847 let currentProgress: number = 0;
848 const progressWrapper = (
849 details: string,
850 worked?: number,
851 total?: number,
852 ) => {
853 let increment = 0;
854 if (worked && total) {
855 const progressValue = Math.round((worked / total) * 100);
856 increment = progressValue - currentProgress;
857 currentProgress = progressValue;
858 }
859 windowProgress.report({ message: details, increment });
860 };
861 const abortController = new AbortController();
862 token.onCancellationRequested(() => {
863 console.log(`Pulling ${modelName} model was cancelled`);
864 abortController.abort();
865 });
866 await modelInstaller.installModel(
867 modelName,
868 abortController.signal,
869 progressWrapper,
870 );
871 },
872 );
873}
874
875export function registerAllCommands(
876 context: vscode.ExtensionContext,
877 ide: VsCodeIde,
878 extensionContext: vscode.ExtensionContext,
879 sidebar: ContinueGUIWebviewViewProvider,
880 consoleView: ContinueConsoleWebviewViewProvider,
881 configHandler: ConfigHandler,
882 verticalDiffManager: VerticalDiffManager,
883 battery: Battery,
884 quickEdit: QuickEdit,
885 core: Core,
886 editDecorationManager: EditDecorationManager,
887) {
888 for (const [command, callback] of Object.entries(
889 getCommandsMap(
890 ide,
891 extensionContext,
892 sidebar,
893 consoleView,
894 configHandler,
895 verticalDiffManager,
896 battery,
897 quickEdit,
898 core,
899 editDecorationManager,
900 ),
901 )) {
902 context.subscriptions.push(
903 vscode.commands.registerCommand(command, callback),
904 );
905 }
906
907 try {
908 registerCopyBufferService(context, core);
909 } catch (e: any) {
910 //Non-critical error, it needs to be intercepted and not prevent the extension from starting
911 console.log("Error registering CopyBufferService: ", e);
912 Telemetry.capture(
913 "vscode_extension_copy_buffer_failure",
914 {
915 stack: extractMinimalStackTraceInfo(e.stack),
916 message: e.message,
917 },
918 false,
919 true,
920 );
921 }
922}