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