( chatId?: string, )
| 101 | * Returns null if no previous chat exists or files can't be parsed. |
| 102 | */ |
| 103 | export function loadMostRecentChatState( |
| 104 | chatId?: string, |
| 105 | ): SavedChatState | null { |
| 106 | try { |
| 107 | let chatDir: string | null = null |
| 108 | |
| 109 | if (chatId && chatId.trim().length > 0) { |
| 110 | const baseDir = path.join(getProjectDataDir(), 'chats') |
| 111 | const candidateDir = path.join(baseDir, chatId.trim()) |
| 112 | if ( |
| 113 | fs.existsSync(candidateDir) && |
| 114 | fs.statSync(candidateDir).isDirectory() |
| 115 | ) { |
| 116 | chatDir = candidateDir |
| 117 | } else { |
| 118 | logger.debug( |
| 119 | { candidateDir, chatId }, |
| 120 | 'Requested chatId directory not found, falling back to most recent chat directory', |
| 121 | ) |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | if (!chatDir) { |
| 126 | chatDir = getMostRecentChatDir() |
| 127 | } |
| 128 | |
| 129 | if (!chatDir) { |
| 130 | logger.debug('No previous chat directory found') |
| 131 | return null |
| 132 | } |
| 133 | |
| 134 | const runStatePath = path.join(chatDir, RUN_STATE_FILENAME) |
| 135 | const messagesPath = path.join(chatDir, CHAT_MESSAGES_FILENAME) |
| 136 | |
| 137 | if (!fs.existsSync(runStatePath) || !fs.existsSync(messagesPath)) { |
| 138 | logger.debug( |
| 139 | { runStatePath, messagesPath }, |
| 140 | 'Missing state files in chat directory', |
| 141 | ) |
| 142 | return null |
| 143 | } |
| 144 | |
| 145 | const runStateContent = fs.readFileSync(runStatePath, 'utf8') |
| 146 | const messagesContent = fs.readFileSync(messagesPath, 'utf8') |
| 147 | |
| 148 | const runState = JSON.parse(runStateContent) as RunState |
| 149 | runState.traceSessionId ??= randomUUID() |
| 150 | const messages = JSON.parse(messagesContent) as ChatMessage[] |
| 151 | |
| 152 | const resolvedChatId = path.basename(chatDir) |
| 153 | |
| 154 | logger.info( |
| 155 | { |
| 156 | runStatePath, |
| 157 | messagesPath, |
| 158 | messageCount: messages.length, |
| 159 | chatId: resolvedChatId, |
| 160 | }, |
no test coverage detected