diff --git a/README.md b/README.md index fef694115..beb2a4143 100644 --- a/README.md +++ b/README.md @@ -19,3 +19,41 @@ cn ```bash cn --headless "Generate a conventional commit name for the current git changes." ``` + +### Session Management + +The CLI automatically saves your chat history for each terminal session. You can resume where you left off: + +```bash +# Resume the last session in this terminal +cn --resume +``` + +Each terminal window maintains its own separate session, so you can have multiple concurrent conversations without them interfering with each other. + +### Advanced Usage + +```bash +# Resume session with specific assistant +cn --resume --config my-assistant + +# Resume session in headless mode +cn --resume --headless +``` + +## Command Line Options + +- `--headless`: Run in headless mode (no TUI) +- `--config `: Specify assistant configuration path +- `--resume`: Resume the last session for this terminal +- ``: Optional prompt to start with + +## Session Storage + +Sessions are stored in `~/.continue-cli/sessions/` and are automatically managed per terminal window using environment variables like: +- `TERM_SESSION_ID` +- `SSH_TTY` +- `TMUX` +- `STY` + +If none of these are available, the process ID is used as a fallback. diff --git a/package-lock.json b/package-lock.json index 93e9eafa3..30358c7d4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/cli", - "version": "1.1.0", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/cli", - "version": "1.1.0", + "version": "1.2.0", "license": "Apache-2.0", "dependencies": { "@continuedev/openai-adapters": "^1.0.18", @@ -24,9 +24,11 @@ "open": "^10.1.0", "react": "^19.1.0", "readline-sync": "^1.4.10", + "typescript": "^5.8.3", "uuid": "^9.0.1" }, "bin": { + "cn": "dist/index.js", "continue-cli": "dist/index.js" }, "devDependencies": { @@ -13580,9 +13582,7 @@ "version": "5.8.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", - "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/package.json b/package.json index 7471bba38..64458f233 100644 --- a/package.json +++ b/package.json @@ -47,6 +47,7 @@ "open": "^10.1.0", "react": "^19.1.0", "readline-sync": "^1.4.10", + "typescript": "^5.8.3", "uuid": "^9.0.1" }, "devDependencies": { diff --git a/src/args.ts b/src/args.ts index ffac63648..ff2f242c9 100644 --- a/src/args.ts +++ b/src/args.ts @@ -2,6 +2,7 @@ export interface CommandLineArgs { isHeadless: boolean; configPath: string; prompt?: string; // Optional prompt argument + resume?: boolean; // Resume from last session } /** @@ -22,6 +23,10 @@ export function parseArgs(): CommandLineArgs { result.isHeadless = true; } + if (args.includes("--resume")) { + result.resume = true; + } + // Get config path from --config flag const configIndex = args.indexOf("--config"); if (configIndex !== -1 && configIndex + 1 < args.length) { diff --git a/src/index.ts b/src/index.ts index 61e4a40b4..ad150b7b5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,6 +15,7 @@ import { handleSlashCommands } from "./slashCommands.js"; import { streamChatResponse } from "./streamChatResponse.js"; import { constructSystemMessage } from "./systemMessage.js"; import { startTUIChat } from "./ui/index.js"; +import { loadSession, saveSession, hasSession } from "./session.js"; // Parse command line arguments const args = parseArgs(); @@ -84,7 +85,7 @@ async function chat() { // If not in headless mode, start the TUI chat (default) if (!args.isHeadless) { - await startTUIChat(assistant, client, mcpService, args.prompt); + await startTUIChat(assistant, client, mcpService, args.prompt, args.resume); return; } @@ -92,11 +93,26 @@ async function chat() { introMessage(assistant, mcpService); // Rules - const chatHistory: ChatCompletionMessageParam[] = []; - const rulesSystemMessage = assistant.systemMessage; - const systemMessage = constructSystemMessage(rulesSystemMessage); - if (systemMessage) { - chatHistory.push({ role: "system", content: systemMessage }); + let chatHistory: ChatCompletionMessageParam[] = []; + + // Load previous session if --resume flag is used + if (args.resume) { + const savedHistory = loadSession(); + if (savedHistory) { + chatHistory = savedHistory; + console.log(chalk.yellow("Resuming previous session...")); + } else { + console.log(chalk.yellow("No previous session found, starting fresh...")); + } + } + + // If no session loaded or not resuming, initialize with system message + if (chatHistory.length === 0) { + const rulesSystemMessage = assistant.systemMessage; + const systemMessage = constructSystemMessage(rulesSystemMessage); + if (systemMessage) { + chatHistory.push({ role: "system", content: systemMessage }); + } } let isFirstMessage = true; @@ -141,6 +157,8 @@ async function chat() { try { await streamChatResponse(chatHistory, assistant, client); + // Save session after each successful response + saveSession(chatHistory); } catch (e: any) { console.error(`\n${chalk.red(`Error: ${e.message}`)}`); console.info( diff --git a/src/session.ts b/src/session.ts new file mode 100644 index 000000000..d9d448142 --- /dev/null +++ b/src/session.ts @@ -0,0 +1,104 @@ +import { ChatCompletionMessageParam } from "openai/resources.mjs"; +import fs from "fs"; +import path from "path"; +import os from "os"; + +/** + * Get a unique session identifier for the current terminal session + * Uses environment variables to ensure each terminal window has its own session + */ +function getSessionId(): string { + // Use a combination of terminal session ID and process ID to ensure uniqueness + const terminalSession = process.env.TERM_SESSION_ID || + process.env.SSH_TTY || + process.env.TMUX || + process.env.STY || + process.pid.toString(); + + // Clean up the session ID to be filesystem-safe + const cleanSessionId = terminalSession.replace(/[^a-zA-Z0-9-_]/g, '-'); + + return `continue-cli-${cleanSessionId}`; +} + +/** + * Get the session storage directory + */ +function getSessionDir(): string { + const homeDir = os.homedir(); + const sessionDir = path.join(homeDir, '.continue-cli', 'sessions'); + + // Create directory if it doesn't exist + if (!fs.existsSync(sessionDir)) { + fs.mkdirSync(sessionDir, { recursive: true }); + } + + return sessionDir; +} + +/** + * Get the session file path for the current session + */ +function getSessionFilePath(): string { + const sessionId = getSessionId(); + const sessionDir = getSessionDir(); + return path.join(sessionDir, `${sessionId}.json`); +} + +/** + * Save chat history to session file + */ +export function saveSession(chatHistory: ChatCompletionMessageParam[]): void { + try { + const sessionFilePath = getSessionFilePath(); + const sessionData = { + timestamp: new Date().toISOString(), + chatHistory + }; + + fs.writeFileSync(sessionFilePath, JSON.stringify(sessionData, null, 2)); + } catch (error) { + console.error('Error saving session:', error); + } +} + +/** + * Load chat history from session file + */ +export function loadSession(): ChatCompletionMessageParam[] | null { + try { + const sessionFilePath = getSessionFilePath(); + + if (!fs.existsSync(sessionFilePath)) { + return null; + } + + const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, 'utf8')); + return sessionData.chatHistory || null; + } catch (error) { + console.error('Error loading session:', error); + return null; + } +} + +/** + * Clear the current session + */ +export function clearSession(): void { + try { + const sessionFilePath = getSessionFilePath(); + if (fs.existsSync(sessionFilePath)) { + fs.unlinkSync(sessionFilePath); + } + } catch (error) { + console.error('Error clearing session:', error); + } +} + +/** + * Check if a session exists for the current terminal + */ +export function hasSession(): boolean { + const sessionFilePath = getSessionFilePath(); + return fs.existsSync(sessionFilePath); +} \ No newline at end of file diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index f05c4567a..73cd8faec 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -7,6 +7,7 @@ import { handleSlashCommands } from "../slashCommands.js"; import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; import { getToolDisplayName } from "../tools.js"; +import { loadSession, saveSession, hasSession } from "../session.js"; import LoadingAnimation from "./LoadingAnimation.js"; import ToolResultSummary from "./ToolResultSummary.js"; import UserInput from "./UserInput.js"; @@ -15,6 +16,7 @@ interface TUIChatProps { assistant: ContinueClient["assistant"]; client: ContinueClient["client"]; initialPrompt?: string; + resume?: boolean; } interface DisplayMessage { @@ -30,21 +32,49 @@ const TUIChat: React.FC = ({ assistant, client, initialPrompt, + resume, }) => { const [chatHistory, setChatHistory] = useState( () => { - const history: ChatCompletionMessageParam[] = []; - const rulesSystemMessage = assistant.systemMessage; - const systemMessage = constructSystemMessage(rulesSystemMessage); - if (systemMessage) { - history.push({ role: "system", content: systemMessage }); + let history: ChatCompletionMessageParam[] = []; + + // Load previous session if --resume flag is used + if (resume) { + const savedHistory = loadSession(); + if (savedHistory) { + history = savedHistory; + } } + + // If no session loaded or not resuming, initialize with system message + if (history.length === 0) { + const rulesSystemMessage = assistant.systemMessage; + const systemMessage = constructSystemMessage(rulesSystemMessage); + if (systemMessage) { + history.push({ role: "system", content: systemMessage }); + } + } + return history; } ); const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); - const [messages, setMessages] = useState([]); + const [messages, setMessages] = useState(() => { + // Convert loaded chat history to display messages (excluding system messages) + if (resume) { + const savedHistory = loadSession(); + if (savedHistory) { + return savedHistory + .filter(msg => msg.role !== "system") + .map(msg => ({ + role: msg.role, + content: msg.content as string + })); + } + } + return []; + }); const [inputMode, setInputMode] = useState(true); const [abortController, setAbortController] = useState(null); @@ -230,6 +260,9 @@ const TUIChat: React.FC = ({ { role: "assistant", content: messageContent, isStreaming: false } ]); } + + // Save session after successful response + saveSession(newHistory); } catch (error: any) { const errorMessage = `Error: ${error.message}`; setMessages((prev) => [ diff --git a/src/ui/index.ts b/src/ui/index.ts index 36eb0fcb5..73207413c 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -9,7 +9,8 @@ export async function startTUIChat( assistant: ContinueClient["assistant"], client: ContinueClient["client"], mcpService: MCPService, - initialPrompt?: string + initialPrompt?: string, + resume?: boolean ) { // Show intro message before starting TUI introMessage(assistant, mcpService); @@ -20,6 +21,7 @@ export async function startTUIChat( assistant, client, initialPrompt, + resume, }) );