From b155702635df673a09d4c53cf24d33ae32f23bb9 Mon Sep 17 00:00:00 2001 From: Aditya Mitra <61635505+uinstinct@users.noreply.github.com> Date: Wed, 25 Mar 2026 02:54:30 +0530 Subject: [PATCH] feat(cli): export and import sessions (#11075) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * add session export slash command * import session * Fix slashCommands test: mock path.isAbsolute and history manager The import of historyManager in slashCommands.ts triggers core/util/paths.ts which calls path.isAbsolute — not provided by the existing path mock. Add the missing path exports and mock core/util/history.js to avoid filesystem operations in tests. --------- Co-authored-by: Dallin Romney --- extensions/cli/src/commands/commands.ts | 10 ++ extensions/cli/src/slashCommands.test.ts | 13 +++ extensions/cli/src/slashCommands.ts | 109 ++++++++++++++++++ extensions/cli/src/ui/TUIChat.tsx | 67 +++++++++++ .../cli/src/ui/components/ScreenContent.tsx | 12 ++ .../cli/src/ui/context/NavigationContext.tsx | 2 +- .../cli/src/ui/hooks/useChat.helpers.ts | 7 ++ extensions/cli/src/ui/hooks/useChat.ts | 2 + extensions/cli/src/ui/hooks/useChat.types.ts | 2 + 9 files changed, 223 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/commands/commands.ts b/extensions/cli/src/commands/commands.ts index dad5f8bb4..9f057af44 100644 --- a/extensions/cli/src/commands/commands.ts +++ b/extensions/cli/src/commands/commands.ts @@ -131,6 +131,16 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ description: "Import a skill from a URL or name into ~/.continue/skills", category: "system", }, + { + name: "export", + description: "Export a session to JSON file", + category: "system", + }, + { + name: "import", + description: "Import a session from JSON file", + category: "system", + }, ]; // Remote mode specific commands diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index 76ebccd6f..1d3675b26 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -74,8 +74,21 @@ vi.mock("os", () => ({ vi.mock("path", () => ({ default: { join: vi.fn((...parts) => parts.join("/")), + isAbsolute: vi.fn((p: string) => p.startsWith("/")), + resolve: vi.fn((...parts) => parts.join("/")), }, join: vi.fn((...parts) => parts.join("/")), + isAbsolute: vi.fn((p: string) => p.startsWith("/")), + resolve: vi.fn((...parts) => parts.join("/")), +})); + +// Mock history manager to avoid file system operations +vi.mock("core/util/history.js", () => ({ + default: { + list: vi.fn(() => []), + load: vi.fn(() => ({ history: [] })), + save: vi.fn(), + }, })); // Mock session functions diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index 64f3787f7..5b472ca75 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -1,5 +1,10 @@ +import fs from "fs"; + import { type AssistantConfig } from "@continuedev/sdk"; import chalk from "chalk"; +import type { Session } from "core/index.js"; +import historyManager from "core/util/history.js"; +import { v4 as uuidv4 } from "uuid"; import { isAuthenticated, @@ -223,6 +228,108 @@ function handleSessions() { return { openSessionSelector: true }; } +const EXPORTED_SESSION_VERSION = 1; + +interface ExportedSession { + version: number; + exportedAt: string; + session: Session; +} + +function isValidExportedSession(data: unknown): data is ExportedSession { + if (typeof data !== "object" || data === null) { + return false; + } + const obj = data as Record; + return ( + obj.version === EXPORTED_SESSION_VERSION && + typeof obj.exportedAt === "string" && + typeof obj.session === "object" && + obj.session !== null && + typeof (obj.session as Record).sessionId === "string" && + typeof (obj.session as Record).title === "string" && + Array.isArray((obj.session as Record).history) + ); +} + +function handleExport(_args: string[]): SlashCommandResult { + posthogService.capture("useSlashCommand", { name: "export" }); + + return { + exit: false, + openExportSelector: true, + }; +} + +function handleImport(args: string[]): SlashCommandResult { + posthogService.capture("useSlashCommand", { name: "import" }); + + const filePath = args.join(" ").trim(); + if (!filePath) { + return { + exit: false, + output: chalk.yellow( + "Please provide a file path. Usage: /import ", + ), + }; + } + + if (!fs.existsSync(filePath)) { + return { + exit: false, + output: chalk.red(`File not found: ${filePath}`), + }; + } + + try { + const fileContent = fs.readFileSync(filePath, "utf-8"); + const exportedData: unknown = JSON.parse(fileContent); + + if (!isValidExportedSession(exportedData)) { + return { + exit: false, + output: chalk.red( + "Invalid session file: expected a valid Continue exported session (version 1).", + ), + }; + } + + let session = exportedData.session; + + const existing = historyManager.load(session.sessionId); + const sessionExists = existing.history.length > 0; + + if (sessionExists) { + const originalId = session.sessionId; + session = { + ...session, + sessionId: uuidv4(), + }; + historyManager.save(session); + return { + exit: false, + output: chalk.green( + `Session imported with new ID: ${session.sessionId}\n` + + chalk.gray(`(original ID: ${originalId} already existed)`), + ), + }; + } + + historyManager.save(session); + return { + exit: false, + output: chalk.green( + `Session imported: ${session.sessionId} (${session.title})`, + ), + }; + } catch (error: any) { + return { + exit: false, + output: chalk.red(`Failed to import session: ${error.message}`), + }; + } +} + const commandHandlers: Record = { help: handleHelp, clear: () => { @@ -261,6 +368,8 @@ const commandHandlers: Record = { skills: () => handleSkills(), "import-skill": (args) => handleImportSkill(args), sessions: handleSessions, + export: handleExport, + import: handleImport, }; export async function handleSlashCommands( diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 62174cead..21692df23 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -287,6 +287,7 @@ const TUIChat: React.FC = ({ onShowUpdateSelector: () => navigateTo("update"), onShowSessionSelector: () => navigateTo("session"), onShowJobsSelector: () => navigateTo("jobs"), + onShowExportSelector: () => navigateTo("export"), onReload: handleReload, onClear: handleClear, onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1), @@ -332,6 +333,71 @@ const TUIChat: React.FC = ({ [closeCurrentScreen, setChatHistory, setShowIntroMessage], ); + // Export session handler + const handleExportSession = useCallback( + async (sessionId: string) => { + try { + const { loadSessionById } = await import("../session.js"); + const fs = await import("fs"); + const path = await import("path"); + + const session = loadSessionById(sessionId); + if (!session) { + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: `Failed to export: Session ${sessionId} not found`, + }, + contextItems: [], + }, + ]); + closeCurrentScreen(); + return; + } + + const exportPayload = { + version: 1, + exportedAt: new Date().toISOString(), + session, + }; + + const defaultPath = path.join( + process.cwd(), + `continue-session-${session.sessionId}.json`, + ); + const jsonOutput = JSON.stringify(exportPayload, null, 2); + fs.writeFileSync(defaultPath, jsonOutput, "utf-8"); + + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: `Session exported to ${defaultPath}`, + }, + contextItems: [], + }, + ]); + closeCurrentScreen(); + } catch (error: any) { + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: `Failed to export session: ${error.message}`, + }, + contextItems: [], + }, + ]); + closeCurrentScreen(); + } + }, + [closeCurrentScreen, setChatHistory], + ); + // Determine if input should be disabled // Allow input even when services are loading, but disable for UI overlays const isInputDisabled = @@ -432,6 +498,7 @@ const TUIChat: React.FC = ({ handleConfigSelect={handleConfigSelect} handleModelSelect={handleModelSelect} handleSessionSelect={handleSessionSelect} + handleExportSession={handleExportSession} handleReload={handleReload} closeCurrentScreen={closeCurrentScreen} activePermissionRequest={activePermissionRequest} diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 516cb7811..856484c54 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -31,6 +31,7 @@ interface ScreenContentProps { handleConfigSelect: (config: ConfigOption) => Promise; handleModelSelect: (model: ModelOption) => Promise; handleSessionSelect: (sessionId: string) => Promise; + handleExportSession: (sessionId: string) => Promise; handleReload: () => Promise; closeCurrentScreen: () => void; activePermissionRequest: ActivePermissionRequest | null; @@ -74,6 +75,7 @@ export const ScreenContent: React.FC = ({ handleConfigSelect, handleModelSelect, handleSessionSelect, + handleExportSession, handleReload, closeCurrentScreen, activePermissionRequest, @@ -164,6 +166,16 @@ export const ScreenContent: React.FC = ({ ); } + // Export selector + if (isScreenActive("export")) { + return ( + + ); + } + // Jobs selector if (isScreenActive("jobs")) { return ; diff --git a/extensions/cli/src/ui/context/NavigationContext.tsx b/extensions/cli/src/ui/context/NavigationContext.tsx index 04c1689f5..6f389c599 100644 --- a/extensions/cli/src/ui/context/NavigationContext.tsx +++ b/extensions/cli/src/ui/context/NavigationContext.tsx @@ -22,7 +22,7 @@ export type NavigationScreen = | "update" // Update selector | "edit" // Edit message selector | "jobs" // Background Jobs selector - | "session"; // Session selector + | "export"; // Export session selector interface NavigationState { currentScreen: NavigationScreen; diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 6eb49924d..62b9490c0 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -52,6 +52,7 @@ interface ProcessSlashCommandResultOptions { onShowMCPSelector?: () => void; onShowSessionSelector?: () => void; onShowJobsSelector?: () => void; + onShowExportSelector?: () => void; onClear?: () => void; } @@ -68,6 +69,7 @@ export function processSlashCommandResult({ onShowMCPSelector, onShowSessionSelector, onShowJobsSelector, + onShowExportSelector, onClear, }: ProcessSlashCommandResultOptions): string | null { if (result.exit) { @@ -104,6 +106,11 @@ export function processSlashCommandResult({ return null; } + if (result.openExportSelector && onShowExportSelector) { + onShowExportSelector(); + return null; + } + if (result.clear) { const systemMessage = chatHistory.find( (item) => item.message.role === "system", diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 21b0a2c04..09d328e88 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -60,6 +60,7 @@ export function useChat({ onShowMCPSelector, onShowSessionSelector, onShowJobsSelector, + onShowExportSelector, onClear, onRefreshStatic, isRemoteMode = false, @@ -453,6 +454,7 @@ export function useChat({ onShowSessionSelector, onShowJobsSelector, onShowUpdateSelector, + onShowExportSelector, onClear, }); diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index 0e2887c6a..47a9b536a 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -20,6 +20,7 @@ export interface UseChatProps { onShowModelSelector?: () => void; onShowSessionSelector?: () => void; onShowJobsSelector?: () => void; + onShowExportSelector?: () => void; onReload?: () => Promise; onClear?: () => void; onRefreshStatic?: () => void; @@ -68,6 +69,7 @@ export interface SlashCommandResult { openUpdateSelector?: boolean; openSessionSelector?: boolean; openJobsSelector?: boolean; + openExportSelector?: boolean; compact?: boolean; diffContent?: string; }