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