Elffuss BraidHub

kikocis/continue public

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