| 1 | import { Box, Text } from "ink"; |
| 2 | import React, { |
| 3 | useCallback, |
| 4 | useEffect, |
| 5 | useMemo, |
| 6 | useRef, |
| 7 | useState, |
| 8 | } from "react"; |
| 9 | |
| 10 | import { useServices } from "../hooks/useService.js"; |
| 11 | import { |
| 12 | ApiClientServiceState, |
| 13 | AuthServiceState, |
| 14 | ConfigServiceState, |
| 15 | MCPServiceState, |
| 16 | ModelServiceState, |
| 17 | UpdateServiceState, |
| 18 | } from "../services/types.js"; |
| 19 | import { logger } from "../util/logger.js"; |
| 20 | |
| 21 | import { ActionStatus } from "./components/ActionStatus.js"; |
| 22 | import { BottomStatusBar } from "./components/BottomStatusBar.js"; |
| 23 | import { ResourceDebugBar } from "./components/ResourceDebugBar.js"; |
| 24 | import { ScreenContent } from "./components/ScreenContent.js"; |
| 25 | import { StaticChatContent } from "./components/StaticChatContent.js"; |
| 26 | import { useNavigation } from "./context/NavigationContext.js"; |
| 27 | import { useChat } from "./hooks/useChat.js"; |
| 28 | import { useContextPercentage } from "./hooks/useContextPercentage.js"; |
| 29 | import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; |
| 30 | import { |
| 31 | useCurrentMode, |
| 32 | useIntroMessage, |
| 33 | useLoginHandlers, |
| 34 | useSelectors, |
| 35 | } from "./hooks/useTUIChatHooks.js"; |
| 36 | |
| 37 | interface TUIChatProps { |
| 38 | // Remote mode props |
| 39 | remoteUrl?: string; |
| 40 | |
| 41 | // Local mode props - now optional since we'll get them from services |
| 42 | configPath?: string; |
| 43 | initialPrompt?: string; |
| 44 | resume?: boolean; |
| 45 | fork?: string; |
| 46 | additionalRules?: string[]; |
| 47 | additionalPrompts?: string[]; |
| 48 | } |
| 49 | |
| 50 | // Helper function to load and set session |
| 51 | async function loadAndSetSession( |
| 52 | sessionId: string, |
| 53 | closeCurrentScreen: () => void, |
| 54 | setChatHistory: (history: any) => void, |
| 55 | setShowIntroMessage: (show: boolean) => void, |
| 56 | ) { |
| 57 | try { |
| 58 | // Close the session selector |
| 59 | closeCurrentScreen(); |
| 60 | |
| 61 | // Import session functions |
| 62 | const { loadSessionById } = await import("../session.js"); |
| 63 | |
| 64 | // Load the session |
| 65 | const session = loadSessionById(sessionId); |
| 66 | if (!session) { |
| 67 | logger.error(`Session ${sessionId} could not be loaded.`); |
| 68 | return; |
| 69 | } |
| 70 | |
| 71 | // Set the session ID so future operations use this session |
| 72 | process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace( |
| 73 | "continue-cli-", |
| 74 | "", |
| 75 | ); |
| 76 | |
| 77 | // Set the chat history from the session |
| 78 | setChatHistory(session.history); |
| 79 | |
| 80 | // Clear the intro message since we're now showing a resumed session |
| 81 | setShowIntroMessage(false); |
| 82 | } catch (error) { |
| 83 | console.error("Error loading session:", error); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | // Custom hook to manage services |
| 88 | function useTUIChatServices(remoteUrl?: string) { |
| 89 | const isRemoteMode = useMemo(() => !!remoteUrl, [remoteUrl]); |
| 90 | |
| 91 | const { services, allReady: allServicesReady } = useServices<{ |
| 92 | auth: AuthServiceState; |
| 93 | config: ConfigServiceState; |
| 94 | model: ModelServiceState; |
| 95 | mcp: MCPServiceState; |
| 96 | apiClient: ApiClientServiceState; |
| 97 | update: UpdateServiceState; |
| 98 | }>(["auth", "config", "model", "mcp", "apiClient", "update"]); |
| 99 | |
| 100 | return { services, allServicesReady, isRemoteMode }; |
| 101 | } |
| 102 | |
| 103 | // Custom hook for chat handlers |
| 104 | function useChatHandlers( |
| 105 | setShowIntroMessage: (show: boolean) => void, |
| 106 | setStaticRefreshTrigger: React.Dispatch<React.SetStateAction<number>>, |
| 107 | ) { |
| 108 | // Temporary refs to avoid circular dependency |
| 109 | const resetChatHistoryRef = useRef<(() => void) | null>(null); |
| 110 | |
| 111 | // Handle clearing chat and resetting intro message |
| 112 | const handleClear = useCallback(() => { |
| 113 | setShowIntroMessage(true); |
| 114 | // Trigger static content refresh by incrementing the trigger |
| 115 | setStaticRefreshTrigger((prev) => prev + 1); |
| 116 | }, [setShowIntroMessage, setStaticRefreshTrigger]); |
| 117 | |
| 118 | // Service reload handlers - these will trigger reactive updates |
| 119 | const handleReload = useCallback(async () => { |
| 120 | // Services will automatically update the UI when they reload |
| 121 | // We just need to reset chat history, intro message, and clear the screen |
| 122 | if (resetChatHistoryRef.current) { |
| 123 | resetChatHistoryRef.current(); |
| 124 | } |
| 125 | setShowIntroMessage(false); |
| 126 | process.stdout.write("\x1b[2J\x1b[H"); |
| 127 | }, [setShowIntroMessage]); |
| 128 | |
| 129 | return { |
| 130 | handleClear, |
| 131 | handleReload, |
| 132 | resetChatHistoryRef, |
| 133 | }; |
| 134 | } |
| 135 | |
| 136 | // eslint-disable-next-line complexity |
| 137 | const TUIChat: React.FC<TUIChatProps> = ({ |
| 138 | remoteUrl, |
| 139 | configPath, |
| 140 | initialPrompt, |
| 141 | resume, |
| 142 | fork, |
| 143 | additionalRules, |
| 144 | additionalPrompts, |
| 145 | }) => { |
| 146 | // Use custom hook for services |
| 147 | const { services, allServicesReady, isRemoteMode } = |
| 148 | useTUIChatServices(remoteUrl); |
| 149 | |
| 150 | // Use navigation context |
| 151 | const { |
| 152 | state: navState, |
| 153 | navigateTo, |
| 154 | closeCurrentScreen, |
| 155 | isScreenActive, |
| 156 | } = useNavigation(); |
| 157 | |
| 158 | // Use intro message hook |
| 159 | const [showIntroMessage, setShowIntroMessage] = useIntroMessage( |
| 160 | isRemoteMode, |
| 161 | services, |
| 162 | allServicesReady, |
| 163 | ); |
| 164 | |
| 165 | // State for current mode (for hiding cwd in plan/auto modes) |
| 166 | const currentMode = useCurrentMode(); |
| 167 | |
| 168 | // Use login handlers |
| 169 | const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers( |
| 170 | navigateTo, |
| 171 | navState, |
| 172 | closeCurrentScreen, |
| 173 | ); |
| 174 | |
| 175 | // State to trigger static content refresh for /clear command |
| 176 | const [staticRefreshTrigger, setStaticRefreshTrigger] = useState(0); |
| 177 | |
| 178 | // Use chat handlers hook |
| 179 | const { handleClear, handleReload, resetChatHistoryRef } = useChatHandlers( |
| 180 | setShowIntroMessage, |
| 181 | setStaticRefreshTrigger, |
| 182 | ); |
| 183 | |
| 184 | // State for diff content overlay |
| 185 | const [diffContent, setDiffContent] = useState<string>(""); |
| 186 | |
| 187 | // State for temporary status message |
| 188 | const [statusMessage, setStatusMessage] = useState<string>(""); |
| 189 | |
| 190 | // Handler to show diff overlay |
| 191 | const handleShowDiff = useCallback( |
| 192 | (content: string) => { |
| 193 | setDiffContent(content); |
| 194 | navigateTo("diff"); |
| 195 | }, |
| 196 | [navigateTo], |
| 197 | ); |
| 198 | |
| 199 | // Handler to show temporary status message |
| 200 | const handleShowStatusMessage = useCallback((message: string) => { |
| 201 | setStatusMessage(message); |
| 202 | // Clear after 3 seconds |
| 203 | setTimeout(() => { |
| 204 | setStatusMessage(""); |
| 205 | }, 3000); |
| 206 | }, []); |
| 207 | |
| 208 | const { |
| 209 | chatHistory, |
| 210 | setChatHistory, |
| 211 | isWaitingForResponse, |
| 212 | responseStartTime, |
| 213 | isCompacting, |
| 214 | compactionStartTime, |
| 215 | inputMode, |
| 216 | activePermissionRequest, |
| 217 | wasInterrupted, |
| 218 | queuedMessages, |
| 219 | handleUserMessage, |
| 220 | handleInterrupt, |
| 221 | handleFileAttached, |
| 222 | resetChatHistory, |
| 223 | handleToolPermissionResponse, |
| 224 | } = useChat({ |
| 225 | assistant: services.config?.config || undefined, |
| 226 | model: services.model?.model || undefined, |
| 227 | llmApi: services.model?.llmApi || undefined, |
| 228 | initialPrompt, |
| 229 | resume, |
| 230 | fork, |
| 231 | additionalRules, |
| 232 | additionalPrompts, |
| 233 | onShowConfigSelector: () => navigateTo("config"), |
| 234 | onShowModelSelector: () => navigateTo("model"), |
| 235 | onShowMCPSelector: () => navigateTo("mcp"), |
| 236 | onShowUpdateSelector: () => navigateTo("update"), |
| 237 | onShowSessionSelector: () => navigateTo("session"), |
| 238 | onLoginPrompt: handleLoginPrompt, |
| 239 | onReload: handleReload, |
| 240 | onClear: handleClear, |
| 241 | // Remote mode configuration |
| 242 | isRemoteMode, |
| 243 | remoteUrl, |
| 244 | onShowDiff: handleShowDiff, |
| 245 | onShowStatusMessage: handleShowStatusMessage, |
| 246 | }); |
| 247 | |
| 248 | // Update ref after useChat returns |
| 249 | useEffect(() => { |
| 250 | resetChatHistoryRef.current = resetChatHistory; |
| 251 | }, [resetChatHistory]); |
| 252 | |
| 253 | // Memoize the chat history conversion to avoid expensive recalculation on every render |
| 254 | |
| 255 | // Calculate context percentage |
| 256 | const contextData = useContextPercentage({ |
| 257 | chatHistory, |
| 258 | model: services.model?.model || undefined, |
| 259 | }); |
| 260 | |
| 261 | const { renderMessage } = useMessageRenderer(); |
| 262 | |
| 263 | const { handleConfigSelect, handleModelSelect } = useSelectors( |
| 264 | configPath, |
| 265 | setChatHistory, |
| 266 | handleClear, |
| 267 | ); |
| 268 | |
| 269 | // Session selection handler |
| 270 | const handleSessionSelect = useCallback( |
| 271 | async (sessionId: string) => { |
| 272 | await loadAndSetSession( |
| 273 | sessionId, |
| 274 | closeCurrentScreen, |
| 275 | setChatHistory, |
| 276 | setShowIntroMessage, |
| 277 | ); |
| 278 | }, |
| 279 | [closeCurrentScreen, setChatHistory, setShowIntroMessage], |
| 280 | ); |
| 281 | |
| 282 | // Determine if input should be disabled |
| 283 | // Allow input even when services are loading, but disable for UI overlays |
| 284 | const isInputDisabled = |
| 285 | navState.currentScreen !== "chat" || !!activePermissionRequest; |
| 286 | |
| 287 | // Check if verbose mode is enabled for resource debugging |
| 288 | const isVerboseMode = useMemo(() => process.argv.includes("--verbose"), []); |
| 289 | |
| 290 | // State for image in clipboard status |
| 291 | const [hasImageInClipboard, setHasImageInClipboard] = useState(false); |
| 292 | |
| 293 | return ( |
| 294 | <Box flexDirection="column" height="100%"> |
| 295 | {/* Chat history - takes up all available space above input */} |
| 296 | <Box flexDirection="column" flexGrow={1} overflow="hidden"> |
| 297 | {/* Debug component - comment out when not needed */} |
| 298 | {/* {!isRemoteMode && ( |
| 299 | <ServiceDebugger |
| 300 | services={services} |
| 301 | loading={servicesLoading} |
| 302 | error={servicesError} |
| 303 | allReady={allServicesReady} |
| 304 | servicesLoading={servicesLoading} |
| 305 | servicesError={servicesError} |
| 306 | /> |
| 307 | )} */} |
| 308 | |
| 309 | {/* Chat content with intro message and messages in static container */} |
| 310 | <StaticChatContent |
| 311 | showIntroMessage={showIntroMessage && !isRemoteMode} |
| 312 | config={services.config?.config || undefined} |
| 313 | model={services.model?.model || undefined} |
| 314 | mcpService={services.mcp?.mcpService || undefined} |
| 315 | chatHistory={chatHistory} |
| 316 | queuedMessages={queuedMessages} |
| 317 | renderMessage={renderMessage} |
| 318 | refreshTrigger={staticRefreshTrigger} |
| 319 | /> |
| 320 | </Box> |
| 321 | |
| 322 | {/* Fixed bottom section */} |
| 323 | <Box flexDirection="column" flexShrink={0}> |
| 324 | {/* Status */} |
| 325 | <ActionStatus |
| 326 | visible={isWaitingForResponse && !!responseStartTime} |
| 327 | startTime={responseStartTime || 0} |
| 328 | message="" |
| 329 | showSpinner={true} |
| 330 | /> |
| 331 | |
| 332 | {/* Compaction Status */} |
| 333 | <ActionStatus |
| 334 | visible={isCompacting && !!compactionStartTime} |
| 335 | startTime={compactionStartTime || 0} |
| 336 | message="Compacting history" |
| 337 | showSpinner={true} |
| 338 | loadingColor="grey" |
| 339 | /> |
| 340 | |
| 341 | {/* Temporary status message */} |
| 342 | {statusMessage && ( |
| 343 | <Box paddingX={1} paddingY={0}> |
| 344 | <Text color="green">{statusMessage}</Text> |
| 345 | </Box> |
| 346 | )} |
| 347 | |
| 348 | {/* All screen-specific content */} |
| 349 | <ScreenContent |
| 350 | isScreenActive={isScreenActive} |
| 351 | navState={navState} |
| 352 | services={services} |
| 353 | handleLoginTokenSubmit={handleLoginTokenSubmit} |
| 354 | handleConfigSelect={handleConfigSelect} |
| 355 | handleModelSelect={handleModelSelect} |
| 356 | handleSessionSelect={handleSessionSelect} |
| 357 | handleReload={handleReload} |
| 358 | closeCurrentScreen={closeCurrentScreen} |
| 359 | activePermissionRequest={activePermissionRequest} |
| 360 | handleToolPermissionResponse={handleToolPermissionResponse} |
| 361 | handleUserMessage={handleUserMessage} |
| 362 | isWaitingForResponse={isWaitingForResponse} |
| 363 | isCompacting={isCompacting} |
| 364 | inputMode={inputMode} |
| 365 | handleInterrupt={handleInterrupt} |
| 366 | handleFileAttached={handleFileAttached} |
| 367 | isInputDisabled={isInputDisabled} |
| 368 | wasInterrupted={wasInterrupted} |
| 369 | isRemoteMode={isRemoteMode} |
| 370 | onImageInClipboardChange={setHasImageInClipboard} |
| 371 | diffContent={diffContent} |
| 372 | /> |
| 373 | |
| 374 | {/* Resource debug bar - only in verbose mode */} |
| 375 | {isVerboseMode && !isRemoteMode && ( |
| 376 | <ResourceDebugBar visible={navState.currentScreen === "chat"} /> |
| 377 | )} |
| 378 | |
| 379 | {/* Free trial status and Continue CLI info - always show */} |
| 380 | <BottomStatusBar |
| 381 | currentMode={currentMode} |
| 382 | remoteUrl={remoteUrl} |
| 383 | isRemoteMode={isRemoteMode} |
| 384 | services={services} |
| 385 | navState={navState} |
| 386 | navigateTo={navigateTo} |
| 387 | closeCurrentScreen={closeCurrentScreen} |
| 388 | contextPercentage={contextData?.percentage} |
| 389 | hasImageInClipboard={hasImageInClipboard} |
| 390 | /> |
| 391 | </Box> |
| 392 | </Box> |
| 393 | ); |
| 394 | }; |
| 395 | |
| 396 | export { TUIChat }; |