Elffuss BraidHub

kikocis/continue public

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