Elffuss BraidHub

kikocis/continue public

06370262b995 · 8.8 KiBRawPermalink
1import fs from "fs";
2import os from "os";
3import path from "path";
4
5import type { ChatHistoryItem, Session, SessionMetadata } from "core/index.js";
6import historyManager from "core/util/history.js";
7import { v4 as uuidv4 } from "uuid";
8
9// Re-export SessionMetadata for external consumers
10export type { SessionMetadata };
11
12import { logger } from "./util/logger.js";
13
14// Note: We now use UUID-based session IDs instead of terminal-based IDs.
15// Each new chat session gets a unique UUID.
16// The --resume flag loads the most recent session.
17
18/**
19 * Get the session storage directory
20 */
21function getSessionDir(): string {
22 // For tests, use the test directory if we're in test mode
23 if (process.env.CONTINUE_CLI_TEST && process.env.HOME) {
24 const sessionDir = path.join(process.env.HOME, ".continue", "sessions");
25
26 // Create directory if it doesn't exist
27 if (!fs.existsSync(sessionDir)) {
28 fs.mkdirSync(sessionDir, { recursive: true });
29 }
30
31 return sessionDir;
32 }
33
34 const homeDir = os.homedir();
35 const sessionDir = path.join(homeDir, ".continue", "sessions");
36
37 // Create directory if it doesn't exist
38 if (!fs.existsSync(sessionDir)) {
39 fs.mkdirSync(sessionDir, { recursive: true });
40 }
41
42 return sessionDir;
43}
44
45/**
46 * Get the session file path for the current session
47 */
48export function getSessionFilePath(): string {
49 const sessionId = getCurrentSessionId();
50 const sessionDir = getSessionDir();
51 return path.join(sessionDir, `${sessionId}.json`);
52}
53
54// Singleton for current session management
55class SessionManager {
56 private static instance: SessionManager;
57 private currentSession: Session | null = null;
58
59 private constructor() {}
60
61 static getInstance(): SessionManager {
62 if (!SessionManager.instance) {
63 SessionManager.instance = new SessionManager();
64 }
65 return SessionManager.instance;
66 }
67
68 getCurrentSession(): Session {
69 if (!this.currentSession) {
70 this.currentSession = {
71 sessionId: uuidv4(),
72 title: "Untitled Session",
73 workspaceDirectory: process.cwd(),
74 history: [],
75 };
76 }
77 return this.currentSession;
78 }
79
80 setSession(session: Session): void {
81 this.currentSession = session;
82 }
83
84 updateHistory(history: ChatHistoryItem[]): void {
85 const session = this.getCurrentSession();
86 session.history = history;
87 saveSession();
88 }
89
90 updateTitle(title: string): void {
91 const session = this.getCurrentSession();
92 session.title = title;
93 saveSession();
94 }
95
96 clear(): void {
97 this.currentSession = null;
98 }
99
100 hasSession(): boolean {
101 return this.currentSession !== null;
102 }
103
104 getSessionId(): string {
105 return this.getCurrentSession().sessionId;
106 }
107}
108
109function getCurrentSessionId(): string {
110 return SessionManager.getInstance().getSessionId();
111}
112
113function modifySessionBeforeSave(session: Session): Session {
114 const filteredHistory = session.history.filter((item) => {
115 return item.message.role !== "system";
116 });
117
118 const modifiedHistory = filteredHistory.map((item) => {
119 if (item.message.role === "user") {
120 return {
121 ...item,
122 editorState: item.message.content,
123 };
124 }
125
126 return item;
127 });
128
129 return {
130 ...session,
131 history: modifiedHistory,
132 };
133}
134
135/**
136 * Save the current session to file
137 */
138export function saveSession(): void {
139 try {
140 const session = SessionManager.getInstance().getCurrentSession();
141 const sessionToSave = modifySessionBeforeSave(session);
142 historyManager.save(sessionToSave);
143 } catch (error) {
144 logger.error("Error saving session:", error);
145 }
146}
147
148/**
149 * Load session from current terminal's session file
150 */
151export function loadSession(): Session | null {
152 try {
153 // For resume, we need to find the most recent session
154 const sessionDir = getSessionDir();
155 if (!fs.existsSync(sessionDir)) {
156 return null;
157 }
158
159 const files = fs
160 .readdirSync(sessionDir)
161 .filter((f) => f.endsWith(".json") && f !== "sessions.json")
162 .map((f) => ({
163 name: f,
164 path: path.join(sessionDir, f),
165 mtime: fs.statSync(path.join(sessionDir, f)).mtime,
166 }))
167 .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
168
169 if (files.length === 0) {
170 return null;
171 }
172
173 // Load the most recent session
174 const session: Session = JSON.parse(fs.readFileSync(files[0].path, "utf8"));
175 // Set this as the current session for future saves
176 SessionManager.getInstance().setSession(session);
177 return session;
178 } catch (error) {
179 logger.error("Error loading session:", error);
180 return null;
181 }
182}
183
184/**
185 * Create a new session
186 */
187export function createSession(history: ChatHistoryItem[] = []): Session {
188 const session: Session = {
189 sessionId: uuidv4(),
190 title: "Untitled Session",
191 workspaceDirectory: process.cwd(),
192 history,
193 };
194 SessionManager.getInstance().setSession(session);
195 return session;
196}
197
198/**
199 * Clear the current session
200 */
201export function clearSession(): void {
202 try {
203 const manager = SessionManager.getInstance();
204 if (manager.hasSession()) {
205 const sessionFilePath = path.join(
206 getSessionDir(),
207 `${manager.getSessionId()}.json`,
208 );
209 if (fs.existsSync(sessionFilePath)) {
210 fs.unlinkSync(sessionFilePath);
211 }
212 manager.clear();
213 }
214 } catch (error) {
215 logger.error("Error clearing session:", error);
216 }
217}
218
219/**
220 * Check if a session exists for the current terminal
221 */
222export function hasSession(): boolean {
223 const manager = SessionManager.getInstance();
224 if (!manager.hasSession()) {
225 return false;
226 }
227 const sessionFilePath = path.join(
228 getSessionDir(),
229 `${manager.getSessionId()}.json`,
230 );
231 return fs.existsSync(sessionFilePath);
232}
233
234/**
235 * Get metadata from a session file with first user message preview
236 */
237function getSessionMetadataWithPreview(
238 filePath: string,
239): (SessionMetadata & { firstUserMessage?: string }) | null {
240 try {
241 const sessionData: Session = JSON.parse(fs.readFileSync(filePath, "utf8"));
242 const stats = fs.statSync(filePath);
243
244 // Find the first user message for preview
245 let firstUserMessage: string | undefined;
246 for (const item of sessionData.history || []) {
247 if (item.message.role === "user") {
248 const content = item.message.content;
249 // Handle both string and array content types
250 if (typeof content === "string") {
251 firstUserMessage = content;
252 } else if (Array.isArray(content)) {
253 // For array content, find the first text part
254 const textPart = content.find((part) => part.type === "text");
255 firstUserMessage =
256 textPart && "text" in textPart
257 ? textPart.text
258 : "(multimodal message)";
259 } else {
260 firstUserMessage = "(unknown content type)";
261 }
262 break;
263 }
264 }
265
266 return {
267 sessionId: sessionData.sessionId,
268 title: sessionData.title || "Untitled Session",
269 dateCreated: stats.birthtime.toISOString(),
270 workspaceDirectory: sessionData.workspaceDirectory || "",
271 firstUserMessage,
272 };
273 } catch (error) {
274 logger.error(`Error reading session file ${filePath}:`, error);
275 return null;
276 }
277}
278
279/**
280 * List all available sessions with metadata
281 */
282export function listSessions(
283 limit: number = 10,
284): (SessionMetadata & { firstUserMessage?: string })[] {
285 try {
286 const sessions = historyManager.list({ limit });
287
288 // Add first user message preview to each session
289 const sessionsWithPreview: (SessionMetadata & {
290 firstUserMessage?: string;
291 })[] = [];
292
293 for (const sessionMeta of sessions) {
294 const sessionFilePath = path.join(
295 getSessionDir(),
296 `${sessionMeta.sessionId}.json`,
297 );
298
299 if (fs.existsSync(sessionFilePath)) {
300 const metadata = getSessionMetadataWithPreview(sessionFilePath);
301 if (metadata) {
302 sessionsWithPreview.push(metadata);
303 }
304 } else {
305 // Fall back to basic metadata if file doesn't exist
306 sessionsWithPreview.push(sessionMeta);
307 }
308 }
309
310 return sessionsWithPreview;
311 } catch (error) {
312 logger.error("Error listing sessions:", error);
313 return [];
314 }
315}
316
317/**
318 * Load session by ID
319 */
320export function loadSessionById(sessionId: string): Session | null {
321 try {
322 const session = historyManager.load(sessionId);
323 return session;
324 } catch (error) {
325 logger.error("Error loading session by ID:", error);
326 return null;
327 }
328}
329
330/**
331 * Update the current session's history
332 */
333export function updateSessionHistory(history: ChatHistoryItem[]): void {
334 SessionManager.getInstance().updateHistory(history);
335}
336
337/**
338 * Update the current session's title
339 */
340export function updateSessionTitle(title: string): void {
341 SessionManager.getInstance().updateTitle(title);
342}
343
344/**
345 * Get the current session
346 */
347export function getCurrentSession(): Session {
348 return SessionManager.getInstance().getCurrentSession();
349}