| 1 | import fs from "fs"; |
| 2 | import os from "os"; |
| 3 | import path from "path"; |
| 4 | |
| 5 | import type { ChatHistoryItem, Session, SessionMetadata } from "core/index.js"; |
| 6 | import historyManager from "core/util/history.js"; |
| 7 | import { v4 as uuidv4 } from "uuid"; |
| 8 | |
| 9 | import { DEFAULT_SESSION_TITLE } from "./constants/session.js"; |
| 10 | import { logger } from "./util/logger.js"; |
| 11 | |
| 12 | // Re-export SessionMetadata for external consumers |
| 13 | export type { SessionMetadata }; |
| 14 | |
| 15 | // Note: We now use UUID-based session IDs instead of terminal-based IDs. |
| 16 | // Each new chat session gets a unique UUID. |
| 17 | // The --resume flag loads the most recent session. |
| 18 | |
| 19 | /** |
| 20 | * Get the session storage directory |
| 21 | */ |
| 22 | function getSessionDir(): string { |
| 23 | // For tests, use the test directory if we're in test mode |
| 24 | if (process.env.CONTINUE_CLI_TEST && process.env.HOME) { |
| 25 | const sessionDir = path.join(process.env.HOME, ".continue", "sessions"); |
| 26 | |
| 27 | // Create directory if it doesn't exist |
| 28 | if (!fs.existsSync(sessionDir)) { |
| 29 | fs.mkdirSync(sessionDir, { recursive: true }); |
| 30 | } |
| 31 | |
| 32 | return sessionDir; |
| 33 | } |
| 34 | |
| 35 | // Use CONTINUE_GLOBAL_DIR if set (for testing) |
| 36 | const continueHome = |
| 37 | process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue"); |
| 38 | const sessionDir = path.join(continueHome, "sessions"); |
| 39 | |
| 40 | // Create directory if it doesn't exist |
| 41 | if (!fs.existsSync(sessionDir)) { |
| 42 | fs.mkdirSync(sessionDir, { recursive: true }); |
| 43 | } |
| 44 | |
| 45 | return sessionDir; |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Get the session file path for the current session |
| 50 | */ |
| 51 | export function getSessionFilePath(): string { |
| 52 | const sessionId = getCurrentSessionId(); |
| 53 | const sessionDir = getSessionDir(); |
| 54 | return path.join(sessionDir, `${sessionId}.json`); |
| 55 | } |
| 56 | |
| 57 | // Singleton for current session management |
| 58 | class SessionManager { |
| 59 | private static instance: SessionManager; |
| 60 | private currentSession: Session | null = null; |
| 61 | |
| 62 | private constructor() {} |
| 63 | |
| 64 | static getInstance(): SessionManager { |
| 65 | if (!SessionManager.instance) { |
| 66 | SessionManager.instance = new SessionManager(); |
| 67 | } |
| 68 | return SessionManager.instance; |
| 69 | } |
| 70 | |
| 71 | getCurrentSession(): Session { |
| 72 | if (!this.currentSession) { |
| 73 | // Use test session ID for testing consistency |
| 74 | const sessionId = process.env.CONTINUE_CLI_TEST_SESSION_ID |
| 75 | ? process.env.CONTINUE_CLI_TEST_SESSION_ID |
| 76 | : uuidv4(); |
| 77 | |
| 78 | this.currentSession = { |
| 79 | sessionId, |
| 80 | title: DEFAULT_SESSION_TITLE, |
| 81 | workspaceDirectory: process.cwd(), |
| 82 | history: [], |
| 83 | }; |
| 84 | } |
| 85 | return this.currentSession; |
| 86 | } |
| 87 | |
| 88 | setSession(session: Session): void { |
| 89 | this.currentSession = session; |
| 90 | } |
| 91 | |
| 92 | updateHistory(history: ChatHistoryItem[]): void { |
| 93 | const session = this.getCurrentSession(); |
| 94 | session.history = history; |
| 95 | saveSession(); |
| 96 | } |
| 97 | |
| 98 | updateTitle(title: string): void { |
| 99 | const session = this.getCurrentSession(); |
| 100 | session.title = title; |
| 101 | saveSession(); |
| 102 | } |
| 103 | |
| 104 | clear(): void { |
| 105 | this.currentSession = null; |
| 106 | } |
| 107 | |
| 108 | hasSession(): boolean { |
| 109 | return this.currentSession !== null; |
| 110 | } |
| 111 | |
| 112 | getSessionId(): string { |
| 113 | return this.getCurrentSession().sessionId; |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | function getCurrentSessionId(): string { |
| 118 | return SessionManager.getInstance().getSessionId(); |
| 119 | } |
| 120 | |
| 121 | function modifySessionBeforeSave(session: Session): Session { |
| 122 | const filteredHistory = session.history.filter((item) => { |
| 123 | return item.message.role !== "system"; |
| 124 | }); |
| 125 | |
| 126 | const modifiedHistory = filteredHistory.map((item) => { |
| 127 | if (item.message.role === "user") { |
| 128 | return { |
| 129 | ...item, |
| 130 | editorState: item.message.content, |
| 131 | }; |
| 132 | } |
| 133 | |
| 134 | return item; |
| 135 | }); |
| 136 | |
| 137 | return { |
| 138 | ...session, |
| 139 | history: modifiedHistory, |
| 140 | }; |
| 141 | } |
| 142 | |
| 143 | /** |
| 144 | * Save the current session to file |
| 145 | */ |
| 146 | export function saveSession(): void { |
| 147 | try { |
| 148 | const session = SessionManager.getInstance().getCurrentSession(); |
| 149 | const sessionToSave = modifySessionBeforeSave(session); |
| 150 | historyManager.save(sessionToSave); |
| 151 | } catch (error) { |
| 152 | logger.error("Error saving session:", error); |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /** |
| 157 | * Load session from current terminal's session file |
| 158 | */ |
| 159 | export function loadSession(): Session | null { |
| 160 | try { |
| 161 | // For resume, we need to find the most recent session |
| 162 | const sessionDir = getSessionDir(); |
| 163 | if (!fs.existsSync(sessionDir)) { |
| 164 | return null; |
| 165 | } |
| 166 | |
| 167 | const files = fs |
| 168 | .readdirSync(sessionDir) |
| 169 | .filter((f) => f.endsWith(".json") && f !== "sessions.json") |
| 170 | .map((f) => ({ |
| 171 | name: f, |
| 172 | path: path.join(sessionDir, f), |
| 173 | mtime: fs.statSync(path.join(sessionDir, f)).mtime, |
| 174 | })) |
| 175 | .sort((a, b) => b.mtime.getTime() - a.mtime.getTime()); |
| 176 | |
| 177 | if (files.length === 0) { |
| 178 | return null; |
| 179 | } |
| 180 | |
| 181 | // Load the most recent session |
| 182 | const session: Session = JSON.parse(fs.readFileSync(files[0].path, "utf8")); |
| 183 | // Set this as the current session for future saves |
| 184 | SessionManager.getInstance().setSession(session); |
| 185 | return session; |
| 186 | } catch (error) { |
| 187 | logger.error("Error loading session:", error); |
| 188 | return null; |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | /** |
| 193 | * Create a new session |
| 194 | */ |
| 195 | export function createSession(history: ChatHistoryItem[] = []): Session { |
| 196 | const session: Session = { |
| 197 | sessionId: uuidv4(), |
| 198 | title: DEFAULT_SESSION_TITLE, |
| 199 | workspaceDirectory: process.cwd(), |
| 200 | history, |
| 201 | }; |
| 202 | SessionManager.getInstance().setSession(session); |
| 203 | return session; |
| 204 | } |
| 205 | |
| 206 | /** |
| 207 | * Clear the current session |
| 208 | */ |
| 209 | export function clearSession(): void { |
| 210 | try { |
| 211 | const manager = SessionManager.getInstance(); |
| 212 | if (manager.hasSession()) { |
| 213 | const sessionFilePath = path.join( |
| 214 | getSessionDir(), |
| 215 | `${manager.getSessionId()}.json`, |
| 216 | ); |
| 217 | if (fs.existsSync(sessionFilePath)) { |
| 218 | fs.unlinkSync(sessionFilePath); |
| 219 | } |
| 220 | manager.clear(); |
| 221 | } |
| 222 | } catch (error) { |
| 223 | logger.error("Error clearing session:", error); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /** |
| 228 | * Check if a session exists for the current terminal |
| 229 | */ |
| 230 | export function hasSession(): boolean { |
| 231 | const manager = SessionManager.getInstance(); |
| 232 | if (!manager.hasSession()) { |
| 233 | return false; |
| 234 | } |
| 235 | const sessionFilePath = path.join( |
| 236 | getSessionDir(), |
| 237 | `${manager.getSessionId()}.json`, |
| 238 | ); |
| 239 | return fs.existsSync(sessionFilePath); |
| 240 | } |
| 241 | |
| 242 | /** |
| 243 | * Get metadata from a session file with first user message preview |
| 244 | */ |
| 245 | function getSessionMetadataWithPreview( |
| 246 | filePath: string, |
| 247 | ): (SessionMetadata & { firstUserMessage?: string }) | null { |
| 248 | try { |
| 249 | const sessionData: Session = JSON.parse(fs.readFileSync(filePath, "utf8")); |
| 250 | const stats = fs.statSync(filePath); |
| 251 | |
| 252 | // Find the first user message for preview |
| 253 | let firstUserMessage: string | undefined; |
| 254 | for (const item of sessionData.history || []) { |
| 255 | if (item.message.role === "user") { |
| 256 | const content = item.message.content; |
| 257 | // Handle both string and array content types |
| 258 | if (typeof content === "string") { |
| 259 | firstUserMessage = content; |
| 260 | } else if (Array.isArray(content)) { |
| 261 | // For array content, find the first text part |
| 262 | const textPart = content.find((part) => part.type === "text"); |
| 263 | firstUserMessage = |
| 264 | textPart && "text" in textPart |
| 265 | ? textPart.text |
| 266 | : "(multimodal message)"; |
| 267 | } else { |
| 268 | firstUserMessage = "(unknown content type)"; |
| 269 | } |
| 270 | break; |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | return { |
| 275 | sessionId: sessionData.sessionId, |
| 276 | title: sessionData.title || DEFAULT_SESSION_TITLE, |
| 277 | dateCreated: stats.birthtime.toISOString(), |
| 278 | workspaceDirectory: sessionData.workspaceDirectory || "", |
| 279 | firstUserMessage, |
| 280 | }; |
| 281 | } catch (error) { |
| 282 | logger.error(`Error reading session file ${filePath}:`, error); |
| 283 | return null; |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | /** |
| 288 | * List all available sessions with metadata |
| 289 | */ |
| 290 | export function listSessions( |
| 291 | limit: number = 10, |
| 292 | ): (SessionMetadata & { firstUserMessage?: string })[] { |
| 293 | try { |
| 294 | const sessions = historyManager.list({ limit }); |
| 295 | |
| 296 | // Add first user message preview to each session |
| 297 | const sessionsWithPreview: (SessionMetadata & { |
| 298 | firstUserMessage?: string; |
| 299 | })[] = []; |
| 300 | |
| 301 | for (const sessionMeta of sessions) { |
| 302 | const sessionFilePath = path.join( |
| 303 | getSessionDir(), |
| 304 | `${sessionMeta.sessionId}.json`, |
| 305 | ); |
| 306 | |
| 307 | if (fs.existsSync(sessionFilePath)) { |
| 308 | const metadata = getSessionMetadataWithPreview(sessionFilePath); |
| 309 | if (metadata) { |
| 310 | sessionsWithPreview.push(metadata); |
| 311 | } |
| 312 | } else { |
| 313 | // Fall back to basic metadata if file doesn't exist |
| 314 | sessionsWithPreview.push(sessionMeta); |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | return sessionsWithPreview; |
| 319 | } catch (error) { |
| 320 | logger.error("Error listing sessions:", error); |
| 321 | return []; |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | /** |
| 326 | * Load session by ID |
| 327 | */ |
| 328 | export function loadSessionById(sessionId: string): Session | null { |
| 329 | try { |
| 330 | const session = historyManager.load(sessionId); |
| 331 | return session; |
| 332 | } catch (error) { |
| 333 | logger.error("Error loading session by ID:", error); |
| 334 | return null; |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | /** |
| 339 | * Update the current session's history |
| 340 | */ |
| 341 | export function updateSessionHistory(history: ChatHistoryItem[]): void { |
| 342 | SessionManager.getInstance().updateHistory(history); |
| 343 | } |
| 344 | |
| 345 | /** |
| 346 | * Update the current session's title |
| 347 | */ |
| 348 | export function updateSessionTitle(title: string): void { |
| 349 | SessionManager.getInstance().updateTitle(title); |
| 350 | } |
| 351 | |
| 352 | /** |
| 353 | * Get the current session |
| 354 | */ |
| 355 | export function getCurrentSession(): Session { |
| 356 | return SessionManager.getInstance().getCurrentSession(); |
| 357 | } |
| 358 | |
| 359 | /** |
| 360 | * Start a new session with a new sessionId |
| 361 | */ |
| 362 | export function startNewSession(history: ChatHistoryItem[] = []): Session { |
| 363 | const manager = SessionManager.getInstance(); |
| 364 | |
| 365 | // Clear the current session from memory (don't delete the file) |
| 366 | manager.clear(); |
| 367 | |
| 368 | // Create a new session with a new sessionId |
| 369 | const newSession: Session = { |
| 370 | sessionId: uuidv4(), |
| 371 | title: DEFAULT_SESSION_TITLE, |
| 372 | workspaceDirectory: process.cwd(), |
| 373 | history, |
| 374 | }; |
| 375 | |
| 376 | manager.setSession(newSession); |
| 377 | return newSession; |
| 378 | } |