Elffuss BraidHub

kikocis/continue public

feat: expose legacy /share command to VS Code UI

The legacy `/share` slash command is no longer available when using config.yaml.
While the feature could be replaced by a custom prompt command + a tools-supporting model,
it's fairly slow/buggy when relying on local models.

Instead, we're exposing the feature to the VS Code UI
- as a button on each conversation in the history view
- as a VS Code command `Share Current Chat Session as Markdown`

Unfortunately, because the IDE requires special handling for the destination folder selection,
the gui code needs to check if it's running on jetbrains in order to disable this new feature

Signed-off-by: Fred Bricon <fbricon@gmail.com>
Changeset00c2dcd72a7c41e46141541d717530b109b30b50e95d542cc93882c84042a3ea
AuthorFred Bricon <fbricon@gmail.com> · 2025-07-22 15:58 +02:00
CommitterFred Bricon <fbricon@gmail.com> · 2025-08-18 16:12 +02:00
Parentsb334cb9dcd5e

Browse the files at this changeset

10 files changed

modified core/commands/slash/built-in-legacy/share.ts +6 −88
@@ -1,99 +1,17 @@
1-import fs from "fs";
2-import { homedir } from "node:os";
3-import { fileURLToPath, pathToFileURL } from "node:url";
1+import { fileURLToPath } from "node:url";
42 import path from "path";
53
6-import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js";
74 import { SlashCommand } from "../../../index.js";
8-import { renderChatMessage } from "../../../util/messageContent.js";
9-import { getContinueGlobalPath } from "../../../util/paths.js";
10-
11-// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
12-function getOffsetDatetime(date: Date): Date {
13- const offset = date.getTimezoneOffset();
14- const offsetHours = Math.floor(offset / 60);
15- const offsetMinutes = offset % 60;
16- date.setHours(date.getHours() - offsetHours);
17- date.setMinutes(date.getMinutes() - offsetMinutes);
18-
19- return date;
20-}
21-
22-function asBasicISOString(date: Date): string {
23- const isoString = date.toISOString();
24-
25- return isoString.replace(/[-:]|(\.\d+Z)/g, "");
26-}
27-
28-function reformatCodeBlocks(msgText: string): string {
29- const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
30- msgText = msgText.replace(
31- codeBlockFenceRegex,
32- (match, metadata, filename, extension) => {
33- const lang = languageForFilepath(filename);
34- return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
35- },
36- );
37- // Appease the markdown linter
38- return msgText.replace(/```\n```/g, "```\n\n```");
39-}
5+import { shareSession } from "../../../util/historyUtils.js";
406
417 const ShareSlashCommand: SlashCommand = {
428 name: "share",
439 description: "Export the current chat session to markdown",
4410 run: async function* ({ ide, history, params }) {
45- const now = new Date();
46-
47- let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`;
48-
49- // As currently implemented, the /share command is by definition the last
50- // message in the chat history, this will omit it
51- for (const msg of history.slice(0, history.length - 1)) {
52- let msgText = msg.content;
53- msgText = renderChatMessage(msg);
54-
55- if (msg.role === "user" && msgText.search("```") > -1) {
56- msgText = reformatCodeBlocks(msgText);
57- }
58-
59- // format messages as blockquotes
60- msgText = msgText.replace(/^/gm, "> ");
61-
62- content += `\n\n#### ${
63- msg.role === "user" ? "_User_" : "_Assistant_"
64- }\n\n${msgText}`;
65- }
66-
67- let outputDir: string = params?.outputDir ?? getContinueGlobalPath();
68-
69- if (outputDir.startsWith("~")) {
70- outputDir = outputDir.replace(/^~/, homedir);
71- } else if (
72- outputDir.startsWith("./") ||
73- outputDir.startsWith(".\\") ||
74- outputDir === "."
75- ) {
76- const workspaceDirs = await ide.getWorkspaceDirs();
77- // Although the most common situation is to have one directory open in a
78- // workspace it's also possible to have just a file open without an
79- // associated directory or to use multi-root workspaces in which multiple
80- // folders are included. We default to using the first item in the list, if
81- // it exists.
82- const workspaceDirectory = workspaceDirs?.[0] || "";
83- outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
84- }
85-
86- if (!fs.existsSync(outputDir)) {
87- fs.mkdirSync(outputDir, { recursive: true });
88- }
89-
90- const dtString = asBasicISOString(getOffsetDatetime(now));
91- const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
92-
93- const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
94- await ide.writeFile(fileUrl, content);
95- await ide.openFile(fileUrl);
96-
11+ const fileUrl = await shareSession(ide, history, params?.outputDir);
12+ const filePath = fileURLToPath(fileUrl);
13+ // output path is the parent directory of the filePath
14+ const outPath = path.dirname(filePath);
9715 yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`;
9816 },
9917 };
modified core/core.ts +8 −0
@@ -76,6 +76,7 @@
7676 import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
7777 import { OnboardingModes } from "./protocol/core";
7878 import type { IMessenger, Message } from "./protocol/messenger";
79+import { shareSession } from "./util/historyUtils";
7980 import { Logger } from "./util/Logger.js";
8081 import { getUriPathBasename } from "./util/uri";
8182
@@ -323,6 +324,13 @@
323324 historyManager.save(msg.data);
324325 });
325326
327+ on("history/share", async (msg) => {
328+ const session = historyManager.load(msg.data.id);
329+ const outputDir = msg.data.outputDir;
330+ const history = session.history.map((msg) => msg.message);
331+ await shareSession(this.ide, history, outputDir);
332+ });
333+
326334 on("history/clear", (msg) => {
327335 historyManager.clearAll();
328336 });
modified core/protocol/core.ts +1 −0
@@ -74,6 +74,7 @@
7474 "history/delete": [{ id: string }, void];
7575 "history/load": [{ id: string }, Session];
7676 "history/save": [Session, void];
77+ "history/share": [{ id: string; outputDir?: string }, void];
7778 "history/clear": [undefined, void];
7879 "devdata/log": [DevDataLogEvent, void];
7980 "config/addOpenAiKey": [string, void];
modified core/protocol/ideWebview.ts +1 −0
@@ -48,6 +48,7 @@
4848 ];
4949 "edit/addCurrentSelection": [undefined, void];
5050 "edit/clearDecorations": [undefined, void];
51+ "session/share": [{ sessionId: string }, void];
5152 };
5253
5354 export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
added core/util/historyUtils.ts +105 −0
@@ -0,0 +1,105 @@
1+import fs from "fs";
2+import { homedir } from "node:os";
3+import { fileURLToPath, pathToFileURL } from "node:url";
4+import path from "path";
5+
6+import { languageForFilepath } from "../autocomplete/constants/AutocompleteLanguageInfo.js";
7+import { ChatMessage, IDE } from "../index.js";
8+import { renderChatMessage } from "../util/messageContent.js";
9+import { getContinueGlobalPath } from "../util/paths.js";
10+
11+// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
12+function getOffsetDatetime(date: Date): Date {
13+ const offset = date.getTimezoneOffset();
14+ const offsetHours = Math.floor(offset / 60);
15+ const offsetMinutes = offset % 60;
16+ date.setHours(date.getHours() - offsetHours);
17+ date.setMinutes(date.getMinutes() - offsetMinutes);
18+
19+ return date;
20+}
21+
22+function asBasicISOString(date: Date): string {
23+ const isoString = date.toISOString();
24+
25+ return isoString.replace(/[-:]|(\.\d+Z)/g, "");
26+}
27+
28+function reformatCodeBlocks(msgText: string): string {
29+ const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
30+ msgText = msgText.replace(
31+ codeBlockFenceRegex,
32+ (match, metadata, filename, extension) => {
33+ const lang = languageForFilepath(filename);
34+ return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
35+ },
36+ );
37+ // Appease the markdown linter
38+ return msgText.replace(/```\n```/g, "```\n\n```");
39+}
40+
41+export function toMarkDown(history: ChatMessage[], time?: Date): string {
42+ if (!time) {
43+ time = new Date();
44+ }
45+ let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${time.toLocaleString()}`;
46+
47+ for (const msg of history) {
48+ let msgText = renderChatMessage(msg);
49+ if (!msgText) {
50+ continue; // Skip messages without content
51+ }
52+
53+ if (msg.role === "user" && msgText.search("```") > -1) {
54+ msgText = reformatCodeBlocks(msgText);
55+ }
56+
57+ // format messages as blockquotes
58+ msgText = msgText.replace(/^/gm, "> ");
59+
60+ content += `\n\n#### ${
61+ msg.role === "user" ? "_User_" : "_Assistant_"
62+ }\n\n${msgText}`;
63+ }
64+ return content;
65+}
66+
67+export async function shareSession(
68+ ide: IDE,
69+ history: ChatMessage[],
70+ outputDir?: string,
71+) {
72+ const now = new Date();
73+ const content = toMarkDown(history, now);
74+
75+ outputDir = outputDir ?? getContinueGlobalPath();
76+
77+ if (outputDir.startsWith("~")) {
78+ outputDir = outputDir.replace(/^~/, homedir);
79+ } else if (
80+ outputDir.startsWith("./") ||
81+ outputDir.startsWith(".\\") ||
82+ outputDir === "."
83+ ) {
84+ const workspaceDirs = await ide.getWorkspaceDirs();
85+ // Although the most common situation is to have one directory open in a
86+ // workspace it's also possible to have just a file open without an
87+ // associated directory or to use multi-root workspaces in which multiple
88+ // folders are included. We default to using the first item in the list, if
89+ // it exists.
90+ const workspaceDirectory = workspaceDirs?.[0] || "";
91+ outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
92+ }
93+
94+ if (!fs.existsSync(outputDir)) {
95+ fs.mkdirSync(outputDir, { recursive: true });
96+ }
97+
98+ const dtString = asBasicISOString(getOffsetDatetime(now));
99+ const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
100+
101+ const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
102+ await ide.writeFile(fileUrl, content);
103+ await ide.openFile(fileUrl);
104+ return fileUrl;
105+}
modified extensions/vscode/package.json +6 −0
@@ -243,6 +243,12 @@
243243 "icon": "$(add)",
244244 "group": "Continue"
245245 },
246+ {
247+ "command": "continue.shareSession",
248+ "category": "Continue",
249+ "title": "Share Current Chat Session as Markdown",
250+ "group": "Continue"
251+ },
246252 {
247253 "command": "continue.viewHistory",
248254 "category": "Continue",
modified extensions/vscode/src/commands.ts +37 −0
@@ -415,6 +415,43 @@
415415 "continue.newSession": () => {
416416 sidebar.webviewProtocol?.request("newSession", undefined);
417417 },
418+
419+ "continue.shareSession": async (sessionId: string | undefined) => {
420+ if (!sessionId) {
421+ sessionId = await sidebar.webviewProtocol?.request(
422+ "getCurrentSessionId",
423+ undefined,
424+ );
425+ }
426+ if (!sessionId) {
427+ void vscode.window.showErrorMessage(
428+ "No session ID found. Please start a new session first.",
429+ );
430+ return;
431+ }
432+ //let user select the destination folder
433+ const destinationFolder = await vscode.window.showOpenDialog({
434+ canSelectFolders: true,
435+ canSelectFiles: false,
436+ canSelectMany: false,
437+ openLabel: "Select Destination Folder",
438+ });
439+ if (!destinationFolder || destinationFolder.length === 0) {
440+ return;
441+ }
442+
443+ try {
444+ // despite core.invoke not being async, we still need to await it, because the 'history/share' command is async
445+ // if not awaited, then errors will not be caught.
446+ await core.invoke("history/share", {
447+ id: sessionId,
448+ outputDir: destinationFolder[0].fsPath,
449+ });
450+ } catch (error) {
451+ const errorMessage = `Failed to save session: ${error instanceof Error ? error.message : String(error)}`;
452+ void vscode.window.showErrorMessage(errorMessage);
453+ }
454+ },
418455 "continue.viewHistory": () => {
419456 vscode.commands.executeCommand("continue.navigateTo", "/history", true);
420457 },
modified extensions/vscode/src/extension/VsCodeMessenger.ts +8 −0
@@ -106,6 +106,7 @@
106106 this.onWebview("toggleDevTools", (msg) => {
107107 vscode.commands.executeCommand("continue.viewLogs");
108108 });
109+
109110 this.onWebview("reloadWindow", (msg) => {
110111 vscode.commands.executeCommand("workbench.action.reloadWindow");
111112 });
@@ -254,6 +255,13 @@
254255 editDecorationManager.clear();
255256 });
256257
258+ this.onWebview("session/share", async (msg) => {
259+ await vscode.commands.executeCommand(
260+ "continue.shareSession",
261+ msg.data.sessionId,
262+ );
263+ });
264+
257265 /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
258266 WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
259267 this.onWebview(messageType, async (msg) => {
modified gui/src/components/History/HistoryTableRow.tsx +28 −1
@@ -1,4 +1,8 @@
1-import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline";
1+import {
2+ ArrowDownOnSquareIcon,
3+ PencilSquareIcon,
4+ TrashIcon,
5+} from "@heroicons/react/24/outline";
26 import { SessionMetadata } from "core";
37 import { getUriPathBasename } from "core/util/uri";
48 import React, { useContext, useEffect, useState } from "react";
@@ -13,8 +17,11 @@
1317 loadSession,
1418 updateSession,
1519 } from "../../redux/thunks/session";
20+import { isShareSessionSupported } from "../../util";
1621 import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
1722
23+const shareSessionSupported = isShareSessionSupported();
24+
1825 export function HistoryTableRow({
1926 sessionMetadata,
2027 index,
@@ -37,6 +44,15 @@
3744 setSessionTitleEditValue(sessionMetadata.title);
3845 }, [sessionMetadata]);
3946
47+ const shareSession = async (sessionId: string) => {
48+ // "session/share" is not supported in JetBrains yet
49+ if (shareSessionSupported) {
50+ await ideMessenger.request("session/share", {
51+ sessionId,
52+ });
53+ }
54+ };
55+
4056 const handleKeyUp = async (e: React.KeyboardEvent<HTMLInputElement>) => {
4157 if (e.key === "Enter") {
4258 if (sessionTitleEditValue !== sessionMetadata.title) {
@@ -127,6 +143,17 @@
127143 >
128144 <PencilSquareIcon width="1em" height="1em" />
129145 </HeaderButtonWithToolTip>
146+ {shareSessionSupported && (
147+ <HeaderButtonWithToolTip
148+ text="Save Chat as Markdown"
149+ onClick={async (e) => {
150+ e.stopPropagation();
151+ await shareSession(sessionMetadata.sessionId);
152+ }}
153+ >
154+ <ArrowDownOnSquareIcon width="1em" height="1em" />
155+ </HeaderButtonWithToolTip>
156+ )}
130157 <HeaderButtonWithToolTip
131158 text="Delete"
132159 onClick={async (e) => {
modified gui/src/util/index.ts +2 −0
@@ -59,6 +59,8 @@
5959 return getLocalStorage("ide") === "jetbrains";
6060 }
6161
62+export const isShareSessionSupported = () => !isJetBrains();
63+
6264 export function isWebEnvironment(): boolean {
6365 return (
6466 typeof window !== "undefined" &&