(
chatsDir: string,
currentSessionId?: string,
options: GetSessionOptions = {},
)
| 358 | * Corrupted files are automatically filtered out. |
| 359 | */ |
| 360 | export const getSessionFiles = async ( |
| 361 | chatsDir: string, |
| 362 | currentSessionId?: string, |
| 363 | options: GetSessionOptions = {}, |
| 364 | ): Promise<SessionInfo[]> => { |
| 365 | const allFiles = await getAllSessionFiles( |
| 366 | chatsDir, |
| 367 | currentSessionId, |
| 368 | options, |
| 369 | ); |
| 370 | |
| 371 | // Filter out corrupted files and extract SessionInfo |
| 372 | const validSessions = allFiles |
| 373 | .filter( |
| 374 | (entry): entry is { fileName: string; sessionInfo: SessionInfo } => |
| 375 | entry.sessionInfo !== null, |
| 376 | ) |
| 377 | .map((entry) => entry.sessionInfo); |
| 378 | |
| 379 | // Deduplicate sessions by ID |
| 380 | const uniqueSessionsMap = new Map<string, SessionInfo>(); |
| 381 | for (const session of validSessions) { |
| 382 | // If duplicate exists, keep the one with the later lastUpdated timestamp |
| 383 | if ( |
| 384 | !uniqueSessionsMap.has(session.id) || |
| 385 | new Date(session.lastUpdated).getTime() > |
| 386 | new Date(uniqueSessionsMap.get(session.id)!.lastUpdated).getTime() |
| 387 | ) { |
| 388 | uniqueSessionsMap.set(session.id, session); |
| 389 | } |
| 390 | } |
| 391 | const uniqueSessions = Array.from(uniqueSessionsMap.values()); |
| 392 | |
| 393 | // Sort by startTime (oldest first) for stable session numbering |
| 394 | uniqueSessions.sort( |
| 395 | (a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime(), |
| 396 | ); |
| 397 | |
| 398 | // Set the correct 1-based indexes after sorting |
| 399 | uniqueSessions.forEach((session, index) => { |
| 400 | session.index = index + 1; |
| 401 | }); |
| 402 | |
| 403 | return uniqueSessions; |
| 404 | }; |
| 405 | |
| 406 | /** |
| 407 | * Utility class for session discovery and selection. |
no test coverage detected