| 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 | fork?: string; |
| 47 | additionalRules?: string[]; |
| 48 | additionalPrompts?: string[]; |
| 49 | } |
| 50 | |
| 51 | // Helper function to load and set session |
| 52 | async function loadAndSetSession( |
| 53 | sessionId: string, |
| 54 | closeCurrentScreen: () => void, |
| 55 | setChatHistory: (history: any) => void, |
| 56 | setShowIntroMessage: (show: boolean) => void, |
| 57 | ) { |
| 58 | try { |
| 59 | // Close the session selector |
| 60 | closeCurrentScreen(); |
| 61 | |
| 62 | // Import session functions |
| 63 | const { loadSessionById } = await import("../session.js"); |
| 64 | |
| 65 | // Load the session |
| 66 | const session = loadSessionById(sessionId); |
| 67 | if (!session) { |
| 68 | logger.error(`Session ${sessionId} could not be loaded.`); |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | // Set the session ID so future operations use this session |
| 73 | process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace( |
| 74 | "continue-cli-", |
| 75 | "", |
| 76 | ); |
| 77 | |
| 78 | // Set the chat history from the session |
| 79 | setChatHistory(session.history); |
| 80 | |
| 81 | // Clear the intro message since we're now showing a resumed session |
| 82 | setShowIntroMessage(false); |
| 83 | } catch (error) { |
| 84 | console.error("Error loading session:", error); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | // Custom hook to manage services |
| 89 | function useTUIChatServices(remoteUrl?: string) { |
| 90 | const isRemoteMode = useMemo(() => !!remoteUrl, [remoteUrl]); |
| 91 | |
| 92 | const { services, allReady: allServicesReady } = useServices<{ |
| 93 | auth: AuthServiceState; |
| 94 | config: ConfigServiceState; |
| 95 | model: ModelServiceState; |
| 96 | mcp: MCPServiceState; |
| 97 | apiClient: ApiClientServiceState; |
| 98 | }>(["auth", "config", "model", "mcp", "apiClient"]); |
| 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 | const repoURlText = useMemo(() => getRepoUrlText(remoteUrl), [remoteUrl]); |
| 151 | |
| 152 | // Use navigation context |
| 153 | const { |
| 154 | state: navState, |
| 155 | navigateTo, |
| 156 | closeCurrentScreen, |
| 157 | isScreenActive, |
| 158 | } = useNavigation(); |
| 159 | |
| 160 | // Use intro message hook |
| 161 | const [showIntroMessage, setShowIntroMessage] = useIntroMessage( |
| 162 | isRemoteMode, |
| 163 | services, |
| 164 | allServicesReady, |
| 165 | ); |
| 166 | |
| 167 | // State for current mode (for hiding cwd in plan/auto modes) |
| 168 | const currentMode = useCurrentMode(); |
| 169 | |
| 170 | // Use login handlers |
| 171 | const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers( |
| 172 | navigateTo, |
| 173 | navState, |
| 174 | closeCurrentScreen, |
| 175 | ); |
| 176 | |
| 177 | // State to trigger static content refresh for /clear command |
| 178 | const [staticRefreshTrigger, setStaticRefreshTrigger] = useState(0); |
| 179 | |
| 180 | // Use chat handlers hook |
| 181 | const { handleClear, handleReload, resetChatHistoryRef } = useChatHandlers( |
| 182 | setShowIntroMessage, |
| 183 | setStaticRefreshTrigger, |
| 184 | ); |
| 185 | |
| 186 | const { |
| 187 | chatHistory, |
| 188 | setChatHistory, |
| 189 | isWaitingForResponse, |
| 190 | responseStartTime, |
| 191 | inputMode, |
| 192 | activePermissionRequest, |
| 193 | wasInterrupted, |
| 194 | handleUserMessage, |
| 195 | handleInterrupt, |
| 196 | handleFileAttached, |
| 197 | resetChatHistory, |
| 198 | handleToolPermissionResponse, |
| 199 | } = useChat({ |
| 200 | assistant: services.config?.config || undefined, |
| 201 | model: services.model?.model || undefined, |
| 202 | llmApi: services.model?.llmApi || undefined, |
| 203 | initialPrompt, |
| 204 | resume, |
| 205 | fork, |
| 206 | additionalRules, |
| 207 | additionalPrompts, |
| 208 | onShowConfigSelector: () => navigateTo("config"), |
| 209 | onShowModelSelector: () => navigateTo("model"), |
| 210 | onShowMCPSelector: () => navigateTo("mcp"), |
| 211 | onShowSessionSelector: () => navigateTo("session"), |
| 212 | onLoginPrompt: handleLoginPrompt, |
| 213 | onReload: handleReload, |
| 214 | onClear: handleClear, |
| 215 | // Remote mode configuration |
| 216 | isRemoteMode, |
| 217 | remoteUrl, |
| 218 | }); |
| 219 | |
| 220 | // Update ref after useChat returns |
| 221 | useEffect(() => { |
| 222 | resetChatHistoryRef.current = resetChatHistory; |
| 223 | }, [resetChatHistory]); |
| 224 | |
| 225 | // Memoize the chat history conversion to avoid expensive recalculation on every render |
| 226 | |
| 227 | // Calculate context percentage |
| 228 | const contextData = useContextPercentage({ |
| 229 | chatHistory, |
| 230 | model: services.model?.model || undefined, |
| 231 | }); |
| 232 | |
| 233 | const { renderMessage } = useMessageRenderer(); |
| 234 | |
| 235 | const { handleConfigSelect, handleModelSelect } = useSelectors( |
| 236 | configPath, |
| 237 | setChatHistory, |
| 238 | handleClear, |
| 239 | ); |
| 240 | |
| 241 | // Session selection handler |
| 242 | const handleSessionSelect = useCallback( |
| 243 | async (sessionId: string) => { |
| 244 | await loadAndSetSession( |
| 245 | sessionId, |
| 246 | closeCurrentScreen, |
| 247 | setChatHistory, |
| 248 | setShowIntroMessage, |
| 249 | ); |
| 250 | }, |
| 251 | [closeCurrentScreen, setChatHistory, setShowIntroMessage], |
| 252 | ); |
| 253 | |
| 254 | // Determine if input should be disabled |
| 255 | // Allow input even when services are loading, but disable for UI overlays |
| 256 | const isInputDisabled = |
| 257 | navState.currentScreen !== "chat" || !!activePermissionRequest; |
| 258 | |
| 259 | // Check if verbose mode is enabled for resource debugging |
| 260 | const isVerboseMode = useMemo(() => process.argv.includes("--verbose"), []); |
| 261 | |
| 262 | // State for image in clipboard status |
| 263 | const [hasImageInClipboard, setHasImageInClipboard] = useState(false); |
| 264 | |
| 265 | return ( |
| 266 | <Box flexDirection="column" height="100%"> |
| 267 | {/* Chat history - takes up all available space above input */} |
| 268 | <Box flexDirection="column" flexGrow={1} overflow="hidden"> |
| 269 | {/* Debug component - comment out when not needed */} |
| 270 | {/* {!isRemoteMode && ( |
| 271 | <ServiceDebugger |
| 272 | services={services} |
| 273 | loading={servicesLoading} |
| 274 | error={servicesError} |
| 275 | allReady={allServicesReady} |
| 276 | servicesLoading={servicesLoading} |
| 277 | servicesError={servicesError} |
| 278 | /> |
| 279 | )} */} |
| 280 | |
| 281 | {/* Chat content with intro message and messages in static container */} |
| 282 | <StaticChatContent |
| 283 | showIntroMessage={showIntroMessage && !isRemoteMode} |
| 284 | config={services.config?.config || undefined} |
| 285 | model={services.model?.model || undefined} |
| 286 | mcpService={services.mcp?.mcpService || undefined} |
| 287 | chatHistory={chatHistory} |
| 288 | renderMessage={renderMessage} |
| 289 | refreshTrigger={staticRefreshTrigger} |
| 290 | /> |
| 291 | </Box> |
| 292 | |
| 293 | {/* Fixed bottom section */} |
| 294 | <Box flexDirection="column" flexShrink={0}> |
| 295 | {/* Status */} |
| 296 | {isWaitingForResponse && responseStartTime && ( |
| 297 | <Box paddingX={1} flexDirection="row" gap={1}> |
| 298 | <LoadingAnimation visible={isWaitingForResponse} /> |
| 299 | <Text key="loading-start" color="gray"> |
| 300 | ( |
| 301 | </Text> |
| 302 | <Timer startTime={responseStartTime} /> |
| 303 | <Text key="loading-end" color="gray"> |
| 304 | • esc to interrupt ) |
| 305 | </Text> |
| 306 | </Box> |
| 307 | )} |
| 308 | |
| 309 | {/* All screen-specific content */} |
| 310 | <ScreenContent |
| 311 | isScreenActive={isScreenActive} |
| 312 | navState={navState} |
| 313 | services={services} |
| 314 | handleLoginTokenSubmit={handleLoginTokenSubmit} |
| 315 | handleConfigSelect={handleConfigSelect} |
| 316 | handleModelSelect={handleModelSelect} |
| 317 | handleSessionSelect={handleSessionSelect} |
| 318 | handleReload={handleReload} |
| 319 | closeCurrentScreen={closeCurrentScreen} |
| 320 | activePermissionRequest={activePermissionRequest} |
| 321 | handleToolPermissionResponse={handleToolPermissionResponse} |
| 322 | handleUserMessage={handleUserMessage} |
| 323 | isWaitingForResponse={isWaitingForResponse} |
| 324 | inputMode={inputMode} |
| 325 | handleInterrupt={handleInterrupt} |
| 326 | handleFileAttached={handleFileAttached} |
| 327 | isInputDisabled={isInputDisabled} |
| 328 | wasInterrupted={wasInterrupted} |
| 329 | isRemoteMode={isRemoteMode} |
| 330 | onImageInClipboardChange={setHasImageInClipboard} |
| 331 | /> |
| 332 | |
| 333 | {/* Resource debug bar - only in verbose mode */} |
| 334 | {isVerboseMode && !isRemoteMode && ( |
| 335 | <ResourceDebugBar visible={navState.currentScreen === "chat"} /> |
| 336 | )} |
| 337 | |
| 338 | {/* Free trial status and Continue CLI info - always show */} |
| 339 | <BottomStatusBar |
| 340 | currentMode={currentMode} |
| 341 | repoURLText={repoURlText} |
| 342 | isRemoteMode={isRemoteMode} |
| 343 | services={services} |
| 344 | navState={navState} |
| 345 | navigateTo={navigateTo} |
| 346 | closeCurrentScreen={closeCurrentScreen} |
| 347 | contextPercentage={contextData?.percentage} |
| 348 | hasImageInClipboard={hasImageInClipboard} |
| 349 | /> |
| 350 | </Box> |
| 351 | </Box> |
| 352 | ); |
| 353 | }; |
| 354 | |
| 355 | export { TUIChat }; |