| 1 | import * as fs from "fs"; |
| 2 | |
| 3 | import { Session, BaseSessionMetadata } from "../index.js"; |
| 4 | import { ListHistoryOptions } from "../protocol/core.js"; |
| 5 | |
| 6 | import { NEW_SESSION_TITLE } from "./constants.js"; |
| 7 | import { |
| 8 | getSessionFilePath, |
| 9 | getSessionsFolderPath, |
| 10 | getSessionsListPath, |
| 11 | } from "./paths.js"; |
| 12 | function safeParseArray<T>( |
| 13 | value: string, |
| 14 | errorMessage: string = "Error parsing array", |
| 15 | ): T[] | undefined { |
| 16 | try { |
| 17 | return JSON.parse(value) as T[]; |
| 18 | } catch (e: any) { |
| 19 | console.warn(`${errorMessage}: ${e}`); |
| 20 | return undefined; |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | export class HistoryManager { |
| 25 | list(options: ListHistoryOptions): BaseSessionMetadata[] { |
| 26 | const filepath = getSessionsListPath(); |
| 27 | if (!fs.existsSync(filepath)) { |
| 28 | return []; |
| 29 | } |
| 30 | const content = fs.readFileSync(filepath, "utf8"); |
| 31 | |
| 32 | let sessions = safeParseArray<BaseSessionMetadata>(content) ?? []; |
| 33 | sessions = sessions |
| 34 | .filter((session: any) => { |
| 35 | // Filter out old format |
| 36 | return typeof session.session_id !== "string"; |
| 37 | // Reverse to show newest first; sessions.json is chronological by creation |
| 38 | }) |
| 39 | .reverse(); |
| 40 | |
| 41 | // Apply limit and offset |
| 42 | if (options.limit) { |
| 43 | const offset = options.offset || 0; |
| 44 | sessions = sessions.slice(offset, offset + options.limit); |
| 45 | } |
| 46 | |
| 47 | return sessions; |
| 48 | } |
| 49 | |
| 50 | delete(sessionId: string) { |
| 51 | // Delete a session |
| 52 | const sessionFile = getSessionFilePath(sessionId); |
| 53 | if (!fs.existsSync(sessionFile)) { |
| 54 | throw new Error(`Session file ${sessionFile} does not exist`); |
| 55 | } |
| 56 | fs.unlinkSync(sessionFile); |
| 57 | |
| 58 | // Read and update the sessions list |
| 59 | const sessionsListFile = getSessionsListPath(); |
| 60 | const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8"); |
| 61 | let sessionsList = |
| 62 | safeParseArray<BaseSessionMetadata>( |
| 63 | sessionsListRaw, |
| 64 | "Error parsing sessions.json", |
| 65 | ) ?? []; |
| 66 | |
| 67 | sessionsList = sessionsList.filter( |
| 68 | (session) => session.sessionId !== sessionId, |
| 69 | ); |
| 70 | |
| 71 | fs.writeFileSync( |
| 72 | sessionsListFile, |
| 73 | JSON.stringify(sessionsList, undefined, 2), |
| 74 | ); |
| 75 | } |
| 76 | |
| 77 | clearAll() { |
| 78 | fs.rmSync(getSessionsFolderPath(), { recursive: true, force: true }); |
| 79 | } |
| 80 | |
| 81 | load(sessionId: string): Session { |
| 82 | try { |
| 83 | const sessionFile = getSessionFilePath(sessionId); |
| 84 | if (!fs.existsSync(sessionFile)) { |
| 85 | throw new Error(`Session file ${sessionFile} does not exist`); |
| 86 | } |
| 87 | const session: Session = JSON.parse(fs.readFileSync(sessionFile, "utf8")); |
| 88 | session.sessionId = sessionId; |
| 89 | return session; |
| 90 | } catch (e) { |
| 91 | console.log(`Error loading session: ${e}`); |
| 92 | return { |
| 93 | history: [], |
| 94 | title: NEW_SESSION_TITLE, |
| 95 | workspaceDirectory: "", |
| 96 | sessionId: sessionId, |
| 97 | }; |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | save(session: Session) { |
| 102 | // Save the main session json file |
| 103 | // Explicitely rewriting here to influence the written key order in the file! |
| 104 | // e.g. id at the top, history next, etc. |
| 105 | const orderedSession: Session = { |
| 106 | sessionId: session.sessionId, |
| 107 | title: session.title, |
| 108 | workspaceDirectory: session.workspaceDirectory, |
| 109 | history: session.history, |
| 110 | }; |
| 111 | fs.writeFileSync( |
| 112 | getSessionFilePath(session.sessionId), |
| 113 | JSON.stringify(orderedSession, undefined, 2), |
| 114 | ); |
| 115 | |
| 116 | // Read and update the sessions list |
| 117 | const sessionsListFilePath = getSessionsListPath(); |
| 118 | try { |
| 119 | const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8"); |
| 120 | |
| 121 | let sessionsList: BaseSessionMetadata[]; |
| 122 | try { |
| 123 | sessionsList = JSON.parse(rawSessionsList); |
| 124 | } catch (e) { |
| 125 | if (rawSessionsList.trim() === "") { |
| 126 | fs.writeFileSync(sessionsListFilePath, JSON.stringify([])); |
| 127 | sessionsList = []; |
| 128 | } else { |
| 129 | throw e; |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | let found = false; |
| 134 | for (const sessionMetadata of sessionsList) { |
| 135 | if (sessionMetadata.sessionId === session.sessionId) { |
| 136 | sessionMetadata.title = session.title; |
| 137 | sessionMetadata.workspaceDirectory = session.workspaceDirectory; |
| 138 | found = true; |
| 139 | break; |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | if (!found) { |
| 144 | const sessionMetadata: BaseSessionMetadata = { |
| 145 | sessionId: session.sessionId, |
| 146 | title: session.title, |
| 147 | dateCreated: String(Date.now()), |
| 148 | workspaceDirectory: session.workspaceDirectory, |
| 149 | }; |
| 150 | sessionsList.push(sessionMetadata); |
| 151 | } |
| 152 | |
| 153 | fs.writeFileSync( |
| 154 | sessionsListFilePath, |
| 155 | JSON.stringify(sessionsList, undefined, 2), |
| 156 | ); |
| 157 | } catch (error) { |
| 158 | if (error instanceof SyntaxError) { |
| 159 | throw new Error( |
| 160 | `It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session.`, |
| 161 | ); |
| 162 | } |
| 163 | throw new Error( |
| 164 | `It looks like there is a validation error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session. Error: ${error}`, |
| 165 | ); |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | const historyManager = new HistoryManager(); |
| 171 | |
| 172 | export default historyManager; |