Elffuss BraidHub

kikocis/continue public

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