Elffuss BraidHub

kikocis/continue public

cf6f8dc05b27 · 28.9 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.writeCommentsForCode": async () => {
345 captureCommandTelemetry("writeCommentsForCode");
346
347 streamInlineEdit(
348 "comment",
349 "Write comments for this code. Do not change anything about the code itself.",
350 );
351 },
352 "continue.writeDocstringForCode": async () => {
353 captureCommandTelemetry("writeDocstringForCode");
354
355 void streamInlineEdit(
356 "docstring",
357 "Write a docstring for this code. Do not change anything about the code itself.",
358 );
359 },
360 "continue.fixCode": async () => {
361 captureCommandTelemetry("fixCode");
362
363 streamInlineEdit(
364 "fix",
365 "Fix this code. If it is already 100% correct, simply rewrite the code.",
366 );
367 },
368 "continue.optimizeCode": async () => {
369 captureCommandTelemetry("optimizeCode");
370 streamInlineEdit("optimize", "Optimize this code");
371 },
372 "continue.fixGrammar": async () => {
373 captureCommandTelemetry("fixGrammar");
374 streamInlineEdit(
375 "fixGrammar",
376 "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.",
377 );
378 },
379 "continue.clearConsole": async () => {
380 consoleView.clearLog();
381 },
382 "continue.viewLogs": async () => {
383 captureCommandTelemetry("viewLogs");
384 vscode.commands.executeCommand("workbench.action.toggleDevTools");
385 },
386 "continue.debugTerminal": async () => {
387 captureCommandTelemetry("debugTerminal");
388
389 const terminalContents = await ide.getTerminalContents();
390
391 vscode.commands.executeCommand("continue.continueGUIView.focus");
392
393 sidebar.webviewProtocol?.request("userInput", {
394 input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`,
395 });
396 },
397 "continue.hideInlineTip": () => {
398 vscode.workspace
399 .getConfiguration(EXTENSION_NAME)
400 .update("showInlineTip", false, vscode.ConfigurationTarget.Global);
401 },
402
403 // Commands without keyboard shortcuts
404 "continue.addModel": () => {
405 captureCommandTelemetry("addModel");
406
407 vscode.commands.executeCommand("continue.continueGUIView.focus");
408 sidebar.webviewProtocol?.request("addModel", undefined);
409 },
410 "continue.newSession": () => {
411 sidebar.webviewProtocol?.request("newSession", undefined);
412 },
413 "continue.viewHistory": () => {
414 vscode.commands.executeCommand("continue.navigateTo", "/history", true);
415 },
416 "continue.focusContinueSessionId": async (
417 sessionId: string | undefined,
418 ) => {
419 if (!sessionId) {
420 sessionId = await vscode.window.showInputBox({
421 prompt: "Enter the Session ID",
422 });
423 }
424 void sidebar.webviewProtocol?.request("focusContinueSessionId", {
425 sessionId,
426 });
427 },
428 "continue.applyCodeFromChat": () => {
429 void sidebar.webviewProtocol.request("applyCodeFromChat", undefined);
430 },
431 "continue.toggleFullScreen": async () => {
432 focusGUI();
433
434 const sessionId = await sidebar.webviewProtocol.request(
435 "getCurrentSessionId",
436 undefined,
437 );
438 // Check if full screen is already open by checking open tabs
439 const fullScreenTab = getFullScreenTab();
440
441 if (fullScreenTab && fullScreenPanel) {
442 // Full screen open, but not focused - focus it
443 fullScreenPanel.reveal();
444 return;
445 }
446
447 // Clear the sidebar to prevent overwriting changes made in fullscreen
448 vscode.commands.executeCommand("continue.newSession");
449
450 // Full screen not open - open it
451 captureCommandTelemetry("openFullScreen");
452
453 // Create the full screen panel
454 let panel = vscode.window.createWebviewPanel(
455 "continue.continueGUIView",
456 "Continue",
457 vscode.ViewColumn.One,
458 {
459 retainContextWhenHidden: true,
460 enableScripts: true,
461 },
462 );
463 fullScreenPanel = panel;
464
465 // Add content to the panel
466 panel.webview.html = sidebar.getSidebarContent(
467 extensionContext,
468 panel,
469 undefined,
470 undefined,
471 true,
472 );
473
474 const sessionLoader = panel.onDidChangeViewState(() => {
475 vscode.commands.executeCommand("continue.newSession");
476 if (sessionId) {
477 vscode.commands.executeCommand(
478 "continue.focusContinueSessionId",
479 sessionId,
480 );
481 }
482 panel.reveal();
483 sessionLoader.dispose();
484 });
485
486 // When panel closes, reset the webview and focus
487 panel.onDidDispose(
488 () => {
489 sidebar.resetWebviewProtocolWebview();
490 vscode.commands.executeCommand("continue.focusContinueInput");
491 },
492 null,
493 extensionContext.subscriptions,
494 );
495
496 vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow");
497 vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
498 },
499 "continue.openConfigPage": () => {
500 vscode.commands.executeCommand("continue.navigateTo", "/config", false);
501 },
502 "continue.selectFilesAsContext": async (
503 firstUri: vscode.Uri,
504 uris: vscode.Uri[],
505 ) => {
506 if (uris === undefined) {
507 throw new Error("No files were selected");
508 }
509
510 vscode.commands.executeCommand("continue.continueGUIView.focus");
511
512 for (const uri of uris) {
513 // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files)
514 const isDirectory = await vscode.workspace.fs
515 .stat(uri)
516 ?.then((stat) => stat.type === vscode.FileType.Directory);
517 if (isDirectory) {
518 for await (const fileUri of walkDirAsync(uri.toString(), ide, {
519 source: "vscode continue.selectFilesAsContext command",
520 })) {
521 await addEntireFileToContext(
522 vscode.Uri.parse(fileUri),
523 sidebar.webviewProtocol,
524 ide.ideUtils,
525 );
526 }
527 } else {
528 await addEntireFileToContext(
529 uri,
530 sidebar.webviewProtocol,
531 ide.ideUtils,
532 );
533 }
534 }
535 },
536 "continue.logAutocompleteOutcome": (
537 completionId: string,
538 completionProvider: CompletionProvider,
539 ) => {
540 completionProvider.accept(completionId);
541 },
542 "continue.toggleTabAutocompleteEnabled": () => {
543 captureCommandTelemetry("toggleTabAutocompleteEnabled");
544
545 const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
546 const enabled = config.get("enableTabAutocomplete");
547 const pauseOnBattery = config.get<boolean>(
548 "pauseTabAutocompleteOnBattery",
549 );
550 if (!pauseOnBattery || battery.isACConnected()) {
551 config.update(
552 "enableTabAutocomplete",
553 !enabled,
554 vscode.ConfigurationTarget.Global,
555 );
556 } else {
557 if (enabled) {
558 const paused = getStatusBarStatus() === StatusBarStatus.Paused;
559 if (paused) {
560 setupStatusBar(StatusBarStatus.Enabled);
561 } else {
562 config.update(
563 "enableTabAutocomplete",
564 false,
565 vscode.ConfigurationTarget.Global,
566 );
567 }
568 } else {
569 setupStatusBar(StatusBarStatus.Paused);
570 config.update(
571 "enableTabAutocomplete",
572 true,
573 vscode.ConfigurationTarget.Global,
574 );
575 }
576 }
577 },
578 "continue.forceAutocomplete": async () => {
579 captureCommandTelemetry("forceAutocomplete");
580
581 // 1. Explicitly hide any existing suggestion. This clears VS Code's cache for the current position.
582 await vscode.commands.executeCommand("editor.action.inlineSuggest.hide");
583
584 // 2. Now trigger a new one. VS Code has no cached suggestion, so it's forced to call our provider.
585 await vscode.commands.executeCommand(
586 "editor.action.inlineSuggest.trigger",
587 );
588 },
589
590 "continue.openTabAutocompleteConfigMenu": async () => {
591 captureCommandTelemetry("openTabAutocompleteConfigMenu");
592
593 const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
594 const quickPick = vscode.window.createQuickPick();
595
596 const { config: continueConfig } = await configHandler.loadConfig();
597 const autocompleteModels =
598 continueConfig?.modelsByRole.autocomplete ?? [];
599 const selected =
600 continueConfig?.selectedModelByRole?.autocomplete?.title ?? undefined;
601
602 // Toggle between Disabled, Paused, and Enabled
603 const pauseOnBattery =
604 config.get<boolean>("pauseTabAutocompleteOnBattery") &&
605 !battery.isACConnected();
606 const currentStatus = getStatusBarStatus();
607
608 let targetStatus: StatusBarStatus | undefined;
609 if (pauseOnBattery) {
610 // Cycle from Disabled -> Paused -> Enabled
611 targetStatus =
612 currentStatus === StatusBarStatus.Paused
613 ? StatusBarStatus.Enabled
614 : currentStatus === StatusBarStatus.Disabled
615 ? StatusBarStatus.Paused
616 : StatusBarStatus.Disabled;
617 } else {
618 // Toggle between Disabled and Enabled
619 targetStatus =
620 currentStatus === StatusBarStatus.Disabled
621 ? StatusBarStatus.Enabled
622 : StatusBarStatus.Disabled;
623 }
624
625 quickPick.items = [
626 {
627 label: "$(gear) Open settings",
628 },
629 {
630 label: "$(comment) Open chat",
631 description: getMetaKeyLabel() + " + L",
632 },
633 {
634 label: "$(screen-full) Open full screen chat",
635 description:
636 getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + M",
637 },
638 {
639 label: quickPickStatusText(targetStatus),
640 description:
641 getMetaKeyLabel() + " + K, " + getMetaKeyLabel() + " + A",
642 },
643 {
644 kind: vscode.QuickPickItemKind.Separator,
645 label: "Switch model",
646 },
647 ...autocompleteModels.map((model) => ({
648 label: getAutocompleteStatusBarTitle(selected, model),
649 description: getAutocompleteStatusBarDescription(selected, model),
650 })),
651 ];
652 quickPick.onDidAccept(() => {
653 const selectedOption = quickPick.selectedItems[0].label;
654 const targetStatus =
655 getStatusBarStatusFromQuickPickItemLabel(selectedOption);
656
657 if (targetStatus !== undefined) {
658 setupStatusBar(targetStatus);
659 config.update(
660 "enableTabAutocomplete",
661 targetStatus === StatusBarStatus.Enabled,
662 vscode.ConfigurationTarget.Global,
663 );
664 } else if (
665 autocompleteModels.some((model) => model.title === selectedOption)
666 ) {
667 if (core.configHandler.currentProfile?.profileDescription.id) {
668 core.invoke("config/updateSelectedModel", {
669 profileId:
670 core.configHandler.currentProfile?.profileDescription.id,
671 role: "autocomplete",
672 title: selectedOption,
673 });
674 }
675 } else if (selectedOption === "$(comment) Open chat") {
676 vscode.commands.executeCommand("continue.focusContinueInput");
677 } else if (selectedOption === "$(screen-full) Open full screen chat") {
678 vscode.commands.executeCommand("continue.toggleFullScreen");
679 } else if (selectedOption === "$(gear) Open settings") {
680 vscode.commands.executeCommand("continue.navigateTo", "/config");
681 }
682
683 quickPick.dispose();
684 });
685 quickPick.show();
686 },
687 "continue.navigateTo": (path: string, toggle: boolean) => {
688 sidebar.webviewProtocol?.request("navigateTo", { path, toggle });
689 focusGUI();
690 },
691 "continue.startLocalOllama": () => {
692 startLocalOllama(ide);
693 },
694 "continue.installModel": async (
695 modelName: string,
696 llmProvider: ILLM | undefined,
697 ) => {
698 try {
699 if (!isModelInstaller(llmProvider)) {
700 const msg = llmProvider
701 ? `LLM provider '${llmProvider.providerName}' does not support installing models`
702 : "Missing LLM Provider";
703 throw new Error(msg);
704 }
705 await installModelWithProgress(modelName, llmProvider);
706 } catch (e) {
707 const message = e instanceof Error ? e.message : String(e);
708 vscode.window.showErrorMessage(
709 `Failed to install '${modelName}': ${message}`,
710 );
711 }
712 },
713 "continue.convertConfigJsonToConfigYaml": async () => {
714 const configJson = fs.readFileSync(getConfigJsonPath(), "utf-8");
715 const parsed = JSON.parse(configJson);
716 const configYaml = convertJsonToYamlConfig(parsed);
717
718 const configYamlPath = getConfigYamlPath();
719 fs.writeFileSync(configYamlPath, YAML.stringify(configYaml));
720
721 // Open config.yaml
722 await openEditorAndRevealRange(
723 vscode.Uri.file(configYamlPath),
724 undefined,
725 undefined,
726 false,
727 );
728
729 void vscode.window
730 .showInformationMessage(
731 "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.",
732 "Read the docs",
733 )
734 .then(async (selection) => {
735 if (selection === "Read the docs") {
736 await vscode.env.openExternal(
737 vscode.Uri.parse("https://docs.continue.dev/yaml-migration"),
738 );
739 }
740 });
741 },
742 "continue.enterEnterpriseLicenseKey": async () => {
743 captureCommandTelemetry("enterEnterpriseLicenseKey");
744
745 const licenseKey = await vscode.window.showInputBox({
746 prompt: "Enter your enterprise license key",
747 password: true,
748 ignoreFocusOut: true,
749 placeHolder: "License key",
750 });
751
752 if (!licenseKey) {
753 return;
754 }
755
756 try {
757 const isValid = core.invoke("mdm/setLicenseKey", {
758 licenseKey,
759 });
760
761 if (isValid) {
762 void vscode.window.showInformationMessage(
763 "Enterprise license key successfully validated and saved. Reloading window.",
764 );
765 await new Promise((resolve) => setTimeout(resolve, 1000));
766 await vscode.commands.executeCommand("workbench.action.reloadWindow");
767 } else {
768 void vscode.window.showErrorMessage(
769 "Invalid license key. Please check your license key and try again.",
770 );
771 }
772 } catch (error) {
773 void vscode.window.showErrorMessage(
774 `Failed to set enterprise license key: ${error instanceof Error ? error.message : String(error)}`,
775 );
776 }
777 },
778 "continue.forceNextEdit": async () => {
779 captureCommandTelemetry("forceNextEdit");
780
781 // This is basically the same logic as forceAutocomplete.
782 // I'm writing a new command KV pair here in case we diverge in features.
783
784 await vscode.commands.executeCommand("editor.action.inlineSuggest.hide");
785
786 await vscode.commands.executeCommand(
787 "editor.action.inlineSuggest.trigger",
788 );
789 },
790 };
791};
792
793const registerCopyBufferService = (
794 context: vscode.ExtensionContext,
795 core: Core,
796) => {
797 const typeDisposable = vscode.commands.registerCommand(
798 "editor.action.clipboardCopyAction",
799 async (arg) => doCopy(typeDisposable),
800 );
801
802 async function doCopy(typeDisposable: any) {
803 typeDisposable.dispose(); // must dispose to avoid endless loops
804
805 await vscode.commands.executeCommand("editor.action.clipboardCopyAction");
806
807 const clipboardText = await vscode.env.clipboard.readText();
808
809 if (clipboardText) {
810 core.invoke("clipboardCache/add", {
811 content: clipboardText,
812 });
813 }
814
815 await context.workspaceState.update("continue.copyBuffer", {
816 text: clipboardText,
817 copiedAt: new Date().toISOString(),
818 });
819
820 // re-register to continue intercepting copy commands
821 typeDisposable = vscode.commands.registerCommand(
822 "editor.action.clipboardCopyAction",
823 async () => doCopy(typeDisposable),
824 );
825 context.subscriptions.push(typeDisposable);
826 }
827
828 context.subscriptions.push(typeDisposable);
829};
830
831async function installModelWithProgress(
832 modelName: string,
833 modelInstaller: ModelInstaller,
834) {
835 return vscode.window.withProgress(
836 {
837 location: vscode.ProgressLocation.Notification,
838 title: `Installing model '${modelName}'`,
839 cancellable: true,
840 },
841 async (windowProgress, token) => {
842 let currentProgress: number = 0;
843 const progressWrapper = (
844 details: string,
845 worked?: number,
846 total?: number,
847 ) => {
848 let increment = 0;
849 if (worked && total) {
850 const progressValue = Math.round((worked / total) * 100);
851 increment = progressValue - currentProgress;
852 currentProgress = progressValue;
853 }
854 windowProgress.report({ message: details, increment });
855 };
856 const abortController = new AbortController();
857 token.onCancellationRequested(() => {
858 console.log(`Pulling ${modelName} model was cancelled`);
859 abortController.abort();
860 });
861 await modelInstaller.installModel(
862 modelName,
863 abortController.signal,
864 progressWrapper,
865 );
866 },
867 );
868}
869
870export function registerAllCommands(
871 context: vscode.ExtensionContext,
872 ide: VsCodeIde,
873 extensionContext: vscode.ExtensionContext,
874 sidebar: ContinueGUIWebviewViewProvider,
875 consoleView: ContinueConsoleWebviewViewProvider,
876 configHandler: ConfigHandler,
877 verticalDiffManager: VerticalDiffManager,
878 battery: Battery,
879 quickEdit: QuickEdit,
880 core: Core,
881 editDecorationManager: EditDecorationManager,
882) {
883 for (const [command, callback] of Object.entries(
884 getCommandsMap(
885 ide,
886 extensionContext,
887 sidebar,
888 consoleView,
889 configHandler,
890 verticalDiffManager,
891 battery,
892 quickEdit,
893 core,
894 editDecorationManager,
895 ),
896 )) {
897 context.subscriptions.push(
898 vscode.commands.registerCommand(command, callback),
899 );
900 }
901
902 try {
903 registerCopyBufferService(context, core);
904 } catch (e: any) {
905 //Non-critical error, it needs to be intercepted and not prevent the extension from starting
906 console.log("Error registering CopyBufferService: ", e);
907 Telemetry.capture(
908 "vscode_extension_copy_buffer_failure",
909 {
910 stack: extractMinimalStackTraceInfo(e.stack),
911 message: e.message,
912 },
913 false,
914 true,
915 );
916 }
917}