Elffuss BraidHub

kikocis/continue public

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