Elffuss BraidHub

kikocis/continue public

8d9577e85559 · 11.7 KiBRawPermalink
1import fs from "fs";
2import os from "os";
3import path from "path";
4
5import type {
6 BaseSessionMetadata,
7 ChatHistoryItem,
8 Session,
9} from "core/index.js";
10import historyManager from "core/util/history.js";
11import { v4 as uuidv4 } from "uuid";
12
13import {
14 getAccessToken,
15 isAuthenticatedConfig,
16 loadAuthConfig,
17} from "./auth/workos.js";
18import { DEFAULT_SESSION_TITLE } from "./constants/session.js";
19import { env } from "./env.js";
20import { logger } from "./util/logger.js";
21
22// Re-export BaseSessionMetadata for external consumers
23export type { BaseSessionMetadata };
24
25// Extended type for sessions that can be local or remote
26export interface ExtendedSessionMetadata extends BaseSessionMetadata {
27 firstUserMessage?: string;
28 isRemote?: boolean;
29 remoteId?: string; // For remote sessions, this is the agent ID
30}
31
32// Note: We now use UUID-based session IDs instead of terminal-based IDs.
33// Each new chat session gets a unique UUID.
34// The --resume flag loads the most recent session.
35
36/**
37 * Get the session storage directory
38 */
39function getSessionDir(): string {
40 // For tests, use the test directory if we're in test mode
41 if (process.env.CONTINUE_CLI_TEST && process.env.HOME) {
42 const sessionDir = path.join(process.env.HOME, ".continue", "sessions");
43
44 // Create directory if it doesn't exist
45 if (!fs.existsSync(sessionDir)) {
46 fs.mkdirSync(sessionDir, { recursive: true });
47 }
48
49 return sessionDir;
50 }
51
52 // Use CONTINUE_GLOBAL_DIR if set (for testing)
53 const continueHome =
54 process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue");
55 const sessionDir = path.join(continueHome, "sessions");
56
57 // Create directory if it doesn't exist
58 if (!fs.existsSync(sessionDir)) {
59 fs.mkdirSync(sessionDir, { recursive: true });
60 }
61
62 return sessionDir;
63}
64
65/**
66 * Get the session file path for the current session
67 */
68export function getSessionFilePath(): string {
69 const sessionId = getCurrentSessionId();
70 const sessionDir = getSessionDir();
71 return path.join(sessionDir, `${sessionId}.json`);
72}
73
74// Singleton for current session management
75class SessionManager {
76 private static instance: SessionManager;
77 private currentSession: Session | null = null;
78
79 private constructor() {}
80
81 static getInstance(): SessionManager {
82 if (!SessionManager.instance) {
83 SessionManager.instance = new SessionManager();
84 }
85 return SessionManager.instance;
86 }
87
88 getCurrentSession(): Session {
89 if (!this.currentSession) {
90 // Use test session ID for testing consistency
91 const sessionId = process.env.CONTINUE_CLI_TEST_SESSION_ID
92 ? process.env.CONTINUE_CLI_TEST_SESSION_ID
93 : uuidv4();
94
95 this.currentSession = {
96 sessionId,
97 title: DEFAULT_SESSION_TITLE,
98 workspaceDirectory: process.cwd(),
99 history: [],
100 };
101 }
102 return this.currentSession;
103 }
104
105 setSession(session: Session): void {
106 this.currentSession = session;
107 }
108
109 updateHistory(history: ChatHistoryItem[]): void {
110 const session = this.getCurrentSession();
111 session.history = history;
112 saveSession();
113 }
114
115 updateTitle(title: string): void {
116 const session = this.getCurrentSession();
117 session.title = title;
118 saveSession();
119 }
120
121 clear(): void {
122 this.currentSession = null;
123 }
124
125 hasSession(): boolean {
126 return this.currentSession !== null;
127 }
128
129 getSessionId(): string {
130 return this.getCurrentSession().sessionId;
131 }
132}
133
134function getCurrentSessionId(): string {
135 return SessionManager.getInstance().getSessionId();
136}
137
138function modifySessionBeforeSave(session: Session): Session {
139 const filteredHistory = session.history.filter((item) => {
140 return item.message.role !== "system";
141 });
142
143 const modifiedHistory = filteredHistory.map((item) => {
144 if (item.message.role === "user") {
145 return {
146 ...item,
147 editorState: item.message.content,
148 };
149 }
150
151 return item;
152 });
153
154 return {
155 ...session,
156 history: modifiedHistory,
157 };
158}
159
160/**
161 * Save the current session to file
162 */
163export function saveSession(): void {
164 try {
165 const session = SessionManager.getInstance().getCurrentSession();
166 const sessionToSave = modifySessionBeforeSave(session);
167 historyManager.save(sessionToSave);
168 } catch (error) {
169 logger.error("Error saving session:", error);
170 }
171}
172
173/**
174 * Load session from current terminal's session file
175 */
176export function loadSession(): Session | null {
177 try {
178 // For resume, we need to find the most recent session
179 const sessionDir = getSessionDir();
180 if (!fs.existsSync(sessionDir)) {
181 return null;
182 }
183
184 const files = fs
185 .readdirSync(sessionDir)
186 .filter((f) => f.endsWith(".json") && f !== "sessions.json")
187 .map((f) => ({
188 name: f,
189 path: path.join(sessionDir, f),
190 mtime: fs.statSync(path.join(sessionDir, f)).mtime,
191 }))
192 .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
193
194 if (files.length === 0) {
195 return null;
196 }
197
198 // Load the most recent session
199 const session: Session = JSON.parse(fs.readFileSync(files[0].path, "utf8"));
200 // Set this as the current session for future saves
201 SessionManager.getInstance().setSession(session);
202 return session;
203 } catch (error) {
204 logger.error("Error loading session:", error);
205 return null;
206 }
207}
208
209/**
210 * Create a new session
211 */
212export function createSession(history: ChatHistoryItem[] = []): Session {
213 const session: Session = {
214 sessionId: uuidv4(),
215 title: DEFAULT_SESSION_TITLE,
216 workspaceDirectory: process.cwd(),
217 history,
218 };
219 SessionManager.getInstance().setSession(session);
220 return session;
221}
222
223/**
224 * Clear the current session
225 */
226export function clearSession(): void {
227 try {
228 const manager = SessionManager.getInstance();
229 if (manager.hasSession()) {
230 const sessionFilePath = path.join(
231 getSessionDir(),
232 `${manager.getSessionId()}.json`,
233 );
234 if (fs.existsSync(sessionFilePath)) {
235 fs.unlinkSync(sessionFilePath);
236 }
237 manager.clear();
238 }
239 } catch (error) {
240 logger.error("Error clearing session:", error);
241 }
242}
243
244/**
245 * Check if a session exists for the current terminal
246 */
247export function hasSession(): boolean {
248 const manager = SessionManager.getInstance();
249 if (!manager.hasSession()) {
250 return false;
251 }
252 const sessionFilePath = path.join(
253 getSessionDir(),
254 `${manager.getSessionId()}.json`,
255 );
256 return fs.existsSync(sessionFilePath);
257}
258
259/**
260 * Get metadata from a session file with first user message preview
261 */
262function getSessionMetadataWithPreview(
263 filePath: string,
264): ExtendedSessionMetadata | null {
265 try {
266 const sessionData: Session = JSON.parse(fs.readFileSync(filePath, "utf8"));
267 const stats = fs.statSync(filePath);
268
269 // Find the first user message for preview
270 let firstUserMessage: string | undefined;
271 for (const item of sessionData.history || []) {
272 if (item.message.role === "user") {
273 const content = item.message.content;
274 // Handle both string and array content types
275 if (typeof content === "string") {
276 firstUserMessage = content;
277 } else if (Array.isArray(content)) {
278 // For array content, find the first text part
279 const textPart = content.find((part) => part.type === "text");
280 firstUserMessage =
281 textPart && "text" in textPart
282 ? textPart.text
283 : "(multimodal message)";
284 } else {
285 firstUserMessage = "(unknown content type)";
286 }
287 break;
288 }
289 }
290
291 return {
292 sessionId: sessionData.sessionId,
293 title: sessionData.title || DEFAULT_SESSION_TITLE,
294 dateCreated: stats.birthtime.toISOString(),
295 workspaceDirectory: sessionData.workspaceDirectory || "",
296 firstUserMessage,
297 };
298 } catch (error) {
299 logger.error(`Error reading session file ${filePath}:`, error);
300 return null;
301 }
302}
303
304/**
305 * Fetch remote agents/sessions from the API
306 */
307export async function getRemoteSessions(): Promise<ExtendedSessionMetadata[]> {
308 try {
309 const authConfig = loadAuthConfig();
310 const accessToken = getAccessToken(authConfig);
311
312 if (
313 !accessToken ||
314 !isAuthenticatedConfig(authConfig) ||
315 !authConfig.userEmail.endsWith("@continue.dev")
316 ) {
317 return [];
318 }
319
320 const response = await fetch(new URL("agents/devboxes", env.apiBase), {
321 method: "GET",
322 headers: {
323 "Content-Type": "application/json",
324 Authorization: `Bearer ${accessToken}`,
325 },
326 });
327
328 if (!response.ok) {
329 logger.error(`Failed to fetch remote agents: ${response.status}`);
330 return [];
331 }
332
333 const agents = await response.json();
334
335 return agents.map((agent: any) => ({
336 sessionId: `remote-${agent.id}`,
337 title: agent.name || "Remote Agent",
338 dateCreated: new Date(agent.create_time_ms).toISOString(),
339 workspaceDirectory: "",
340 isRemote: true,
341 remoteId: agent.id,
342 firstUserMessage: "Remote agent session",
343 }));
344 } catch (error) {
345 logger.error("Error fetching remote sessions:", error);
346 return [];
347 }
348}
349
350/**
351 * List all available sessions with metadata (both local and remote)
352 */
353export async function listSessions(
354 limit: number = 100,
355): Promise<ExtendedSessionMetadata[]> {
356 try {
357 // Get local sessions
358 const localSessions = historyManager.list({ limit });
359
360 // Add first user message preview to each local session
361 const localSessionsWithPreview: ExtendedSessionMetadata[] = [];
362
363 for (const sessionMeta of localSessions) {
364 const sessionFilePath = path.join(
365 getSessionDir(),
366 `${sessionMeta.sessionId}.json`,
367 );
368
369 if (fs.existsSync(sessionFilePath)) {
370 const metadata = getSessionMetadataWithPreview(sessionFilePath);
371 if (metadata) {
372 localSessionsWithPreview.push({
373 ...metadata,
374 isRemote: false,
375 });
376 }
377 } else {
378 // Fall back to basic metadata if file doesn't exist
379 localSessionsWithPreview.push({
380 ...sessionMeta,
381 isRemote: false,
382 });
383 }
384 }
385
386 // Get remote sessions
387 const remoteSessions = await getRemoteSessions();
388
389 // Combine and sort by date (most recent first)
390 const allSessions = [...localSessionsWithPreview, ...remoteSessions]
391 .sort(
392 (a, b) =>
393 new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(),
394 )
395 .slice(0, limit);
396
397 return allSessions;
398 } catch (error) {
399 logger.error("Error listing sessions:", error);
400 return [];
401 }
402}
403
404/**
405 * Load session by ID
406 */
407export function loadSessionById(sessionId: string): Session | null {
408 try {
409 const session = historyManager.load(sessionId);
410 return session;
411 } catch (error) {
412 logger.error("Error loading session by ID:", error);
413 return null;
414 }
415}
416
417/**
418 * Update the current session's history
419 */
420export function updateSessionHistory(history: ChatHistoryItem[]): void {
421 SessionManager.getInstance().updateHistory(history);
422}
423
424/**
425 * Update the current session's title
426 */
427export function updateSessionTitle(title: string): void {
428 SessionManager.getInstance().updateTitle(title);
429}
430
431/**
432 * Get the current session
433 */
434export function getCurrentSession(): Session {
435 return SessionManager.getInstance().getCurrentSession();
436}
437
438/**
439 * Start a new session with a new sessionId
440 */
441export function startNewSession(history: ChatHistoryItem[] = []): Session {
442 const manager = SessionManager.getInstance();
443
444 // Clear the current session from memory (don't delete the file)
445 manager.clear();
446
447 // Create a new session with a new sessionId
448 const newSession: Session = {
449 sessionId: uuidv4(),
450 title: DEFAULT_SESSION_TITLE,
451 workspaceDirectory: process.cwd(),
452 history,
453 };
454
455 manager.setSession(newSession);
456 return newSession;
457}