| 1 | import { useApp } from "ink"; |
| 2 | import { ChatCompletionMessageParam } from "openai/resources.mjs"; |
| 3 | import { useEffect, useState } from "react"; |
| 4 | |
| 5 | import { findCompactionIndex } from "../../compaction.js"; |
| 6 | import { toolPermissionManager } from "../../permissions/permissionManager.js"; |
| 7 | import { services } from "../../services/index.js"; |
| 8 | import { loadSession, saveSession } from "../../session.js"; |
| 9 | import { handleSlashCommands } from "../../slashCommands.js"; |
| 10 | import { telemetryService } from "../../telemetry/telemetryService.js"; |
| 11 | import { formatError } from "../../util/formatError.js"; |
| 12 | import { logger } from "../../util/logger.js"; |
| 13 | import { DisplayMessage } from "../types.js"; |
| 14 | |
| 15 | import { |
| 16 | formatMessageWithFiles, |
| 17 | handleAutoCompaction, |
| 18 | handleCompactCommand, |
| 19 | handleSpecialCommands, |
| 20 | initChatHistory, |
| 21 | processSlashCommandResult, |
| 22 | trackUserMessage, |
| 23 | } from "./useChat.helpers.js"; |
| 24 | import { |
| 25 | handleRemoteMessage, |
| 26 | setupRemotePolling, |
| 27 | } from "./useChat.remote.helpers.js"; |
| 28 | import { |
| 29 | createStreamCallbacks, |
| 30 | executeStreaming, |
| 31 | } from "./useChat.stream.helpers.js"; |
| 32 | import { |
| 33 | ActivePermissionRequest, |
| 34 | AttachedFile, |
| 35 | UseChatProps, |
| 36 | } from "./useChat.types.js"; |
| 37 | |
| 38 | export function useChat({ |
| 39 | assistant, |
| 40 | model, |
| 41 | llmApi, |
| 42 | initialPrompt, |
| 43 | resume, |
| 44 | additionalRules, |
| 45 | onShowConfigSelector, |
| 46 | onShowModelSelector, |
| 47 | onShowMCPSelector, |
| 48 | onShowSessionSelector, |
| 49 | onLoginPrompt: _onLoginPrompt, |
| 50 | isRemoteMode = false, |
| 51 | remoteUrl, |
| 52 | }: UseChatProps) { |
| 53 | const { exit } = useApp(); |
| 54 | |
| 55 | const [chatHistory, setChatHistory] = useState<ChatCompletionMessageParam[]>( |
| 56 | () => { |
| 57 | // In remote mode, start with empty history (will be populated by polling) |
| 58 | if (isRemoteMode) { |
| 59 | return []; |
| 60 | } |
| 61 | |
| 62 | // Synchronously initialize chat history to prevent race conditions |
| 63 | // Load previous session if resume flag is used |
| 64 | // If no session loaded or not resuming, we'll need to add system message |
| 65 | // We can't make this async, so we'll handle it in the useEffect |
| 66 | return resume ? (loadSession() ?? []) : []; |
| 67 | }, |
| 68 | ); |
| 69 | |
| 70 | const [messages, setMessages] = useState<DisplayMessage[]>(() => { |
| 71 | if (resume) { |
| 72 | const savedHistory = loadSession(); |
| 73 | if (savedHistory) { |
| 74 | return savedHistory |
| 75 | .filter((msg) => msg.role !== "system") |
| 76 | .map((msg) => ({ |
| 77 | role: msg.role, |
| 78 | content: msg.content as string, |
| 79 | })); |
| 80 | } |
| 81 | } |
| 82 | return []; |
| 83 | }); |
| 84 | |
| 85 | const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); |
| 86 | const [responseStartTime, setResponseStartTime] = useState<number | null>( |
| 87 | null, |
| 88 | ); |
| 89 | const [inputMode, setInputMode] = useState(true); |
| 90 | const [abortController, setAbortController] = |
| 91 | useState<AbortController | null>(null); |
| 92 | const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState( |
| 93 | // If we're resuming and found a saved session, we're already initialized |
| 94 | // If we're in remote mode, we're initialized (will be populated by polling) |
| 95 | isRemoteMode || (resume && loadSession() !== null), |
| 96 | ); |
| 97 | |
| 98 | // Capture initial rules to prevent re-initialization when rules change |
| 99 | const [initialRules] = useState(additionalRules); |
| 100 | const [attachedFiles, setAttachedFiles] = useState<AttachedFile[]>([]); |
| 101 | const [activePermissionRequest, setActivePermissionRequest] = |
| 102 | useState<ActivePermissionRequest | null>(null); |
| 103 | const [compactionIndex, setCompactionIndex] = useState<number | null>(() => { |
| 104 | // When resuming, check for compaction markers in the loaded history |
| 105 | if (resume) { |
| 106 | const savedHistory = loadSession(); |
| 107 | if (savedHistory) { |
| 108 | return findCompactionIndex(savedHistory); |
| 109 | } |
| 110 | } |
| 111 | return null; |
| 112 | }); |
| 113 | |
| 114 | // Clean up abort controller on unmount |
| 115 | useEffect(() => { |
| 116 | return () => { |
| 117 | if (abortController && !abortController.signal.aborted) { |
| 118 | abortController.abort(); |
| 119 | } |
| 120 | }; |
| 121 | }, [abortController]); |
| 122 | |
| 123 | // Remote mode polling |
| 124 | useEffect(() => { |
| 125 | if (!isRemoteMode || !remoteUrl || process.env.NODE_ENV === "test") return; |
| 126 | |
| 127 | return setupRemotePolling({ |
| 128 | remoteUrl, |
| 129 | setMessages, |
| 130 | setChatHistory, |
| 131 | setIsWaitingForResponse, |
| 132 | responseStartTime, |
| 133 | setResponseStartTime, |
| 134 | }); |
| 135 | }, [isRemoteMode, remoteUrl, responseStartTime]); |
| 136 | |
| 137 | useEffect(() => { |
| 138 | // Skip initialization in remote mode or if already initialized |
| 139 | if (isRemoteMode || isChatHistoryInitialized) return; |
| 140 | |
| 141 | // Initialize chat history with system message only if we don't have a session |
| 142 | const initializeHistory = async () => { |
| 143 | // Only add system message if we don't have any messages yet |
| 144 | if (chatHistory.length === 0) { |
| 145 | const history = await initChatHistory(resume, initialRules); |
| 146 | setChatHistory(history); |
| 147 | } |
| 148 | setIsChatHistoryInitialized(true); |
| 149 | }; |
| 150 | |
| 151 | initializeHistory(); |
| 152 | // Note: Using initialRules instead of additionalRules to prevent re-initialization |
| 153 | // when rules change during the conversation |
| 154 | }, [ |
| 155 | isRemoteMode, |
| 156 | isChatHistoryInitialized, |
| 157 | chatHistory.length, |
| 158 | resume, |
| 159 | initialRules, |
| 160 | ]); |
| 161 | |
| 162 | useEffect(() => { |
| 163 | // Only handle initial prompt after chat history is initialized |
| 164 | // This prevents race conditions where the prompt runs before system message is loaded |
| 165 | if (initialPrompt && isChatHistoryInitialized) { |
| 166 | handleUserMessage(initialPrompt); |
| 167 | } |
| 168 | }, [initialPrompt, isChatHistoryInitialized]); |
| 169 | |
| 170 | const executeStreamingResponse = async ( |
| 171 | newHistory: ChatCompletionMessageParam[], |
| 172 | currentCompactionIndex: number | null, |
| 173 | message: string, |
| 174 | ) => { |
| 175 | // Clean up previous abort controller if it exists |
| 176 | if (abortController && !abortController.signal.aborted) { |
| 177 | abortController.abort(); |
| 178 | } |
| 179 | |
| 180 | // Start streaming response |
| 181 | const controller = new AbortController(); |
| 182 | setAbortController(controller); |
| 183 | setIsWaitingForResponse(true); |
| 184 | setResponseStartTime(Date.now()); |
| 185 | setInputMode(false); |
| 186 | logger.debug("Starting chat response stream", { |
| 187 | messageLength: message.length, |
| 188 | historyLength: newHistory.length, |
| 189 | }); |
| 190 | |
| 191 | try { |
| 192 | const currentStreamingMessageRef = { |
| 193 | current: null as DisplayMessage | null, |
| 194 | }; |
| 195 | const streamCallbacks = createStreamCallbacks( |
| 196 | { setMessages, setActivePermissionRequest }, |
| 197 | currentStreamingMessageRef, |
| 198 | ); |
| 199 | |
| 200 | // Execute streaming chat response |
| 201 | await executeStreaming({ |
| 202 | newHistory, |
| 203 | model, |
| 204 | llmApi, |
| 205 | controller, |
| 206 | streamCallbacks, |
| 207 | currentCompactionIndex, |
| 208 | }); |
| 209 | |
| 210 | if ( |
| 211 | currentStreamingMessageRef.current && |
| 212 | currentStreamingMessageRef.current.content |
| 213 | ) { |
| 214 | const messageContent = currentStreamingMessageRef.current.content; |
| 215 | setMessages((prev) => [ |
| 216 | ...prev, |
| 217 | { |
| 218 | role: "assistant", |
| 219 | content: messageContent, |
| 220 | isStreaming: false, |
| 221 | }, |
| 222 | ]); |
| 223 | } |
| 224 | |
| 225 | // Update the chat history with the complete conversation after streaming |
| 226 | setChatHistory(newHistory); |
| 227 | logger.debug("Chat history updated", { |
| 228 | finalHistoryLength: newHistory.length, |
| 229 | }); |
| 230 | |
| 231 | // Save the updated history to session |
| 232 | logger.debug("Saving session", { historyLength: newHistory.length }); |
| 233 | saveSession(newHistory); |
| 234 | logger.debug("Session saved"); |
| 235 | } catch (error: any) { |
| 236 | const errorMessage = `Error: ${formatError(error)}`; |
| 237 | setMessages((prev) => [ |
| 238 | ...prev, |
| 239 | { |
| 240 | role: "system", |
| 241 | content: errorMessage, |
| 242 | messageType: "system" as const, |
| 243 | }, |
| 244 | ]); |
| 245 | } finally { |
| 246 | // Stop active time tracking |
| 247 | telemetryService.stopActiveTime(); |
| 248 | |
| 249 | setAbortController(null); |
| 250 | setIsWaitingForResponse(false); |
| 251 | setResponseStartTime(null); |
| 252 | setInputMode(true); |
| 253 | } |
| 254 | }; |
| 255 | |
| 256 | const handleUserMessage = async (message: string) => { |
| 257 | // Handle special commands |
| 258 | const handled = await handleSpecialCommands({ |
| 259 | message, |
| 260 | isRemoteMode, |
| 261 | remoteUrl, |
| 262 | onShowConfigSelector, |
| 263 | exit, |
| 264 | setMessages, |
| 265 | }); |
| 266 | |
| 267 | if (handled) return; |
| 268 | |
| 269 | // Handle slash commands (skip in remote mode except for /exit which we handled above) |
| 270 | if (!isRemoteMode && assistant) { |
| 271 | const commandResult = await handleSlashCommands(message, assistant); |
| 272 | if (commandResult) { |
| 273 | if (commandResult.compact) { |
| 274 | await handleCompactCommand({ |
| 275 | chatHistory, |
| 276 | model, |
| 277 | llmApi, |
| 278 | setChatHistory, |
| 279 | setMessages, |
| 280 | setCompactionIndex, |
| 281 | }); |
| 282 | return; |
| 283 | } |
| 284 | |
| 285 | const newInput = processSlashCommandResult({ |
| 286 | result: commandResult, |
| 287 | chatHistory, |
| 288 | setChatHistory, |
| 289 | setMessages, |
| 290 | exit, |
| 291 | onShowConfigSelector, |
| 292 | onShowModelSelector, |
| 293 | onShowMCPSelector, |
| 294 | onShowSessionSelector, |
| 295 | }); |
| 296 | |
| 297 | if (newInput) { |
| 298 | message = newInput; |
| 299 | } else { |
| 300 | return; |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // Track telemetry |
| 306 | trackUserMessage(message, model); |
| 307 | |
| 308 | // Add user message to history and display |
| 309 | const messageContent = formatMessageWithFiles(message, attachedFiles); |
| 310 | if (attachedFiles.length > 0) { |
| 311 | setAttachedFiles([]); |
| 312 | } |
| 313 | |
| 314 | // In remote mode, send message to server instead of processing locally |
| 315 | if (isRemoteMode && remoteUrl) { |
| 316 | await handleRemoteMessage({ |
| 317 | remoteUrl, |
| 318 | messageContent, |
| 319 | setMessages, |
| 320 | }); |
| 321 | return; |
| 322 | } |
| 323 | |
| 324 | // Check if auto-compacting is needed BEFORE adding user message |
| 325 | const { currentChatHistory, currentCompactionIndex } = |
| 326 | await handleAutoCompaction({ |
| 327 | chatHistory, |
| 328 | model, |
| 329 | llmApi, |
| 330 | compactionIndex, |
| 331 | setMessages, |
| 332 | setChatHistory, |
| 333 | setCompactionIndex, |
| 334 | }); |
| 335 | |
| 336 | // NOW add user message to history and UI |
| 337 | const newUserMessage: ChatCompletionMessageParam = { |
| 338 | role: "user", |
| 339 | content: messageContent, |
| 340 | }; |
| 341 | const newHistory = [...currentChatHistory, newUserMessage]; |
| 342 | setChatHistory(newHistory); |
| 343 | setMessages((prev) => [...prev, { role: "user", content: message }]); |
| 344 | |
| 345 | // Execute the streaming response |
| 346 | await executeStreamingResponse(newHistory, currentCompactionIndex, message); |
| 347 | }; |
| 348 | |
| 349 | const handleInterrupt = () => { |
| 350 | // In remote mode, send interrupt signal to server |
| 351 | if (isRemoteMode && remoteUrl) { |
| 352 | // Send a message to interrupt the remote server |
| 353 | fetch(`${remoteUrl}/message`, { |
| 354 | method: "POST", |
| 355 | headers: { |
| 356 | "Content-Type": "application/json", |
| 357 | }, |
| 358 | body: JSON.stringify({ message: "" }), // Empty message triggers interrupt |
| 359 | }).catch((error) => { |
| 360 | logger.error("Failed to send interrupt to remote server:", error); |
| 361 | }); |
| 362 | return; |
| 363 | } |
| 364 | |
| 365 | // Local mode: abort the controller |
| 366 | if (abortController && isWaitingForResponse) { |
| 367 | abortController.abort(); |
| 368 | setMessages((prev) => [ |
| 369 | ...prev, |
| 370 | { |
| 371 | role: "system", |
| 372 | content: "[Interrupted by user]", |
| 373 | messageType: "system" as const, |
| 374 | }, |
| 375 | ]); |
| 376 | } |
| 377 | }; |
| 378 | |
| 379 | const handleFileAttached = (filePath: string, content: string) => { |
| 380 | setAttachedFiles((prev) => [...prev, { path: filePath, content }]); |
| 381 | }; |
| 382 | |
| 383 | const resetChatHistory = async () => { |
| 384 | const newHistory = await initChatHistory( |
| 385 | false, // Don't resume when resetting |
| 386 | additionalRules, |
| 387 | ); |
| 388 | setChatHistory(newHistory); |
| 389 | setMessages([]); |
| 390 | }; |
| 391 | |
| 392 | const handleToolPermissionResponse = async ( |
| 393 | requestId: string, |
| 394 | approved: boolean, |
| 395 | createPolicy?: boolean, |
| 396 | stopStream?: boolean, |
| 397 | ) => { |
| 398 | // Capture the current permission request before clearing it |
| 399 | const currentRequest = activePermissionRequest; |
| 400 | |
| 401 | // Clear the active permission request |
| 402 | setActivePermissionRequest(null); |
| 403 | |
| 404 | // Handle policy creation if requested |
| 405 | if (approved && createPolicy && currentRequest) { |
| 406 | try { |
| 407 | const { generatePolicyRule, addPolicyToYaml } = await import( |
| 408 | "../../permissions/policyWriter.js" |
| 409 | ); |
| 410 | |
| 411 | const policyRule = generatePolicyRule( |
| 412 | currentRequest.toolName, |
| 413 | currentRequest.toolArgs, |
| 414 | ); |
| 415 | |
| 416 | await addPolicyToYaml(policyRule); |
| 417 | logger.debug(`Policy created: ${policyRule}`); |
| 418 | |
| 419 | // Reload permissions to pick up the new policy without requiring restart |
| 420 | await services.mode.getToolPermissionService().reloadPermissions(); |
| 421 | } catch (error) { |
| 422 | logger.error("Failed to create policy or reload permissions", { |
| 423 | error, |
| 424 | }); |
| 425 | // Continue with the approval even if policy creation/reload fails |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | // Send response to permission manager |
| 430 | // The streamChatResponse will handle showing the appropriate message |
| 431 | // through its normal onToolStart/onToolError flow |
| 432 | if (approved) { |
| 433 | toolPermissionManager.approveRequest(requestId); |
| 434 | } else { |
| 435 | toolPermissionManager.rejectRequest(requestId); |
| 436 | |
| 437 | // If this is a "stop stream" rejection, abort the current request |
| 438 | if (stopStream && abortController && isWaitingForResponse) { |
| 439 | abortController.abort(); |
| 440 | setMessages((prev) => [ |
| 441 | ...prev, |
| 442 | { |
| 443 | role: "system", |
| 444 | content: |
| 445 | "[Tool canceled - please tell Continue what to do differently]", |
| 446 | messageType: "system" as const, |
| 447 | }, |
| 448 | ]); |
| 449 | setIsWaitingForResponse(false); |
| 450 | setResponseStartTime(null); |
| 451 | setInputMode(true); |
| 452 | } |
| 453 | } |
| 454 | }; |
| 455 | |
| 456 | return { |
| 457 | messages, |
| 458 | setMessages, |
| 459 | chatHistory, |
| 460 | setChatHistory, |
| 461 | isWaitingForResponse, |
| 462 | responseStartTime, |
| 463 | inputMode, |
| 464 | attachedFiles, |
| 465 | activePermissionRequest, |
| 466 | handleUserMessage, |
| 467 | handleInterrupt, |
| 468 | handleFileAttached, |
| 469 | resetChatHistory, |
| 470 | handleToolPermissionResponse, |
| 471 | }; |
| 472 | } |