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