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>
This commit is contained in:
parent
a37f3730c5
commit
71a0a1cd7d
10 changed files with 202 additions and 89 deletions
|
|
@ -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}\`.`;
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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];
|
||||
|
|
|
|||
|
|
@ -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 & {
|
||||
|
|
|
|||
105
core/util/historyUtils.ts
Normal file
105
core/util/historyUtils.ts
Normal file
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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) => {
|
||||
|
|
|
|||
|
|
@ -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<HTMLInputElement>) => {
|
||||
if (e.key === "Enter") {
|
||||
if (sessionTitleEditValue !== sessionMetadata.title) {
|
||||
|
|
@ -127,6 +143,17 @@ export function HistoryTableRow({
|
|||
>
|
||||
<PencilSquareIcon width="1em" height="1em" />
|
||||
</HeaderButtonWithToolTip>
|
||||
{shareSessionSupported && (
|
||||
<HeaderButtonWithToolTip
|
||||
text="Save Chat as Markdown"
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
await shareSession(sessionMetadata.sessionId);
|
||||
}}
|
||||
>
|
||||
<ArrowDownOnSquareIcon width="1em" height="1em" />
|
||||
</HeaderButtonWithToolTip>
|
||||
)}
|
||||
<HeaderButtonWithToolTip
|
||||
text="Delete"
|
||||
onClick={async (e) => {
|
||||
|
|
|
|||
|
|
@ -59,6 +59,8 @@ export function isJetBrains() {
|
|||
return getLocalStorage("ide") === "jetbrains";
|
||||
}
|
||||
|
||||
export const isShareSessionSupported = () => !isJetBrains();
|
||||
|
||||
export function isWebEnvironment(): boolean {
|
||||
return (
|
||||
typeof window !== "undefined" &&
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue