| 1 | import fs from "fs"; |
| 2 | import os from "os"; |
| 3 | import path from "path"; |
| 4 | |
| 5 | import type { |
| 6 | BaseSessionMetadata, |
| 7 | ChatHistoryItem, |
| 8 | Session, |
| 9 | } from "core/index.js"; |
| 10 | import historyManager from "core/util/history.js"; |
| 11 | import { v4 as uuidv4 } from "uuid"; |
| 12 | |
| 13 | import { |
| 14 | getAccessToken, |
| 15 | isAuthenticatedConfig, |
| 16 | loadAuthConfig, |
| 17 | } from "./auth/workos.js"; |
| 18 | import { DEFAULT_SESSION_TITLE } from "./constants/session.js"; |
| 19 | import { env } from "./env.js"; |
| 20 | import { logger } from "./util/logger.js"; |
| 21 | |
| 22 | // Re-export BaseSessionMetadata for external consumers |
| 23 | export type { BaseSessionMetadata }; |
| 24 | |
| 25 | // Extended type for sessions that can be local or remote |
| 26 | export interface ExtendedSessionMetadata extends BaseSessionMetadata { |
| 27 | firstUserMessage?: string; |
| 28 | isRemote?: boolean; |
| 29 | remoteId?: string; // For remote sessions, this is the agent ID |
| 30 | } |
| 31 | |
| 32 | // Note: We now use UUID-based session IDs instead of terminal-based IDs. |
| 33 | // Each new chat session gets a unique UUID. |
| 34 | // The --resume flag loads the most recent session. |
| 35 | |
| 36 | /** |
| 37 | * Get the session storage directory |
| 38 | */ |
| 39 | function getSessionDir(): string { |
| 40 | // For tests, use the test directory if we're in test mode |
| 41 | if (process.env.CONTINUE_CLI_TEST && process.env.HOME) { |
| 42 | const sessionDir = path.join(process.env.HOME, ".continue", "sessions"); |
| 43 | |
| 44 | // Create directory if it doesn't exist |
| 45 | if (!fs.existsSync(sessionDir)) { |
| 46 | fs.mkdirSync(sessionDir, { recursive: true }); |
| 47 | } |
| 48 | |
| 49 | return sessionDir; |
| 50 | } |
| 51 | |
| 52 | // Use CONTINUE_GLOBAL_DIR if set (for testing) |
| 53 | const continueHome = |
| 54 | process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue"); |
| 55 | const sessionDir = path.join(continueHome, "sessions"); |
| 56 | |
| 57 | // Create directory if it doesn't exist |
| 58 | if (!fs.existsSync(sessionDir)) { |
| 59 | fs.mkdirSync(sessionDir, { recursive: true }); |
| 60 | } |
| 61 | |
| 62 | return sessionDir; |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Get the session file path for the current session |
| 67 | */ |
| 68 | export function getSessionFilePath(): string { |
| 69 | const sessionId = getCurrentSessionId(); |
| 70 | const sessionDir = getSessionDir(); |
| 71 | return path.join(sessionDir, `${sessionId}.json`); |
| 72 | } |
| 73 | |
| 74 | // Singleton for current session management |
| 75 | class SessionManager { |
| 76 | private static instance: SessionManager; |
| 77 | private currentSession: Session | null = null; |
| 78 | |
| 79 | private constructor() {} |
| 80 | |
| 81 | static getInstance(): SessionManager { |
| 82 | if (!SessionManager.instance) { |
| 83 | SessionManager.instance = new SessionManager(); |
| 84 | } |
| 85 | return SessionManager.instance; |
| 86 | } |
| 87 | |
| 88 | getCurrentSession(): Session { |
| 89 | if (!this.currentSession) { |
| 90 | // Use test session ID for testing consistency |
| 91 | const sessionId = process.env.CONTINUE_CLI_TEST_SESSION_ID |
| 92 | ? process.env.CONTINUE_CLI_TEST_SESSION_ID |
| 93 | : uuidv4(); |
| 94 | |
| 95 | this.currentSession = { |
| 96 | sessionId, |
| 97 | title: DEFAULT_SESSION_TITLE, |
| 98 | workspaceDirectory: process.cwd(), |
| 99 | history: [], |
| 100 | }; |
| 101 | } |
| 102 | return this.currentSession; |
| 103 | } |
| 104 | |
| 105 | setSession(session: Session): void { |
| 106 | this.currentSession = session; |
| 107 | } |
| 108 | |
| 109 | updateHistory(history: ChatHistoryItem[]): void { |
| 110 | const session = this.getCurrentSession(); |
| 111 | session.history = history; |
| 112 | saveSession(); |
| 113 | } |
| 114 | |
| 115 | updateTitle(title: string): void { |
| 116 | const session = this.getCurrentSession(); |
| 117 | session.title = title; |
| 118 | saveSession(); |
| 119 | } |
| 120 | |
| 121 | clear(): void { |
| 122 | this.currentSession = null; |
| 123 | } |
| 124 | |
| 125 | hasSession(): boolean { |
| 126 | return this.currentSession !== null; |
| 127 | } |
| 128 | |
| 129 | getSessionId(): string { |
| 130 | return this.getCurrentSession().sessionId; |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | function getCurrentSessionId(): string { |
| 135 | return SessionManager.getInstance().getSessionId(); |
| 136 | } |
| 137 | |
| 138 | function modifySessionBeforeSave(session: Session): Session { |
| 139 | const filteredHistory = session.history.filter((item) => { |
| 140 | return item.message.role !== "system"; |
| 141 | }); |
| 142 | |
| 143 | const modifiedHistory = filteredHistory.map((item) => { |
| 144 | if (item.message.role === "user") { |
| 145 | return { |
| 146 | ...item, |
| 147 | editorState: item.message.content, |
| 148 | }; |
| 149 | } |
| 150 | |
| 151 | return item; |
| 152 | }); |
| 153 | |
| 154 | return { |
| 155 | ...session, |
| 156 | history: modifiedHistory, |
| 157 | }; |
| 158 | } |
| 159 | |
| 160 | export function getSessionPersistenceSnapshot(session: Session): Session { |
| 161 | return modifySessionBeforeSave(session); |
| 162 | } |
| 163 | |
| 164 | /** |
| 165 | * Get the complete state snapshot that matches the /state endpoint format |
| 166 | */ |
| 167 | export interface StateSnapshot { |
| 168 | session: Session; |
| 169 | isProcessing: boolean; |
| 170 | messageQueueLength: number; |
| 171 | pendingPermission: any; |
| 172 | } |
| 173 | |
| 174 | export function getCompleteStateSnapshot( |
| 175 | session: Session, |
| 176 | isProcessing: boolean = false, |
| 177 | messageQueueLength: number = 0, |
| 178 | pendingPermission: any = null, |
| 179 | ): StateSnapshot { |
| 180 | return { |
| 181 | session: getSessionPersistenceSnapshot(session), |
| 182 | isProcessing, |
| 183 | messageQueueLength, |
| 184 | pendingPermission, |
| 185 | }; |
| 186 | } |
| 187 | |
| 188 | /** |
| 189 | * Save the current session to file |
| 190 | */ |
| 191 | export function saveSession(): void { |
| 192 | try { |
| 193 | const session = SessionManager.getInstance().getCurrentSession(); |
| 194 | const sessionToSave = getSessionPersistenceSnapshot(session); |
| 195 | historyManager.save(sessionToSave); |
| 196 | } catch (error) { |
| 197 | logger.error("Error saving session:", error); |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | /** |
| 202 | * Load session from current terminal's session file |
| 203 | */ |
| 204 | export function loadSession(): Session | null { |
| 205 | try { |
| 206 | // For resume, we need to find the most recent session |
| 207 | const sessionDir = getSessionDir(); |
| 208 | if (!fs.existsSync(sessionDir)) { |
| 209 | return null; |
| 210 | } |
| 211 | |
| 212 | const files = fs |
| 213 | .readdirSync(sessionDir) |
| 214 | .filter((f) => f.endsWith(".json") && f !== "sessions.json") |
| 215 | .map((f) => ({ |
| 216 | name: f, |
| 217 | path: path.join(sessionDir, f), |
| 218 | mtime: fs.statSync(path.join(sessionDir, f)).mtime, |
| 219 | })) |
| 220 | .sort((a, b) => b.mtime.getTime() - a.mtime.getTime()); |
| 221 | |
| 222 | if (files.length === 0) { |
| 223 | return null; |
| 224 | } |
| 225 | |
| 226 | // Load the most recent session |
| 227 | const session: Session = JSON.parse(fs.readFileSync(files[0].path, "utf8")); |
| 228 | // Set this as the current session for future saves |
| 229 | SessionManager.getInstance().setSession(session); |
| 230 | return session; |
| 231 | } catch (error) { |
| 232 | logger.error("Error loading session:", error); |
| 233 | return null; |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | /** |
| 238 | * Create a new session |
| 239 | */ |
| 240 | export function createSession(history: ChatHistoryItem[] = []): Session { |
| 241 | const session: Session = { |
| 242 | sessionId: uuidv4(), |
| 243 | title: DEFAULT_SESSION_TITLE, |
| 244 | workspaceDirectory: process.cwd(), |
| 245 | history, |
| 246 | }; |
| 247 | SessionManager.getInstance().setSession(session); |
| 248 | return session; |
| 249 | } |
| 250 | |
| 251 | /** |
| 252 | * Clear the current session |
| 253 | */ |
| 254 | export function clearSession(): void { |
| 255 | try { |
| 256 | const manager = SessionManager.getInstance(); |
| 257 | if (manager.hasSession()) { |
| 258 | const sessionFilePath = path.join( |
| 259 | getSessionDir(), |
| 260 | `${manager.getSessionId()}.json`, |
| 261 | ); |
| 262 | if (fs.existsSync(sessionFilePath)) { |
| 263 | fs.unlinkSync(sessionFilePath); |
| 264 | } |
| 265 | manager.clear(); |
| 266 | } |
| 267 | } catch (error) { |
| 268 | logger.error("Error clearing session:", error); |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | /** |
| 273 | * Check if a session exists for the current terminal |
| 274 | */ |
| 275 | export function hasSession(): boolean { |
| 276 | const manager = SessionManager.getInstance(); |
| 277 | if (!manager.hasSession()) { |
| 278 | return false; |
| 279 | } |
| 280 | const sessionFilePath = path.join( |
| 281 | getSessionDir(), |
| 282 | `${manager.getSessionId()}.json`, |
| 283 | ); |
| 284 | return fs.existsSync(sessionFilePath); |
| 285 | } |
| 286 | |
| 287 | /** |
| 288 | * Get metadata from a session file with first user message preview |
| 289 | */ |
| 290 | function getSessionMetadataWithPreview( |
| 291 | filePath: string, |
| 292 | ): ExtendedSessionMetadata | null { |
| 293 | try { |
| 294 | const sessionData: Session = JSON.parse(fs.readFileSync(filePath, "utf8")); |
| 295 | const stats = fs.statSync(filePath); |
| 296 | |
| 297 | // Find the first user message for preview |
| 298 | let firstUserMessage: string | undefined; |
| 299 | for (const item of sessionData.history || []) { |
| 300 | if (item.message.role === "user") { |
| 301 | const content = item.message.content; |
| 302 | // Handle both string and array content types |
| 303 | if (typeof content === "string") { |
| 304 | firstUserMessage = content; |
| 305 | } else if (Array.isArray(content)) { |
| 306 | // For array content, find the first text part |
| 307 | const textPart = content.find((part) => part.type === "text"); |
| 308 | firstUserMessage = |
| 309 | textPart && "text" in textPart |
| 310 | ? textPart.text |
| 311 | : "(multimodal message)"; |
| 312 | } else { |
| 313 | firstUserMessage = "(unknown content type)"; |
| 314 | } |
| 315 | break; |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | return { |
| 320 | sessionId: sessionData.sessionId, |
| 321 | title: sessionData.title || DEFAULT_SESSION_TITLE, |
| 322 | dateCreated: stats.birthtime.toISOString(), |
| 323 | workspaceDirectory: sessionData.workspaceDirectory || "", |
| 324 | firstUserMessage, |
| 325 | }; |
| 326 | } catch (error) { |
| 327 | logger.error(`Error reading session file ${filePath}:`, error); |
| 328 | return null; |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | /** |
| 333 | * Fetch remote agents/sessions from the API |
| 334 | */ |
| 335 | export async function getRemoteSessions(): Promise<ExtendedSessionMetadata[]> { |
| 336 | try { |
| 337 | const authConfig = loadAuthConfig(); |
| 338 | const accessToken = getAccessToken(authConfig); |
| 339 | |
| 340 | if ( |
| 341 | !accessToken || |
| 342 | !isAuthenticatedConfig(authConfig) || |
| 343 | !authConfig.userEmail.endsWith("@continue.dev") |
| 344 | ) { |
| 345 | return []; |
| 346 | } |
| 347 | |
| 348 | const response = await fetch(new URL("agents", env.apiBase), { |
| 349 | method: "GET", |
| 350 | headers: { |
| 351 | "Content-Type": "application/json", |
| 352 | Authorization: `Bearer ${accessToken}`, |
| 353 | }, |
| 354 | }); |
| 355 | |
| 356 | if (!response.ok) { |
| 357 | logger.error(`Failed to fetch remote agents: ${response.status}`); |
| 358 | return []; |
| 359 | } |
| 360 | |
| 361 | const agents = await response.json(); |
| 362 | |
| 363 | return agents.map((agent: any) => ({ |
| 364 | sessionId: `remote-${agent.id}`, |
| 365 | title: agent.name || "Remote Agent", |
| 366 | dateCreated: new Date(agent.create_time_ms).toISOString(), |
| 367 | workspaceDirectory: "", |
| 368 | isRemote: true, |
| 369 | remoteId: agent.id, |
| 370 | firstUserMessage: "Remote agent session", |
| 371 | })); |
| 372 | } catch (error) { |
| 373 | logger.error("Error fetching remote sessions:", error); |
| 374 | return []; |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | /** |
| 379 | * List all available sessions with metadata (both local and remote) |
| 380 | */ |
| 381 | export async function listSessions( |
| 382 | limit: number = 100, |
| 383 | ): Promise<ExtendedSessionMetadata[]> { |
| 384 | try { |
| 385 | // Get local sessions |
| 386 | const localSessions = historyManager.list({ limit }); |
| 387 | |
| 388 | // Add first user message preview to each local session |
| 389 | const localSessionsWithPreview: ExtendedSessionMetadata[] = []; |
| 390 | |
| 391 | for (const sessionMeta of localSessions) { |
| 392 | const sessionFilePath = path.join( |
| 393 | getSessionDir(), |
| 394 | `${sessionMeta.sessionId}.json`, |
| 395 | ); |
| 396 | |
| 397 | if (fs.existsSync(sessionFilePath)) { |
| 398 | const metadata = getSessionMetadataWithPreview(sessionFilePath); |
| 399 | if (metadata) { |
| 400 | localSessionsWithPreview.push({ |
| 401 | ...metadata, |
| 402 | isRemote: false, |
| 403 | }); |
| 404 | } |
| 405 | } else { |
| 406 | // Fall back to basic metadata if file doesn't exist |
| 407 | localSessionsWithPreview.push({ |
| 408 | ...sessionMeta, |
| 409 | isRemote: false, |
| 410 | }); |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | // Get remote sessions |
| 415 | const remoteSessions = await getRemoteSessions(); |
| 416 | |
| 417 | // Combine and sort by date (most recent first) |
| 418 | const allSessions = [...localSessionsWithPreview, ...remoteSessions] |
| 419 | .sort( |
| 420 | (a, b) => |
| 421 | new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(), |
| 422 | ) |
| 423 | .slice(0, limit); |
| 424 | |
| 425 | return allSessions; |
| 426 | } catch (error) { |
| 427 | logger.error("Error listing sessions:", error); |
| 428 | return []; |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | /** |
| 433 | * Load session by ID |
| 434 | */ |
| 435 | export function loadSessionById(sessionId: string): Session | null { |
| 436 | try { |
| 437 | const session = historyManager.load(sessionId); |
| 438 | return session; |
| 439 | } catch (error) { |
| 440 | logger.error("Error loading session by ID:", error); |
| 441 | return null; |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | /** |
| 446 | * Update the current session's history |
| 447 | */ |
| 448 | export function updateSessionHistory(history: ChatHistoryItem[]): void { |
| 449 | SessionManager.getInstance().updateHistory(history); |
| 450 | } |
| 451 | |
| 452 | /** |
| 453 | * Update the current session's title |
| 454 | */ |
| 455 | export function updateSessionTitle(title: string): void { |
| 456 | SessionManager.getInstance().updateTitle(title); |
| 457 | } |
| 458 | |
| 459 | /** |
| 460 | * Get the current session |
| 461 | */ |
| 462 | export function getCurrentSession(): Session { |
| 463 | return SessionManager.getInstance().getCurrentSession(); |
| 464 | } |
| 465 | |
| 466 | /** |
| 467 | * Start a new session with a new sessionId |
| 468 | */ |
| 469 | export function startNewSession(history: ChatHistoryItem[] = []): Session { |
| 470 | const manager = SessionManager.getInstance(); |
| 471 | |
| 472 | // Clear the current session from memory (don't delete the file) |
| 473 | manager.clear(); |
| 474 | |
| 475 | // Create a new session with a new sessionId |
| 476 | const newSession: Session = { |
| 477 | sessionId: uuidv4(), |
| 478 | title: DEFAULT_SESSION_TITLE, |
| 479 | workspaceDirectory: process.cwd(), |
| 480 | history, |
| 481 | }; |
| 482 | |
| 483 | manager.setSession(newSession); |
| 484 | return newSession; |
| 485 | } |