Elffuss BraidHub

kikocis/continue public

0a1f7aa3091d · 8.2 KiBRawPermalink
1import { Box, Text } from "ink";
2import React, { useMemo } from "react";
3
4import { useServices } from "../hooks/useService.js";
5import {
6 ApiClientServiceState,
7 AuthServiceState,
8 ConfigServiceState,
9 MCPServiceState,
10 ModelServiceState,
11} from "../services/types.js";
12
13import { BottomStatusBar } from "./components/BottomStatusBar.js";
14import { ScreenContent } from "./components/ScreenContent.js";
15import { StaticChatContent } from "./components/StaticChatContent.js";
16import { useNavigation } from "./context/NavigationContext.js";
17import { useChat } from "./hooks/useChat.js";
18import { useContextPercentage } from "./hooks/useContextPercentage.js";
19import { useMessageRenderer } from "./hooks/useMessageRenderer.js";
20import {
21 getRepoUrlText,
22 useCurrentMode,
23 useIntroMessage,
24 useLoginHandlers,
25 useSelectors,
26} from "./hooks/useTUIChatHooks.js";
27import { LoadingAnimation } from "./LoadingAnimation.js";
28import { Timer } from "./Timer.js";
29
30interface TUIChatProps {
31 // Remote mode props
32 remoteUrl?: string;
33
34 // Local mode props - now optional since we'll get them from services
35 configPath?: string;
36 initialPrompt?: string;
37 resume?: boolean;
38 additionalRules?: string[];
39}
40
41const TUIChat: React.FC<TUIChatProps> = ({
42 remoteUrl,
43 configPath,
44 initialPrompt,
45 resume,
46 additionalRules,
47}) => {
48 // Check if we're in remote mode
49 const isRemoteMode = useMemo(() => {
50 return !!remoteUrl;
51 }, [remoteUrl]);
52
53 const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [remoteUrl]);
54
55 // Get all services reactively - only in normal mode
56 const { services, allReady: allServicesReady } = useServices<{
57 auth: AuthServiceState;
58 config: ConfigServiceState;
59 model: ModelServiceState;
60 mcp: MCPServiceState;
61 apiClient: ApiClientServiceState;
62 }>(["auth", "config", "model", "mcp", "apiClient"]);
63
64 // Use navigation context
65 const {
66 state: navState,
67 navigateTo,
68 closeCurrentScreen,
69 isScreenActive,
70 } = useNavigation();
71
72 // Use intro message hook
73 const [showIntroMessage, setShowIntroMessage] = useIntroMessage(
74 isRemoteMode,
75 services,
76 allServicesReady,
77 );
78
79 // State for current mode (for hiding cwd in plan/auto modes)
80 const currentMode = useCurrentMode();
81
82 // Use login handlers
83 const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers(
84 navigateTo,
85 navState,
86 closeCurrentScreen,
87 );
88
89 // Service reload handlers - these will trigger reactive updates
90 const handleReload = async () => {
91 // Services will automatically update the UI when they reload
92 // We just need to reset chat history, intro message, and clear the screen
93 resetChatHistory();
94 setShowIntroMessage(false);
95 process.stdout.write("\x1b[2J\x1b[H");
96 };
97
98 const {
99 messages,
100 setMessages,
101 chatHistory,
102 setChatHistory,
103 isWaitingForResponse,
104 responseStartTime,
105 inputMode,
106 activePermissionRequest,
107 handleUserMessage,
108 handleInterrupt,
109 handleFileAttached,
110 resetChatHistory,
111 handleToolPermissionResponse,
112 } = useChat({
113 assistant: services.config?.config || undefined,
114 model: services.model?.model || undefined,
115 llmApi: services.model?.llmApi || undefined,
116 initialPrompt,
117 resume,
118 additionalRules,
119 onShowConfigSelector: () => navigateTo("config"),
120 onShowModelSelector: () => navigateTo("model"),
121 onShowMCPSelector: () => navigateTo("mcp"),
122 onShowSessionSelector: () => navigateTo("session"),
123 onLoginPrompt: handleLoginPrompt,
124 onReload: handleReload,
125 // Remote mode configuration
126 isRemoteMode,
127 remoteUrl,
128 });
129
130 // Calculate context percentage
131 const contextData = useContextPercentage({
132 chatHistory,
133 model: services.model?.model || undefined,
134 });
135
136 const { renderMessage } = useMessageRenderer();
137
138 const { handleConfigSelect, handleModelSelect } = useSelectors(
139 configPath,
140 setMessages,
141 resetChatHistory,
142 );
143
144 // Session selection handler
145 const handleSessionSelect = async (sessionId: string) => {
146 try {
147 // Close the session selector
148 closeCurrentScreen();
149
150 // Import session functions
151 const { loadSessionById } = await import("../session.js");
152
153 // Load the session history
154 const sessionHistory = loadSessionById(sessionId);
155 if (!sessionHistory) {
156 console.error(`Session ${sessionId} could not be loaded.`);
157 return;
158 }
159
160 // Set the session ID so future operations use this session
161 process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
162 "continue-cli-",
163 "",
164 );
165
166 // Directly set the chat history and messages to the loaded session
167 setChatHistory(sessionHistory);
168
169 // Convert chat history to display messages (exclude system messages)
170 const displayMessages = sessionHistory
171 .filter((msg) => msg.role !== "system")
172 .map((msg) => ({
173 role: msg.role,
174 content: msg.content as string,
175 }));
176
177 setMessages(displayMessages);
178
179 // Clear the intro message since we're now showing a resumed session
180 setShowIntroMessage(false);
181 } catch (error) {
182 console.error("Error loading session:", error);
183 }
184 };
185
186 // Determine if input should be disabled
187 // Allow input even when services are loading, but disable for UI overlays
188 const isInputDisabled =
189 navState.currentScreen !== "chat" || !!activePermissionRequest;
190
191 return (
192 <Box flexDirection="column" height="100%">
193 {/* Chat history - takes up all available space above input */}
194 <Box flexDirection="column" flexGrow={1} paddingX={1} overflow="hidden">
195 {/* Debug component - comment out when not needed */}
196 {/* {!isRemoteMode && (
197 <ServiceDebugger
198 services={services}
199 loading={servicesLoading}
200 error={servicesError}
201 allReady={allServicesReady}
202 servicesLoading={servicesLoading}
203 servicesError={servicesError}
204 />
205 )} */}
206
207 {/* Chat content with intro message and messages in static container */}
208 <StaticChatContent
209 showIntroMessage={showIntroMessage && !isRemoteMode}
210 config={services.config?.config || undefined}
211 model={services.model?.model || undefined}
212 mcpService={services.mcp?.mcpService || undefined}
213 messages={messages}
214 renderMessage={renderMessage}
215 />
216 </Box>
217
218 {/* Fixed bottom section */}
219 <Box flexDirection="column" flexShrink={0}>
220 {/* Status */}
221 {isWaitingForResponse && responseStartTime && (
222 <Box paddingX={1} flexDirection="row" gap={1}>
223 <LoadingAnimation visible={isWaitingForResponse} />
224 <Text key="loading-start" color="gray">
225 (
226 </Text>
227 <Timer startTime={responseStartTime} />
228 <Text key="loading-end" color="gray">
229 • esc to interrupt )
230 </Text>
231 </Box>
232 )}
233
234 {/* All screen-specific content */}
235 <ScreenContent
236 isScreenActive={isScreenActive}
237 navState={navState}
238 services={services}
239 handleLoginTokenSubmit={handleLoginTokenSubmit}
240 handleConfigSelect={handleConfigSelect}
241 handleModelSelect={handleModelSelect}
242 handleSessionSelect={handleSessionSelect}
243 handleReload={handleReload}
244 closeCurrentScreen={closeCurrentScreen}
245 activePermissionRequest={activePermissionRequest}
246 handleToolPermissionResponse={handleToolPermissionResponse}
247 handleUserMessage={handleUserMessage}
248 isWaitingForResponse={isWaitingForResponse}
249 inputMode={inputMode}
250 handleInterrupt={handleInterrupt}
251 handleFileAttached={handleFileAttached}
252 isInputDisabled={isInputDisabled}
253 isRemoteMode={isRemoteMode}
254 />
255
256 {/* Free trial status and Continue CLI info - always show */}
257 <BottomStatusBar
258 currentMode={currentMode}
259 repoURLText={repoURlText}
260 isRemoteMode={isRemoteMode}
261 services={services}
262 navState={navState}
263 navigateTo={navigateTo}
264 closeCurrentScreen={closeCurrentScreen}
265 contextPercentage={contextData?.percentage}
266 />
267 </Box>
268 </Box>
269 );
270};
271
272export { TUIChat };