Elffuss BraidHub

kikocis/continue public

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