Elffuss BraidHub

kikocis/continue public

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