feat(cli): export and import sessions (#11075)
* 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 <dallinromney@gmail.com>
This commit is contained in:
parent
2874981435
commit
b155702635
9 changed files with 223 additions and 1 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<string, unknown>;
|
||||
return (
|
||||
obj.version === EXPORTED_SESSION_VERSION &&
|
||||
typeof obj.exportedAt === "string" &&
|
||||
typeof obj.session === "object" &&
|
||||
obj.session !== null &&
|
||||
typeof (obj.session as Record<string, unknown>).sessionId === "string" &&
|
||||
typeof (obj.session as Record<string, unknown>).title === "string" &&
|
||||
Array.isArray((obj.session as Record<string, unknown>).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 <file-path>",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
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<string, CommandHandler> = {
|
||||
help: handleHelp,
|
||||
clear: () => {
|
||||
|
|
@ -261,6 +368,8 @@ const commandHandlers: Record<string, CommandHandler> = {
|
|||
skills: () => handleSkills(),
|
||||
"import-skill": (args) => handleImportSkill(args),
|
||||
sessions: handleSessions,
|
||||
export: handleExport,
|
||||
import: handleImport,
|
||||
};
|
||||
|
||||
export async function handleSlashCommands(
|
||||
|
|
|
|||
|
|
@ -287,6 +287,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
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<TUIChatProps> = ({
|
|||
[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<TUIChatProps> = ({
|
|||
handleConfigSelect={handleConfigSelect}
|
||||
handleModelSelect={handleModelSelect}
|
||||
handleSessionSelect={handleSessionSelect}
|
||||
handleExportSession={handleExportSession}
|
||||
handleReload={handleReload}
|
||||
closeCurrentScreen={closeCurrentScreen}
|
||||
activePermissionRequest={activePermissionRequest}
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ interface ScreenContentProps {
|
|||
handleConfigSelect: (config: ConfigOption) => Promise<void>;
|
||||
handleModelSelect: (model: ModelOption) => Promise<void>;
|
||||
handleSessionSelect: (sessionId: string) => Promise<void>;
|
||||
handleExportSession: (sessionId: string) => Promise<void>;
|
||||
handleReload: () => Promise<void>;
|
||||
closeCurrentScreen: () => void;
|
||||
activePermissionRequest: ActivePermissionRequest | null;
|
||||
|
|
@ -74,6 +75,7 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
|
|||
handleConfigSelect,
|
||||
handleModelSelect,
|
||||
handleSessionSelect,
|
||||
handleExportSession,
|
||||
handleReload,
|
||||
closeCurrentScreen,
|
||||
activePermissionRequest,
|
||||
|
|
@ -164,6 +166,16 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
|
|||
);
|
||||
}
|
||||
|
||||
// Export selector
|
||||
if (isScreenActive("export")) {
|
||||
return (
|
||||
<SessionSelectorWithLoading
|
||||
onSelect={handleExportSession}
|
||||
onExit={closeCurrentScreen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Jobs selector
|
||||
if (isScreenActive("jobs")) {
|
||||
return <JobsSelector onCancel={closeCurrentScreen} />;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ export interface UseChatProps {
|
|||
onShowModelSelector?: () => void;
|
||||
onShowSessionSelector?: () => void;
|
||||
onShowJobsSelector?: () => void;
|
||||
onShowExportSelector?: () => void;
|
||||
onReload?: () => Promise<void>;
|
||||
onClear?: () => void;
|
||||
onRefreshStatic?: () => void;
|
||||
|
|
@ -68,6 +69,7 @@ export interface SlashCommandResult {
|
|||
openUpdateSelector?: boolean;
|
||||
openSessionSelector?: boolean;
|
||||
openJobsSelector?: boolean;
|
||||
openExportSelector?: boolean;
|
||||
compact?: boolean;
|
||||
diffContent?: string;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue