| 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 | } from "../services/types.js"; |
| 18 | import { logger } from "../util/logger.js"; |
| 19 | |
| 20 | import { BottomStatusBar } from "./components/BottomStatusBar.js"; |
| 21 | import { ResourceDebugBar } from "./components/ResourceDebugBar.js"; |
| 22 | import { ScreenContent } from "./components/ScreenContent.js"; |
| 23 | import { StaticChatContent } from "./components/StaticChatContent.js"; |
| 24 | import { useNavigation } from "./context/NavigationContext.js"; |
| 25 | import { useChat } from "./hooks/useChat.js"; |
| 26 | import { useContextPercentage } from "./hooks/useContextPercentage.js"; |
| 27 | import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; |
| 28 | import { |
| 29 | getRepoUrlText, |
| 30 | useCurrentMode, |
| 31 | useIntroMessage, |
| 32 | useLoginHandlers, |
| 33 | useSelectors, |
| 34 | } from "./hooks/useTUIChatHooks.js"; |
| 35 | import { LoadingAnimation } from "./LoadingAnimation.js"; |
| 36 | import { Timer } from "./Timer.js"; |
| 37 | |
| 38 | interface TUIChatProps { |
| 39 | // Remote mode props |
| 40 | remoteUrl?: string; |
| 41 | |
| 42 | // Local mode props - now optional since we'll get them from services |
| 43 | configPath?: string; |
| 44 | initialPrompt?: string; |
| 45 | resume?: boolean; |
| 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 | }>(["auth", "config", "model", "mcp", "apiClient"]); |
| 98 | |
| 99 | return { services, allServicesReady, isRemoteMode }; |
| 100 | } |
| 101 | |
| 102 | // Custom hook for chat handlers |
| 103 | function useChatHandlers( |
| 104 | setShowIntroMessage: (show: boolean) => void, |
| 105 | setStaticRefreshTrigger: React.Dispatch<React.SetStateAction<number>>, |
| 106 | ) { |
| 107 | // Temporary refs to avoid circular dependency |
| 108 | const resetChatHistoryRef = useRef<(() => void) | null>(null); |
| 109 | |
| 110 | // Handle clearing chat and resetting intro message |
| 111 | const handleClear = useCallback(() => { |
| 112 | setShowIntroMessage(true); |
| 113 | // Trigger static content refresh by incrementing the trigger |
| 114 | setStaticRefreshTrigger((prev) => prev + 1); |
| 115 | }, [setShowIntroMessage, setStaticRefreshTrigger]); |
| 116 | |
| 117 | // Service reload handlers - these will trigger reactive updates |
| 118 | const handleReload = useCallback(async () => { |
| 119 | // Services will automatically update the UI when they reload |
| 120 | // We just need to reset chat history, intro message, and clear the screen |
| 121 | if (resetChatHistoryRef.current) { |
| 122 | resetChatHistoryRef.current(); |
| 123 | } |
| 124 | setShowIntroMessage(false); |
| 125 | process.stdout.write("\x1b[2J\x1b[H"); |
| 126 | }, [setShowIntroMessage]); |
| 127 | |
| 128 | return { |
| 129 | handleClear, |
| 130 | handleReload, |
| 131 | resetChatHistoryRef, |
| 132 | }; |
| 133 | } |
| 134 | |
| 135 | // eslint-disable-next-line complexity |
| 136 | const TUIChat: React.FC<TUIChatProps> = ({ |
| 137 | remoteUrl, |
| 138 | configPath, |
| 139 | initialPrompt, |
| 140 | resume, |
| 141 | additionalRules, |
| 142 | additionalPrompts, |
| 143 | }) => { |
| 144 | // Use custom hook for services |
| 145 | const { services, allServicesReady, isRemoteMode } = |
| 146 | useTUIChatServices(remoteUrl); |
| 147 | |
| 148 | const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [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 | const { |
| 185 | chatHistory, |
| 186 | setChatHistory, |
| 187 | isWaitingForResponse, |
| 188 | responseStartTime, |
| 189 | inputMode, |
| 190 | activePermissionRequest, |
| 191 | wasInterrupted, |
| 192 | handleUserMessage, |
| 193 | handleInterrupt, |
| 194 | handleFileAttached, |
| 195 | resetChatHistory, |
| 196 | handleToolPermissionResponse, |
| 197 | } = useChat({ |
| 198 | assistant: services.config?.config || undefined, |
| 199 | model: services.model?.model || undefined, |
| 200 | llmApi: services.model?.llmApi || undefined, |
| 201 | initialPrompt, |
| 202 | resume, |
| 203 | additionalRules, |
| 204 | additionalPrompts, |
| 205 | onShowConfigSelector: () => navigateTo("config"), |
| 206 | onShowModelSelector: () => navigateTo("model"), |
| 207 | onShowMCPSelector: () => navigateTo("mcp"), |
| 208 | onShowSessionSelector: () => navigateTo("session"), |
| 209 | onLoginPrompt: handleLoginPrompt, |
| 210 | onReload: handleReload, |
| 211 | onClear: handleClear, |
| 212 | // Remote mode configuration |
| 213 | isRemoteMode, |
| 214 | remoteUrl, |
| 215 | }); |
| 216 | |
| 217 | // Update ref after useChat returns |
| 218 | useEffect(() => { |
| 219 | resetChatHistoryRef.current = resetChatHistory; |
| 220 | }, [resetChatHistory]); |
| 221 | |
| 222 | // Memoize the chat history conversion to avoid expensive recalculation on every render |
| 223 | |
| 224 | // Calculate context percentage |
| 225 | const contextData = useContextPercentage({ |
| 226 | chatHistory, |
| 227 | model: services.model?.model || undefined, |
| 228 | }); |
| 229 | |
| 230 | const { renderMessage } = useMessageRenderer(); |
| 231 | |
| 232 | const { handleConfigSelect, handleModelSelect } = useSelectors( |
| 233 | configPath, |
| 234 | setChatHistory, |
| 235 | handleClear, |
| 236 | ); |
| 237 | |
| 238 | // Session selection handler |
| 239 | const handleSessionSelect = useCallback( |
| 240 | async (sessionId: string) => { |
| 241 | await loadAndSetSession( |
| 242 | sessionId, |
| 243 | closeCurrentScreen, |
| 244 | setChatHistory, |
| 245 | setShowIntroMessage, |
| 246 | ); |
| 247 | }, |
| 248 | [closeCurrentScreen, setChatHistory, setShowIntroMessage], |
| 249 | ); |
| 250 | |
| 251 | // Determine if input should be disabled |
| 252 | // Allow input even when services are loading, but disable for UI overlays |
| 253 | const isInputDisabled = |
| 254 | navState.currentScreen !== "chat" || !!activePermissionRequest; |
| 255 | |
| 256 | // Check if verbose mode is enabled for resource debugging |
| 257 | const isVerboseMode = useMemo(() => process.argv.includes("--verbose"), []); |
| 258 | |
| 259 | return ( |
| 260 | <Box flexDirection="column" height="100%"> |
| 261 | {/* Chat history - takes up all available space above input */} |
| 262 | <Box flexDirection="column" flexGrow={1} overflow="hidden"> |
| 263 | {/* Debug component - comment out when not needed */} |
| 264 | {/* {!isRemoteMode && ( |
| 265 | <ServiceDebugger |
| 266 | services={services} |
| 267 | loading={servicesLoading} |
| 268 | error={servicesError} |
| 269 | allReady={allServicesReady} |
| 270 | servicesLoading={servicesLoading} |
| 271 | servicesError={servicesError} |
| 272 | /> |
| 273 | )} */} |
| 274 | |
| 275 | {/* Chat content with intro message and messages in static container */} |
| 276 | <StaticChatContent |
| 277 | showIntroMessage={showIntroMessage && !isRemoteMode} |
| 278 | config={services.config?.config || undefined} |
| 279 | model={services.model?.model || undefined} |
| 280 | mcpService={services.mcp?.mcpService || undefined} |
| 281 | chatHistory={chatHistory} |
| 282 | renderMessage={renderMessage} |
| 283 | refreshTrigger={staticRefreshTrigger} |
| 284 | /> |
| 285 | </Box> |
| 286 | |
| 287 | {/* Fixed bottom section */} |
| 288 | <Box flexDirection="column" flexShrink={0}> |
| 289 | {/* Status */} |
| 290 | {isWaitingForResponse && responseStartTime && ( |
| 291 | <Box paddingX={1} flexDirection="row" gap={1}> |
| 292 | <LoadingAnimation visible={isWaitingForResponse} /> |
| 293 | <Text key="loading-start" color="gray"> |
| 294 | ( |
| 295 | </Text> |
| 296 | <Timer startTime={responseStartTime} /> |
| 297 | <Text key="loading-end" color="gray"> |
| 298 | • esc to interrupt ) |
| 299 | </Text> |
| 300 | </Box> |
| 301 | )} |
| 302 | |
| 303 | {/* All screen-specific content */} |
| 304 | <ScreenContent |
| 305 | isScreenActive={isScreenActive} |
| 306 | navState={navState} |
| 307 | services={services} |
| 308 | handleLoginTokenSubmit={handleLoginTokenSubmit} |
| 309 | handleConfigSelect={handleConfigSelect} |
| 310 | handleModelSelect={handleModelSelect} |
| 311 | handleSessionSelect={handleSessionSelect} |
| 312 | handleReload={handleReload} |
| 313 | closeCurrentScreen={closeCurrentScreen} |
| 314 | activePermissionRequest={activePermissionRequest} |
| 315 | handleToolPermissionResponse={handleToolPermissionResponse} |
| 316 | handleUserMessage={handleUserMessage} |
| 317 | isWaitingForResponse={isWaitingForResponse} |
| 318 | inputMode={inputMode} |
| 319 | handleInterrupt={handleInterrupt} |
| 320 | handleFileAttached={handleFileAttached} |
| 321 | isInputDisabled={isInputDisabled} |
| 322 | wasInterrupted={wasInterrupted} |
| 323 | isRemoteMode={isRemoteMode} |
| 324 | /> |
| 325 | |
| 326 | {/* Resource debug bar - only in verbose mode */} |
| 327 | {isVerboseMode && !isRemoteMode && ( |
| 328 | <ResourceDebugBar visible={navState.currentScreen === "chat"} /> |
| 329 | )} |
| 330 | |
| 331 | {/* Free trial status and Continue CLI info - always show */} |
| 332 | <BottomStatusBar |
| 333 | currentMode={currentMode} |
| 334 | repoURLText={repoURlText} |
| 335 | isRemoteMode={isRemoteMode} |
| 336 | services={services} |
| 337 | navState={navState} |
| 338 | navigateTo={navigateTo} |
| 339 | closeCurrentScreen={closeCurrentScreen} |
| 340 | contextPercentage={contextData?.percentage} |
| 341 | /> |
| 342 | </Box> |
| 343 | </Box> |
| 344 | ); |
| 345 | }; |
| 346 | |
| 347 | export { TUIChat }; |