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