diff --git a/core/commands/slash/built-in-legacy/share.ts b/core/commands/slash/built-in-legacy/share.ts index daddf8dff..041269ca8 100644 --- a/core/commands/slash/built-in-legacy/share.ts +++ b/core/commands/slash/built-in-legacy/share.ts @@ -1,99 +1,17 @@ -import fs from "fs"; -import { homedir } from "node:os"; -import { fileURLToPath, pathToFileURL } from "node:url"; +import { fileURLToPath } from "node:url"; import path from "path"; -import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js"; import { SlashCommand } from "../../../index.js"; -import { renderChatMessage } from "../../../util/messageContent.js"; -import { getContinueGlobalPath } from "../../../util/paths.js"; - -// If useful elsewhere, helper funcs should move to core/util/index.ts or similar -function getOffsetDatetime(date: Date): Date { - const offset = date.getTimezoneOffset(); - const offsetHours = Math.floor(offset / 60); - const offsetMinutes = offset % 60; - date.setHours(date.getHours() - offsetHours); - date.setMinutes(date.getMinutes() - offsetMinutes); - - return date; -} - -function asBasicISOString(date: Date): string { - const isoString = date.toISOString(); - - return isoString.replace(/[-:]|(\.\d+Z)/g, ""); -} - -function reformatCodeBlocks(msgText: string): string { - const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g; - msgText = msgText.replace( - codeBlockFenceRegex, - (match, metadata, filename, extension) => { - const lang = languageForFilepath(filename); - return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; - }, - ); - // Appease the markdown linter - return msgText.replace(/```\n```/g, "```\n\n```"); -} +import { shareSession } from "../../../util/historyUtils.js"; const ShareSlashCommand: SlashCommand = { name: "share", description: "Export the current chat session to markdown", run: async function* ({ ide, history, params }) { - const now = new Date(); - - let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`; - - // As currently implemented, the /share command is by definition the last - // message in the chat history, this will omit it - for (const msg of history.slice(0, history.length - 1)) { - let msgText = msg.content; - msgText = renderChatMessage(msg); - - if (msg.role === "user" && msgText.search("```") > -1) { - msgText = reformatCodeBlocks(msgText); - } - - // format messages as blockquotes - msgText = msgText.replace(/^/gm, "> "); - - content += `\n\n#### ${ - msg.role === "user" ? "_User_" : "_Assistant_" - }\n\n${msgText}`; - } - - let outputDir: string = params?.outputDir ?? getContinueGlobalPath(); - - if (outputDir.startsWith("~")) { - outputDir = outputDir.replace(/^~/, homedir); - } else if ( - outputDir.startsWith("./") || - outputDir.startsWith(".\\") || - outputDir === "." - ) { - const workspaceDirs = await ide.getWorkspaceDirs(); - // Although the most common situation is to have one directory open in a - // workspace it's also possible to have just a file open without an - // associated directory or to use multi-root workspaces in which multiple - // folders are included. We default to using the first item in the list, if - // it exists. - const workspaceDirectory = workspaceDirs?.[0] || ""; - outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory)); - } - - if (!fs.existsSync(outputDir)) { - fs.mkdirSync(outputDir, { recursive: true }); - } - - const dtString = asBasicISOString(getOffsetDatetime(now)); - const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming? - - const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^ - await ide.writeFile(fileUrl, content); - await ide.openFile(fileUrl); - + const fileUrl = await shareSession(ide, history, params?.outputDir); + const filePath = fileURLToPath(fileUrl); + // output path is the parent directory of the filePath + const outPath = path.dirname(filePath); yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`; }, }; diff --git a/core/core.ts b/core/core.ts index 1e5b2a74b..bb07e5cb9 100644 --- a/core/core.ts +++ b/core/core.ts @@ -76,6 +76,7 @@ import { NextEditProvider } from "./nextEdit/NextEditProvider"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; +import { shareSession } from "./util/historyUtils"; import { Logger } from "./util/Logger.js"; import { getUriPathBasename } from "./util/uri"; @@ -323,6 +324,13 @@ export class Core { historyManager.save(msg.data); }); + on("history/share", async (msg) => { + const session = historyManager.load(msg.data.id); + const outputDir = msg.data.outputDir; + const history = session.history.map((msg) => msg.message); + await shareSession(this.ide, history, outputDir); + }); + on("history/clear", (msg) => { historyManager.clearAll(); }); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 895b8313a..1cc26f0ca 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -74,6 +74,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "history/delete": [{ id: string }, void]; "history/load": [{ id: string }, Session]; "history/save": [Session, void]; + "history/share": [{ id: string; outputDir?: string }, void]; "history/clear": [undefined, void]; "devdata/log": [DevDataLogEvent, void]; "config/addOpenAiKey": [string, void]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 232953f88..21eab1f7f 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -48,6 +48,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { ]; "edit/addCurrentSelection": [undefined, void]; "edit/clearDecorations": [undefined, void]; + "session/share": [{ sessionId: string }, void]; }; export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { diff --git a/core/util/historyUtils.ts b/core/util/historyUtils.ts new file mode 100644 index 000000000..fc0939c7b --- /dev/null +++ b/core/util/historyUtils.ts @@ -0,0 +1,105 @@ +import fs from "fs"; +import { homedir } from "node:os"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import path from "path"; + +import { languageForFilepath } from "../autocomplete/constants/AutocompleteLanguageInfo.js"; +import { ChatMessage, IDE } from "../index.js"; +import { renderChatMessage } from "../util/messageContent.js"; +import { getContinueGlobalPath } from "../util/paths.js"; + +// If useful elsewhere, helper funcs should move to core/util/index.ts or similar +function getOffsetDatetime(date: Date): Date { + const offset = date.getTimezoneOffset(); + const offsetHours = Math.floor(offset / 60); + const offsetMinutes = offset % 60; + date.setHours(date.getHours() - offsetHours); + date.setMinutes(date.getMinutes() - offsetMinutes); + + return date; +} + +function asBasicISOString(date: Date): string { + const isoString = date.toISOString(); + + return isoString.replace(/[-:]|(\.\d+Z)/g, ""); +} + +function reformatCodeBlocks(msgText: string): string { + const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g; + msgText = msgText.replace( + codeBlockFenceRegex, + (match, metadata, filename, extension) => { + const lang = languageForFilepath(filename); + return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; + }, + ); + // Appease the markdown linter + return msgText.replace(/```\n```/g, "```\n\n```"); +} + +export function toMarkDown(history: ChatMessage[], time?: Date): string { + if (!time) { + time = new Date(); + } + let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${time.toLocaleString()}`; + + for (const msg of history) { + let msgText = renderChatMessage(msg); + if (!msgText) { + continue; // Skip messages without content + } + + if (msg.role === "user" && msgText.search("```") > -1) { + msgText = reformatCodeBlocks(msgText); + } + + // format messages as blockquotes + msgText = msgText.replace(/^/gm, "> "); + + content += `\n\n#### ${ + msg.role === "user" ? "_User_" : "_Assistant_" + }\n\n${msgText}`; + } + return content; +} + +export async function shareSession( + ide: IDE, + history: ChatMessage[], + outputDir?: string, +) { + const now = new Date(); + const content = toMarkDown(history, now); + + outputDir = outputDir ?? getContinueGlobalPath(); + + if (outputDir.startsWith("~")) { + outputDir = outputDir.replace(/^~/, homedir); + } else if ( + outputDir.startsWith("./") || + outputDir.startsWith(".\\") || + outputDir === "." + ) { + const workspaceDirs = await ide.getWorkspaceDirs(); + // Although the most common situation is to have one directory open in a + // workspace it's also possible to have just a file open without an + // associated directory or to use multi-root workspaces in which multiple + // folders are included. We default to using the first item in the list, if + // it exists. + const workspaceDirectory = workspaceDirs?.[0] || ""; + outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory)); + } + + if (!fs.existsSync(outputDir)) { + fs.mkdirSync(outputDir, { recursive: true }); + } + + const dtString = asBasicISOString(getOffsetDatetime(now)); + const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming? + + const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^ + await ide.writeFile(fileUrl, content); + await ide.openFile(fileUrl); + return fileUrl; +} diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 5b7116451..3fe3fab99 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -243,6 +243,12 @@ "icon": "$(add)", "group": "Continue" }, + { + "command": "continue.shareSession", + "category": "Continue", + "title": "Share Current Chat Session as Markdown", + "group": "Continue" + }, { "command": "continue.viewHistory", "category": "Continue", diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index cd75d24bd..96dca0d6b 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -415,6 +415,43 @@ const getCommandsMap: ( "continue.newSession": () => { sidebar.webviewProtocol?.request("newSession", undefined); }, + + "continue.shareSession": async (sessionId: string | undefined) => { + if (!sessionId) { + sessionId = await sidebar.webviewProtocol?.request( + "getCurrentSessionId", + undefined, + ); + } + if (!sessionId) { + void vscode.window.showErrorMessage( + "No session ID found. Please start a new session first.", + ); + return; + } + //let user select the destination folder + const destinationFolder = await vscode.window.showOpenDialog({ + canSelectFolders: true, + canSelectFiles: false, + canSelectMany: false, + openLabel: "Select Destination Folder", + }); + if (!destinationFolder || destinationFolder.length === 0) { + return; + } + + try { + // despite core.invoke not being async, we still need to await it, because the 'history/share' command is async + // if not awaited, then errors will not be caught. + await core.invoke("history/share", { + id: sessionId, + outputDir: destinationFolder[0].fsPath, + }); + } catch (error) { + const errorMessage = `Failed to save session: ${error instanceof Error ? error.message : String(error)}`; + void vscode.window.showErrorMessage(errorMessage); + } + }, "continue.viewHistory": () => { vscode.commands.executeCommand("continue.navigateTo", "/history", true); }, diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 516e47983..4f7fa4a1c 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -106,6 +106,7 @@ export class VsCodeMessenger { this.onWebview("toggleDevTools", (msg) => { vscode.commands.executeCommand("continue.viewLogs"); }); + this.onWebview("reloadWindow", (msg) => { vscode.commands.executeCommand("workbench.action.reloadWindow"); }); @@ -254,6 +255,13 @@ export class VsCodeMessenger { editDecorationManager.clear(); }); + this.onWebview("session/share", async (msg) => { + await vscode.commands.executeCommand( + "continue.shareSession", + msg.data.sessionId, + ); + }); + /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/ WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => { this.onWebview(messageType, async (msg) => { diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 0143b1488..a5b1a9b4d 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,4 +1,8 @@ -import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; +import { + ArrowDownOnSquareIcon, + PencilSquareIcon, + TrashIcon, +} from "@heroicons/react/24/outline"; import { SessionMetadata } from "core"; import { getUriPathBasename } from "core/util/uri"; import React, { useContext, useEffect, useState } from "react"; @@ -13,8 +17,11 @@ import { loadSession, updateSession, } from "../../redux/thunks/session"; +import { isShareSessionSupported } from "../../util"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +const shareSessionSupported = isShareSessionSupported(); + export function HistoryTableRow({ sessionMetadata, index, @@ -37,6 +44,15 @@ export function HistoryTableRow({ setSessionTitleEditValue(sessionMetadata.title); }, [sessionMetadata]); + const shareSession = async (sessionId: string) => { + // "session/share" is not supported in JetBrains yet + if (shareSessionSupported) { + await ideMessenger.request("session/share", { + sessionId, + }); + } + }; + const handleKeyUp = async (e: React.KeyboardEvent) => { if (e.key === "Enter") { if (sessionTitleEditValue !== sessionMetadata.title) { @@ -127,6 +143,17 @@ export function HistoryTableRow({ > + {shareSessionSupported && ( + { + e.stopPropagation(); + await shareSession(sessionMetadata.sessionId); + }} + > + + + )} { diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts index d4cc451f4..ed20fe63f 100644 --- a/gui/src/util/index.ts +++ b/gui/src/util/index.ts @@ -59,6 +59,8 @@ export function isJetBrains() { return getLocalStorage("ide") === "jetbrains"; } +export const isShareSessionSupported = () => !isJetBrains(); + export function isWebEnvironment(): boolean { return ( typeof window !== "undefined" &&