Elffuss BraidHub

kikocis/continue public

Merge pull request #6802 from fbricon/save-chat

feat: expose legacy /share command to VS Code UI
Changesetba33beacce3922e4cef407875cb00170754bb31506d6032b93dd09132052ee6f
AuthorDallin Romney <dallinromney@gmail.com> · 2025-09-22 14:55 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-22 14:55 -07:00
Parentsc9a6efde71c8, 2b8d1c29d506

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
@@ -78,6 +78,7 @@
7878 import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
7979 import { OnboardingModes } from "./protocol/core";
8080 import type { IMessenger, Message } from "./protocol/messenger";
81+import { shareSession } from "./util/historyUtils";
8182 import { Logger } from "./util/Logger.js";
8283 import { getUriPathBasename } from "./util/uri";
8384
@@ -366,6 +367,13 @@
366367 historyManager.save(msg.data);
367368 });
368369
370+ on("history/share", async (msg) => {
371+ const session = historyManager.load(msg.data.id);
372+ const outputDir = msg.data.outputDir;
373+ const history = session.history.map((msg) => msg.message);
374+ await shareSession(this.ide, history, outputDir);
375+ });
376+
369377 on("history/clear", (msg) => {
370378 historyManager.clearAll();
371379 });
modified core/protocol/core.ts +1 −0
@@ -82,6 +82,7 @@
8282 "history/load": [{ id: string }, Session];
8383 "history/loadRemote": [{ remoteId: string }, Session];
8484 "history/save": [Session, void];
85+ "history/share": [{ id: string; outputDir?: string }, void];
8586 "history/clear": [undefined, void];
8687 "devdata/log": [DevDataLogEvent, void];
8788 "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
@@ -241,6 +241,12 @@
241241 "icon": "$(add)",
242242 "group": "Continue"
243243 },
244+ {
245+ "command": "continue.shareSession",
246+ "category": "Continue",
247+ "title": "Share Current Chat Session as Markdown",
248+ "group": "Continue"
249+ },
244250 {
245251 "command": "continue.viewHistory",
246252 "category": "Continue",
modified extensions/vscode/src/commands.ts +37 −0
@@ -399,6 +399,43 @@
399399 "continue.newSession": () => {
400400 sidebar.webviewProtocol?.request("newSession", undefined);
401401 },
402+
403+ "continue.shareSession": async (sessionId: string | undefined) => {
404+ if (!sessionId) {
405+ sessionId = await sidebar.webviewProtocol?.request(
406+ "getCurrentSessionId",
407+ undefined,
408+ );
409+ }
410+ if (!sessionId) {
411+ void vscode.window.showErrorMessage(
412+ "No session ID found. Please start a new session first.",
413+ );
414+ return;
415+ }
416+ //let user select the destination folder
417+ const destinationFolder = await vscode.window.showOpenDialog({
418+ canSelectFolders: true,
419+ canSelectFiles: false,
420+ canSelectMany: false,
421+ openLabel: "Select Destination Folder",
422+ });
423+ if (!destinationFolder || destinationFolder.length === 0) {
424+ return;
425+ }
426+
427+ try {
428+ // despite core.invoke not being async, we still need to await it, because the 'history/share' command is async
429+ // if not awaited, then errors will not be caught.
430+ await core.invoke("history/share", {
431+ id: sessionId,
432+ outputDir: destinationFolder[0].fsPath,
433+ });
434+ } catch (error) {
435+ const errorMessage = `Failed to save session: ${error instanceof Error ? error.message : String(error)}`;
436+ void vscode.window.showErrorMessage(errorMessage);
437+ }
438+ },
402439 "continue.viewHistory": () => {
403440 vscode.commands.executeCommand("continue.navigateTo", "/history", true);
404441 },
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 });
@@ -252,6 +253,13 @@
252253 editDecorationManager.clear();
253254 });
254255
256+ this.onWebview("session/share", async (msg) => {
257+ await vscode.commands.executeCommand(
258+ "continue.shareSession",
259+ msg.data.sessionId,
260+ );
261+ });
262+
255263 /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
256264 WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
257265 this.onWebview(messageType, async (msg) => {
modified gui/src/components/History/HistoryTableRow.tsx +24 −1
@@ -1,7 +1,8 @@
11 import {
2- CloudIcon,
2+ ArrowDownOnSquareIcon,
33 PencilSquareIcon,
44 TrashIcon,
5+ CloudIcon,
56 } from "@heroicons/react/24/outline";
67 import { BaseSessionMetadata } from "core";
78 import type { RemoteSessionMetadata } from "core/control-plane/client";
@@ -19,8 +20,11 @@
1920 loadSession,
2021 updateSession,
2122 } from "../../redux/thunks/session";
23+import { isShareSessionSupported } from "../../util";
2224 import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
2325
26+const shareSessionSupported = isShareSessionSupported();
27+
2428 export function HistoryTableRow({
2529 sessionMetadata,
2630 index,
@@ -43,6 +47,14 @@
4347 setSessionTitleEditValue(sessionMetadata.title);
4448 }, [sessionMetadata]);
4549
50+ const shareSession = async (sessionId: string) => {
51+ // "session/share" is not supported in JetBrains yet
52+ if (shareSessionSupported) {
53+ await ideMessenger.request("session/share", {
54+ sessionId,
55+ });
56+ }
57+ };
4658 const isRemote = "isRemote" in sessionMetadata && sessionMetadata.isRemote;
4759
4860 const handleKeyUp = async (e: React.KeyboardEvent<HTMLInputElement>) => {
@@ -178,6 +190,17 @@
178190 >
179191 <PencilSquareIcon width="1em" height="1em" />
180192 </HeaderButtonWithToolTip>
193+ {shareSessionSupported && (
194+ <HeaderButtonWithToolTip
195+ text="Save Chat as Markdown"
196+ onClick={async (e) => {
197+ e.stopPropagation();
198+ await shareSession(sessionMetadata.sessionId);
199+ }}
200+ >
201+ <ArrowDownOnSquareIcon width="1em" height="1em" />
202+ </HeaderButtonWithToolTip>
203+ )}
181204 <HeaderButtonWithToolTip
182205 text="Delete"
183206 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" &&