Elffuss BraidHub

kikocis/continue public

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