Elffuss BraidHub

kikocis/continue public

494a780fdb25 · 2.8 KiBRawPermalink
1import { render } from "ink";
2import React from "react";
3
4import { loadSessionById, listSessions } from "../session.js";
5import { SessionSelector } from "../ui/SessionSelector.js";
6import { logger } from "../util/logger.js";
7
8import { chat } from "./chat.js";
9
10interface ListSessionsOptions {
11 format?: "json";
12}
13
14/**
15 * Set a specific session ID for the current process
16 * This allows us to load a selected session as if it were the current session
17 */
18function setSessionId(sessionId: string): void {
19 // Use the same environment variable that getSessionId() checks
20 process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
21 "continue-cli-",
22 "",
23 );
24}
25
26/**
27 * List recent chat sessions and allow selection
28 */
29export async function listSessionsCommand(
30 options: ListSessionsOptions = {},
31): Promise<void> {
32 // Fetch more sessions than we might display so the UI can choose based on screen height
33 // But still limit for JSON output to keep it reasonable
34 const sessions = listSessions(options.format === "json" ? 10 : 20);
35
36 // Handle JSON format output
37 if (options.format === "json") {
38 console.log(
39 JSON.stringify(
40 {
41 sessions: sessions.map((session) => ({
42 id: session.id,
43 timestamp: session.timestamp.toISOString(),
44 messageCount: session.messageCount,
45 firstUserMessage: session.firstUserMessage,
46 })),
47 },
48 null,
49 2,
50 ),
51 );
52 return;
53 }
54
55 // Handle empty sessions case
56 if (sessions.length === 0) {
57 console.log(
58 "No previous sessions found. Start a new conversation with: cn",
59 );
60 return;
61 }
62
63 // Start TUI selector
64 return new Promise<void>((resolve, reject) => {
65 const handleSelect = async (sessionId: string) => {
66 try {
67 app.unmount();
68
69 // Verify the session exists before trying to load it
70 const sessionHistory = loadSessionById(sessionId);
71 if (!sessionHistory) {
72 console.error(`Session ${sessionId} could not be loaded.`);
73 resolve();
74 return;
75 }
76
77 logger.info(`Loading session: ${sessionId}`);
78
79 // Set the session ID so that when chat() runs, it will load this session
80 setSessionId(sessionId);
81
82 // Start chat with resume flag to load the selected session
83 await chat(undefined, {
84 resume: true,
85 headless: false,
86 });
87
88 resolve();
89 } catch (error) {
90 logger.error("Error loading session:", error);
91 reject(error);
92 }
93 };
94
95 const handleExit = () => {
96 app.unmount();
97 resolve();
98 };
99
100 const app = render(
101 React.createElement(SessionSelector, {
102 sessions,
103 onSelect: handleSelect,
104 onExit: handleExit,
105 }),
106 );
107 });
108}