Elffuss BraidHub

kikocis/continue public

2cf8097f3ed4 · 11.8 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
160export function getSessionPersistenceSnapshot(session: Session): Session {
161 return modifySessionBeforeSave(session);
162}
163
164/**
165 * Save the current session to file
166 */
167export function saveSession(): void {
168 try {
169 const session = SessionManager.getInstance().getCurrentSession();
170 const sessionToSave = getSessionPersistenceSnapshot(session);
171 historyManager.save(sessionToSave);
172 } catch (error) {
173 logger.error("Error saving session:", error);
174 }
175}
176
177/**
178 * Load session from current terminal's session file
179 */
180export function loadSession(): Session | null {
181 try {
182 // For resume, we need to find the most recent session
183 const sessionDir = getSessionDir();
184 if (!fs.existsSync(sessionDir)) {
185 return null;
186 }
187
188 const files = fs
189 .readdirSync(sessionDir)
190 .filter((f) => f.endsWith(".json") && f !== "sessions.json")
191 .map((f) => ({
192 name: f,
193 path: path.join(sessionDir, f),
194 mtime: fs.statSync(path.join(sessionDir, f)).mtime,
195 }))
196 .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
197
198 if (files.length === 0) {
199 return null;
200 }
201
202 // Load the most recent session
203 const session: Session = JSON.parse(fs.readFileSync(files[0].path, "utf8"));
204 // Set this as the current session for future saves
205 SessionManager.getInstance().setSession(session);
206 return session;
207 } catch (error) {
208 logger.error("Error loading session:", error);
209 return null;
210 }
211}
212
213/**
214 * Create a new session
215 */
216export function createSession(history: ChatHistoryItem[] = []): Session {
217 const session: Session = {
218 sessionId: uuidv4(),
219 title: DEFAULT_SESSION_TITLE,
220 workspaceDirectory: process.cwd(),
221 history,
222 };
223 SessionManager.getInstance().setSession(session);
224 return session;
225}
226
227/**
228 * Clear the current session
229 */
230export function clearSession(): void {
231 try {
232 const manager = SessionManager.getInstance();
233 if (manager.hasSession()) {
234 const sessionFilePath = path.join(
235 getSessionDir(),
236 `${manager.getSessionId()}.json`,
237 );
238 if (fs.existsSync(sessionFilePath)) {
239 fs.unlinkSync(sessionFilePath);
240 }
241 manager.clear();
242 }
243 } catch (error) {
244 logger.error("Error clearing session:", error);
245 }
246}
247
248/**
249 * Check if a session exists for the current terminal
250 */
251export function hasSession(): boolean {
252 const manager = SessionManager.getInstance();
253 if (!manager.hasSession()) {
254 return false;
255 }
256 const sessionFilePath = path.join(
257 getSessionDir(),
258 `${manager.getSessionId()}.json`,
259 );
260 return fs.existsSync(sessionFilePath);
261}
262
263/**
264 * Get metadata from a session file with first user message preview
265 */
266function getSessionMetadataWithPreview(
267 filePath: string,
268): ExtendedSessionMetadata | null {
269 try {
270 const sessionData: Session = JSON.parse(fs.readFileSync(filePath, "utf8"));
271 const stats = fs.statSync(filePath);
272
273 // Find the first user message for preview
274 let firstUserMessage: string | undefined;
275 for (const item of sessionData.history || []) {
276 if (item.message.role === "user") {
277 const content = item.message.content;
278 // Handle both string and array content types
279 if (typeof content === "string") {
280 firstUserMessage = content;
281 } else if (Array.isArray(content)) {
282 // For array content, find the first text part
283 const textPart = content.find((part) => part.type === "text");
284 firstUserMessage =
285 textPart && "text" in textPart
286 ? textPart.text
287 : "(multimodal message)";
288 } else {
289 firstUserMessage = "(unknown content type)";
290 }
291 break;
292 }
293 }
294
295 return {
296 sessionId: sessionData.sessionId,
297 title: sessionData.title || DEFAULT_SESSION_TITLE,
298 dateCreated: stats.birthtime.toISOString(),
299 workspaceDirectory: sessionData.workspaceDirectory || "",
300 firstUserMessage,
301 };
302 } catch (error) {
303 logger.error(`Error reading session file ${filePath}:`, error);
304 return null;
305 }
306}
307
308/**
309 * Fetch remote agents/sessions from the API
310 */
311export async function getRemoteSessions(): Promise<ExtendedSessionMetadata[]> {
312 try {
313 const authConfig = loadAuthConfig();
314 const accessToken = getAccessToken(authConfig);
315
316 if (
317 !accessToken ||
318 !isAuthenticatedConfig(authConfig) ||
319 !authConfig.userEmail.endsWith("@continue.dev")
320 ) {
321 return [];
322 }
323
324 const response = await fetch(new URL("agents", env.apiBase), {
325 method: "GET",
326 headers: {
327 "Content-Type": "application/json",
328 Authorization: `Bearer ${accessToken}`,
329 },
330 });
331
332 if (!response.ok) {
333 logger.error(`Failed to fetch remote agents: ${response.status}`);
334 return [];
335 }
336
337 const agents = await response.json();
338
339 return agents.map((agent: any) => ({
340 sessionId: `remote-${agent.id}`,
341 title: agent.name || "Remote Agent",
342 dateCreated: new Date(agent.create_time_ms).toISOString(),
343 workspaceDirectory: "",
344 isRemote: true,
345 remoteId: agent.id,
346 firstUserMessage: "Remote agent session",
347 }));
348 } catch (error) {
349 logger.error("Error fetching remote sessions:", error);
350 return [];
351 }
352}
353
354/**
355 * List all available sessions with metadata (both local and remote)
356 */
357export async function listSessions(
358 limit: number = 100,
359): Promise<ExtendedSessionMetadata[]> {
360 try {
361 // Get local sessions
362 const localSessions = historyManager.list({ limit });
363
364 // Add first user message preview to each local session
365 const localSessionsWithPreview: ExtendedSessionMetadata[] = [];
366
367 for (const sessionMeta of localSessions) {
368 const sessionFilePath = path.join(
369 getSessionDir(),
370 `${sessionMeta.sessionId}.json`,
371 );
372
373 if (fs.existsSync(sessionFilePath)) {
374 const metadata = getSessionMetadataWithPreview(sessionFilePath);
375 if (metadata) {
376 localSessionsWithPreview.push({
377 ...metadata,
378 isRemote: false,
379 });
380 }
381 } else {
382 // Fall back to basic metadata if file doesn't exist
383 localSessionsWithPreview.push({
384 ...sessionMeta,
385 isRemote: false,
386 });
387 }
388 }
389
390 // Get remote sessions
391 const remoteSessions = await getRemoteSessions();
392
393 // Combine and sort by date (most recent first)
394 const allSessions = [...localSessionsWithPreview, ...remoteSessions]
395 .sort(
396 (a, b) =>
397 new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(),
398 )
399 .slice(0, limit);
400
401 return allSessions;
402 } catch (error) {
403 logger.error("Error listing sessions:", error);
404 return [];
405 }
406}
407
408/**
409 * Load session by ID
410 */
411export function loadSessionById(sessionId: string): Session | null {
412 try {
413 const session = historyManager.load(sessionId);
414 return session;
415 } catch (error) {
416 logger.error("Error loading session by ID:", error);
417 return null;
418 }
419}
420
421/**
422 * Update the current session's history
423 */
424export function updateSessionHistory(history: ChatHistoryItem[]): void {
425 SessionManager.getInstance().updateHistory(history);
426}
427
428/**
429 * Update the current session's title
430 */
431export function updateSessionTitle(title: string): void {
432 SessionManager.getInstance().updateTitle(title);
433}
434
435/**
436 * Get the current session
437 */
438export function getCurrentSession(): Session {
439 return SessionManager.getInstance().getCurrentSession();
440}
441
442/**
443 * Start a new session with a new sessionId
444 */
445export function startNewSession(history: ChatHistoryItem[] = []): Session {
446 const manager = SessionManager.getInstance();
447
448 // Clear the current session from memory (don't delete the file)
449 manager.clear();
450
451 // Create a new session with a new sessionId
452 const newSession: Session = {
453 sessionId: uuidv4(),
454 title: DEFAULT_SESSION_TITLE,
455 workspaceDirectory: process.cwd(),
456 history,
457 };
458
459 manager.setSession(newSession);
460 return newSession;
461}