Elffuss BraidHub

kikocis/continue public

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