Elffuss BraidHub

kikocis/continue public

fb08fd5cc0fe · 4.0 KiBRawPermalink
1import { render } from "ink";
2import React from "react";
3
4import { getAccessToken, loadAuthConfig } from "../auth/workos.js";
5import { env } from "../env.js";
6import { listSessions, loadSessionById } from "../session.js";
7import { SessionSelector } from "../ui/SessionSelector.js";
8import { logger } from "../util/logger.js";
9
10import { chat } from "./chat.js";
11import { remote } from "./remote.js";
12
13interface ListSessionsOptions {
14 format?: "json";
15}
16
17/**
18 * Set a specific session ID for the current process
19 * This allows us to load a selected session as if it were the current session
20 */
21function setSessionId(sessionId: string): void {
22 // Use the same environment variable that getSessionId() checks
23 process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
24 "continue-cli-",
25 "",
26 );
27}
28
29export async function getTunnelForAgent(agentId: string): Promise<string> {
30 const authConfig = loadAuthConfig();
31 const accessToken = getAccessToken(authConfig);
32
33 const resp = await fetch(`${env.apiBase}agents/devboxes/${agentId}/tunnel`, {
34 method: "POST",
35 headers: {
36 "Content-Type": "application/json",
37 Authorization: `Bearer ${accessToken}`,
38 },
39 });
40 if (!resp.ok) {
41 throw new Error(
42 `Failed to get tunnel for agent ${agentId}: ${await resp.text()}`,
43 );
44 }
45 const data = await resp.json();
46 return data.url;
47}
48
49/**
50 * List recent chat sessions and allow selection
51 */
52export async function listSessionsCommand(
53 options: ListSessionsOptions = {},
54): Promise<void> {
55 // Handle JSON format output first
56 if (options.format === "json") {
57 const sessions = await listSessions();
58 console.log(
59 JSON.stringify(
60 {
61 sessions: sessions.map((session) => ({
62 id: session.sessionId,
63 timestamp: session.dateCreated,
64 workspaceDirectory: session.workspaceDirectory,
65 title: session.title,
66 firstUserMessage: session.firstUserMessage,
67 isRemote: session.isRemote,
68 remoteId: session.remoteId,
69 })),
70 },
71 null,
72 2,
73 ),
74 );
75 return;
76 }
77
78 // For TUI mode, fetch more sessions than we might display so the UI can choose based on screen height
79 const sessions = await listSessions();
80
81 // Handle empty sessions case
82 if (sessions.length === 0) {
83 console.log(
84 "No previous sessions found. Start a new conversation with: cn",
85 );
86 return;
87 }
88
89 // Start TUI selector
90 return new Promise<void>((resolve, reject) => {
91 const handleSelect = async (sessionId: string) => {
92 try {
93 app.unmount();
94
95 // Find the selected session to check if it's remote
96 const selectedSession = sessions.find((s) => s.sessionId === sessionId);
97
98 if (selectedSession?.isRemote && selectedSession.remoteId) {
99 // Handle remote session - use the remote command with the agent URL
100 logger.info(`Opening remote session: ${selectedSession.remoteId}`);
101
102 const tunnelUrl = await getTunnelForAgent(selectedSession.remoteId);
103
104 await remote(undefined, { url: tunnelUrl });
105 } else {
106 // Handle local session
107 const sessionHistory = loadSessionById(sessionId);
108 if (!sessionHistory) {
109 logger.error(`Session ${sessionId} could not be loaded.`);
110 resolve();
111 return;
112 }
113
114 logger.info(`Loading session: ${sessionId}`);
115
116 // Set the session ID so that when chat() runs, it will load this session
117 setSessionId(sessionId);
118
119 // Start chat with resume flag to load the selected session
120 await chat(undefined, {
121 resume: true,
122 headless: false,
123 });
124 }
125
126 resolve();
127 } catch (error) {
128 logger.error("Error loading session:", error);
129 reject(error);
130 }
131 };
132
133 const handleExit = () => {
134 app.unmount();
135 resolve();
136 };
137
138 const app = render(
139 React.createElement(SessionSelector, {
140 sessions,
141 onSelect: handleSelect,
142 onExit: handleExit,
143 }),
144 );
145 });
146}