| 1 | import type { ChatHistoryItem, Session } from "core/index.js"; |
| 2 | import { useApp } from "ink"; |
| 3 | import { useEffect, useRef, 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 { |
| 9 | createSession, |
| 10 | loadSession, |
| 11 | updateSessionHistory, |
| 12 | } from "../../session.js"; |
| 13 | import { handleSlashCommands } from "../../slashCommands.js"; |
| 14 | import { telemetryService } from "../../telemetry/telemetryService.js"; |
| 15 | import { formatError } from "../../util/formatError.js"; |
| 16 | import { logger } from "../../util/logger.js"; |
| 17 | |
| 18 | import { |
| 19 | handleAutoCompaction, |
| 20 | handleCompactCommand, |
| 21 | } from "./useChat.compaction.js"; |
| 22 | import { |
| 23 | formatMessageWithFiles, |
| 24 | handleSpecialCommands, |
| 25 | initChatHistory, |
| 26 | processSlashCommandResult, |
| 27 | trackUserMessage, |
| 28 | } from "./useChat.helpers.js"; |
| 29 | import { |
| 30 | handleRemoteMessage, |
| 31 | setupRemotePolling, |
| 32 | } from "./useChat.remote.helpers.js"; |
| 33 | import { handleBashModeProcessing } from "./useChat.shellMode.js"; |
| 34 | import { |
| 35 | createStreamCallbacks, |
| 36 | executeStreaming, |
| 37 | } from "./useChat.stream.helpers.js"; |
| 38 | import { |
| 39 | ActivePermissionRequest, |
| 40 | AttachedFile, |
| 41 | UseChatProps, |
| 42 | } from "./useChat.types.js"; |
| 43 | |
| 44 | export function useChat({ |
| 45 | assistant, |
| 46 | model, |
| 47 | llmApi, |
| 48 | initialPrompt, |
| 49 | resume, |
| 50 | fork, |
| 51 | additionalRules, |
| 52 | additionalPrompts, |
| 53 | onShowConfigSelector, |
| 54 | onShowModelSelector, |
| 55 | onShowMCPSelector, |
| 56 | onShowSessionSelector, |
| 57 | onLoginPrompt: _onLoginPrompt, |
| 58 | onClear, |
| 59 | isRemoteMode = false, |
| 60 | remoteUrl, |
| 61 | }: UseChatProps) { |
| 62 | const { exit } = useApp(); |
| 63 | |
| 64 | // Track service subscription |
| 65 | const serviceListenerCleanupRef = useRef<null | (() => void)>(null); |
| 66 | |
| 67 | // Store the current session |
| 68 | const [currentSession, setCurrentSession] = useState<Session>(() => { |
| 69 | // In remote mode, start with empty session (will be populated by polling) |
| 70 | if (isRemoteMode) { |
| 71 | return createSession([]); |
| 72 | } |
| 73 | |
| 74 | // Fork from an existing session if fork flag is used |
| 75 | if (fork) { |
| 76 | const { loadSessionById, startNewSession } = require("../../session.js"); |
| 77 | const sessionToFork = loadSessionById(fork); |
| 78 | if (sessionToFork) { |
| 79 | return startNewSession(sessionToFork.history); |
| 80 | } |
| 81 | // If session not found, create a new empty session |
| 82 | return createSession([]); |
| 83 | } |
| 84 | |
| 85 | // Load previous session if resume flag is used |
| 86 | if (resume) { |
| 87 | const savedSession = loadSession(); |
| 88 | if (savedSession) { |
| 89 | return savedSession; |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // Create new session |
| 94 | return createSession([]); |
| 95 | }); |
| 96 | |
| 97 | // Local view of history driven solely by ChatHistoryService |
| 98 | const [chatHistory, setChatHistoryView] = useState<ChatHistoryItem[]>(() => |
| 99 | services.chatHistory?.isReady() |
| 100 | ? services.chatHistory.getHistory() |
| 101 | : currentSession.history, |
| 102 | ); |
| 103 | // Proxy setter: apply changes to ChatHistoryService (single source of truth) |
| 104 | const setChatHistory: React.Dispatch< |
| 105 | React.SetStateAction<ChatHistoryItem[]> |
| 106 | > = (value) => { |
| 107 | const svc = services.chatHistory; |
| 108 | const current = svc.getHistory(); |
| 109 | const next = typeof value === "function" ? (value as any)(current) : value; |
| 110 | svc.setHistory(next); |
| 111 | }; |
| 112 | |
| 113 | // Initialize ChatHistoryService and subscribe to updates |
| 114 | useEffect(() => { |
| 115 | const svc = services.chatHistory; |
| 116 | svc |
| 117 | .initialize(currentSession, isRemoteMode) |
| 118 | .then(() => { |
| 119 | setChatHistoryView(svc.getHistory()); |
| 120 | const listener = () => { |
| 121 | setChatHistoryView(svc.getHistory()); |
| 122 | }; |
| 123 | svc.on("stateChanged", listener); |
| 124 | serviceListenerCleanupRef.current = () => |
| 125 | svc.off("stateChanged", listener); |
| 126 | }) |
| 127 | .catch((error) => { |
| 128 | logger.error("Failed to initialize ChatHistoryService", { error }); |
| 129 | }); |
| 130 | |
| 131 | return () => { |
| 132 | serviceListenerCleanupRef.current?.(); |
| 133 | serviceListenerCleanupRef.current = null; |
| 134 | }; |
| 135 | }, []); |
| 136 | |
| 137 | const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); |
| 138 | const [responseStartTime, setResponseStartTime] = useState<number | null>( |
| 139 | null, |
| 140 | ); |
| 141 | const [inputMode, setInputMode] = useState(true); |
| 142 | const [abortController, setAbortController] = |
| 143 | useState<AbortController | null>(null); |
| 144 | const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState( |
| 145 | // If we're resuming and found a saved session, we're already initialized |
| 146 | // If we're forking and found a session to fork from, we're already initialized |
| 147 | // If we're in remote mode, we're initialized (will be populated by polling) |
| 148 | isRemoteMode || |
| 149 | (resume && currentSession.history.length > 0) || |
| 150 | (fork && currentSession.history.length > 0), |
| 151 | ); |
| 152 | |
| 153 | // Capture initial rules to prevent re-initialization when rules change |
| 154 | const [initialRules] = useState(additionalRules); |
| 155 | const [attachedFiles, setAttachedFiles] = useState<AttachedFile[]>([]); |
| 156 | const [activePermissionRequest, setActivePermissionRequest] = |
| 157 | useState<ActivePermissionRequest | null>(null); |
| 158 | const [compactionIndex, setCompactionIndex] = useState<number | null>(() => { |
| 159 | // When resuming or forking, check for compaction markers in the loaded history |
| 160 | if ((resume || fork) && currentSession.history.length > 0) { |
| 161 | return findCompactionIndex(currentSession.history); |
| 162 | } |
| 163 | return null; |
| 164 | }); |
| 165 | |
| 166 | // Track interrupted state for resume functionality |
| 167 | const [wasInterrupted, setWasInterrupted] = useState(false); |
| 168 | |
| 169 | // Clean up abort controller on unmount |
| 170 | useEffect(() => { |
| 171 | return () => { |
| 172 | if (abortController && !abortController.signal.aborted) { |
| 173 | abortController.abort(); |
| 174 | } |
| 175 | }; |
| 176 | }, [abortController]); |
| 177 | |
| 178 | // Remote mode polling |
| 179 | useEffect(() => { |
| 180 | if (!isRemoteMode || !remoteUrl || process.env.NODE_ENV === "test") return; |
| 181 | |
| 182 | return setupRemotePolling({ |
| 183 | remoteUrl, |
| 184 | setIsWaitingForResponse, |
| 185 | responseStartTime, |
| 186 | setResponseStartTime, |
| 187 | }); |
| 188 | }, [isRemoteMode, remoteUrl, responseStartTime]); |
| 189 | |
| 190 | useEffect(() => { |
| 191 | // Skip initialization in remote mode or if already initialized |
| 192 | if (isRemoteMode || isChatHistoryInitialized) return; |
| 193 | |
| 194 | // Initialize chat history with system message only if we don't have a session |
| 195 | const initializeHistory = async () => { |
| 196 | // Only add system message if we don't have any messages yet |
| 197 | if (chatHistory.length === 0) { |
| 198 | const history = await initChatHistory(resume, initialRules); |
| 199 | setChatHistory(history); |
| 200 | } |
| 201 | setIsChatHistoryInitialized(true); |
| 202 | }; |
| 203 | |
| 204 | initializeHistory(); |
| 205 | // Note: Using initialRules instead of additionalRules to prevent re-initialization |
| 206 | // when rules change during the conversation |
| 207 | }, [ |
| 208 | isRemoteMode, |
| 209 | isChatHistoryInitialized, |
| 210 | chatHistory.length, |
| 211 | resume, |
| 212 | initialRules, |
| 213 | ]); |
| 214 | |
| 215 | useEffect(() => { |
| 216 | // Only handle initial prompt after chat history is initialized |
| 217 | // This prevents race conditions where the prompt runs before system message is loaded |
| 218 | if ( |
| 219 | (initialPrompt || (additionalPrompts && additionalPrompts.length > 0)) && |
| 220 | isChatHistoryInitialized |
| 221 | ) { |
| 222 | const processPrompts = async () => { |
| 223 | const { processAndCombinePrompts } = await import( |
| 224 | "../../util/promptProcessor.js" |
| 225 | ); |
| 226 | const finalMessage = await processAndCombinePrompts( |
| 227 | additionalPrompts, |
| 228 | initialPrompt, |
| 229 | ); |
| 230 | |
| 231 | if (finalMessage) { |
| 232 | await handleUserMessage(finalMessage); |
| 233 | } |
| 234 | }; |
| 235 | |
| 236 | processPrompts().catch(console.error); |
| 237 | } |
| 238 | }, [initialPrompt, additionalPrompts, isChatHistoryInitialized]); |
| 239 | |
| 240 | const executeStreamingResponse = async ( |
| 241 | newHistory: ChatHistoryItem[], |
| 242 | currentCompactionIndex: number | null, |
| 243 | ) => { |
| 244 | // Clean up previous abort controller if it exists |
| 245 | if (abortController && !abortController.signal.aborted) { |
| 246 | abortController.abort(); |
| 247 | } |
| 248 | |
| 249 | // Start streaming response |
| 250 | const controller = new AbortController(); |
| 251 | setAbortController(controller); |
| 252 | setIsWaitingForResponse(true); |
| 253 | setResponseStartTime(Date.now()); |
| 254 | setInputMode(false); |
| 255 | logger.debug("Starting chat response stream", { |
| 256 | historyLength: newHistory.length, |
| 257 | }); |
| 258 | |
| 259 | try { |
| 260 | const streamCallbacks = createStreamCallbacks({ |
| 261 | setChatHistory: setChatHistory, |
| 262 | setActivePermissionRequest, |
| 263 | llmApi, |
| 264 | model, |
| 265 | }); |
| 266 | |
| 267 | // Execute streaming chat response |
| 268 | await executeStreaming({ |
| 269 | chatHistory: newHistory, |
| 270 | model, |
| 271 | llmApi, |
| 272 | controller, |
| 273 | streamCallbacks, |
| 274 | currentCompactionIndex, |
| 275 | }); |
| 276 | |
| 277 | // Save the updated session with the latest chat history that includes the assistant's reply |
| 278 | // The streamCallbacks update setChatHistory during streaming, so we need to get the current state |
| 279 | setChatHistory((currentHistory) => { |
| 280 | const updatedSession: Session = { |
| 281 | ...currentSession, |
| 282 | history: currentHistory, |
| 283 | }; |
| 284 | updateSessionHistory(currentHistory); |
| 285 | setCurrentSession(updatedSession); |
| 286 | logger.debug("Session saved"); |
| 287 | return currentHistory; |
| 288 | }); |
| 289 | } catch (error: any) { |
| 290 | const errorMessage = `Error: ${formatError(error)}`; |
| 291 | setChatHistory((prev) => [ |
| 292 | ...prev, |
| 293 | { |
| 294 | message: { |
| 295 | role: "system", |
| 296 | content: errorMessage, |
| 297 | }, |
| 298 | contextItems: [], |
| 299 | }, |
| 300 | ]); |
| 301 | } finally { |
| 302 | // Stop active time tracking |
| 303 | telemetryService.stopActiveTime(); |
| 304 | |
| 305 | setAbortController(null); |
| 306 | setIsWaitingForResponse(false); |
| 307 | setResponseStartTime(null); |
| 308 | setInputMode(true); |
| 309 | } |
| 310 | }; |
| 311 | |
| 312 | const handleResumeRequest = async (message: string) => { |
| 313 | if (message !== "" || !wasInterrupted) return false; |
| 314 | |
| 315 | // Find the index of the last user or tool message to resume from |
| 316 | let lastUserOrToolIndex = -1; |
| 317 | for (let i = chatHistory.length - 1; i >= 0; i--) { |
| 318 | if ( |
| 319 | chatHistory[i].message.role === "user" || |
| 320 | !!chatHistory[i].toolCallStates?.length |
| 321 | ) { |
| 322 | lastUserOrToolIndex = i; |
| 323 | break; |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | if (lastUserOrToolIndex >= 0) { |
| 328 | // Truncate history to include up to and including the user/tool message |
| 329 | const truncatedHistory = chatHistory.slice(0, lastUserOrToolIndex + 1); |
| 330 | setChatHistory(truncatedHistory); |
| 331 | |
| 332 | // Clear the interrupted state and resume |
| 333 | setWasInterrupted(false); |
| 334 | |
| 335 | // Re-execute streaming with the truncated history |
| 336 | await executeStreamingResponse(truncatedHistory, compactionIndex); |
| 337 | return true; |
| 338 | } |
| 339 | |
| 340 | return false; |
| 341 | }; |
| 342 | |
| 343 | const handleSlashCommandProcessing = async ( |
| 344 | message: string, |
| 345 | ): Promise<string | null> => { |
| 346 | // Handle slash commands (skip in remote mode except for /exit which we handled above) |
| 347 | if (isRemoteMode || !assistant) { |
| 348 | return message; |
| 349 | } |
| 350 | |
| 351 | const commandResult = await handleSlashCommands(message, assistant); |
| 352 | if (!commandResult) { |
| 353 | return message; |
| 354 | } |
| 355 | |
| 356 | if (commandResult.compact) { |
| 357 | await handleCompactCommand({ |
| 358 | chatHistory, |
| 359 | model, |
| 360 | llmApi, |
| 361 | setChatHistory, |
| 362 | setCompactionIndex, |
| 363 | currentSession, |
| 364 | setCurrentSession, |
| 365 | }); |
| 366 | return null; |
| 367 | } |
| 368 | |
| 369 | const newInput = processSlashCommandResult({ |
| 370 | result: commandResult, |
| 371 | chatHistory, |
| 372 | setChatHistory, |
| 373 | exit, |
| 374 | onShowConfigSelector, |
| 375 | onShowModelSelector, |
| 376 | onShowMCPSelector, |
| 377 | onShowSessionSelector, |
| 378 | onClear, |
| 379 | }); |
| 380 | |
| 381 | return newInput || null; |
| 382 | }; |
| 383 | |
| 384 | const convertMessageContentToString = (content: any): string => { |
| 385 | if (typeof content === "string") { |
| 386 | return content; |
| 387 | } |
| 388 | |
| 389 | // Convert MessagePart[] to string (extracting text, noting images) |
| 390 | return content |
| 391 | .map((part: any) => { |
| 392 | if (part.type === "text") { |
| 393 | return part.text; |
| 394 | } else if (part.type === "imageUrl") { |
| 395 | return "[Image]"; |
| 396 | } |
| 397 | return ""; |
| 398 | }) |
| 399 | .join(""); |
| 400 | }; |
| 401 | |
| 402 | const handleUserMessage = async ( |
| 403 | message: string, |
| 404 | imageMap?: Map<string, Buffer>, |
| 405 | ) => { |
| 406 | // Check if this is a resume request (empty message after interruption) |
| 407 | if (await handleResumeRequest(message)) { |
| 408 | return; |
| 409 | } |
| 410 | |
| 411 | // Clear interrupted state if user types a new message |
| 412 | if (wasInterrupted && message !== "") { |
| 413 | setWasInterrupted(false); |
| 414 | } |
| 415 | |
| 416 | // Handle special commands |
| 417 | const handled = await handleSpecialCommands({ |
| 418 | message, |
| 419 | isRemoteMode, |
| 420 | remoteUrl, |
| 421 | onShowConfigSelector, |
| 422 | exit, |
| 423 | }); |
| 424 | |
| 425 | if (handled) return; |
| 426 | |
| 427 | // Handle shell mode commands (before slash commands) |
| 428 | const bashProcessedMessage = await handleBashModeProcessing(message); |
| 429 | if (bashProcessedMessage === null) { |
| 430 | return; // Bash command was handled and no further processing needed |
| 431 | } |
| 432 | message = bashProcessedMessage; |
| 433 | |
| 434 | // Handle slash commands |
| 435 | const processedMessage = await handleSlashCommandProcessing(message); |
| 436 | if (processedMessage === null) { |
| 437 | return; // Command was handled and no further processing needed |
| 438 | } |
| 439 | message = processedMessage; |
| 440 | |
| 441 | // Track telemetry |
| 442 | trackUserMessage(message, model); |
| 443 | |
| 444 | // Format message with attached files and images |
| 445 | logger.debug("Processing message with images", { |
| 446 | hasImages: !!(imageMap && imageMap.size > 0), |
| 447 | imageCount: imageMap?.size || 0, |
| 448 | }); |
| 449 | const newUserMessage = await formatMessageWithFiles( |
| 450 | message, |
| 451 | attachedFiles, |
| 452 | imageMap, |
| 453 | ); |
| 454 | logger.debug("Message formatted successfully"); |
| 455 | |
| 456 | if (attachedFiles.length > 0) { |
| 457 | setAttachedFiles([]); |
| 458 | } |
| 459 | |
| 460 | // In remote mode, send message to server instead of processing locally |
| 461 | if (isRemoteMode && remoteUrl) { |
| 462 | const messageContentString = convertMessageContentToString( |
| 463 | newUserMessage.message.content, |
| 464 | ); |
| 465 | |
| 466 | await handleRemoteMessage({ |
| 467 | remoteUrl, |
| 468 | messageContent: messageContentString, |
| 469 | }); |
| 470 | return; |
| 471 | } |
| 472 | |
| 473 | // Check if auto-compacting is needed BEFORE adding user message |
| 474 | const { currentChatHistory, currentCompactionIndex } = |
| 475 | await handleAutoCompaction({ |
| 476 | chatHistory, |
| 477 | model, |
| 478 | llmApi, |
| 479 | compactionIndex, |
| 480 | setChatHistory: setChatHistory, |
| 481 | setCompactionIndex, |
| 482 | }); |
| 483 | |
| 484 | // Add the formatted user message to history |
| 485 | const newHistory = [...currentChatHistory, newUserMessage]; |
| 486 | setChatHistory(newHistory); |
| 487 | |
| 488 | // Execute the streaming response |
| 489 | await executeStreamingResponse(newHistory, currentCompactionIndex); |
| 490 | }; |
| 491 | |
| 492 | const handleInterrupt = () => { |
| 493 | // In remote mode, send interrupt signal to server |
| 494 | if (isRemoteMode && remoteUrl) { |
| 495 | // Send a message to interrupt the remote server |
| 496 | fetch(`${remoteUrl}/message`, { |
| 497 | method: "POST", |
| 498 | headers: { |
| 499 | "Content-Type": "application/json", |
| 500 | }, |
| 501 | body: JSON.stringify({ message: "" }), // Empty message triggers interrupt |
| 502 | }).catch((error) => { |
| 503 | logger.error("Failed to send interrupt to remote server:", error); |
| 504 | }); |
| 505 | return; |
| 506 | } |
| 507 | |
| 508 | // Local mode: abort the controller |
| 509 | if (abortController && isWaitingForResponse) { |
| 510 | abortController.abort(); |
| 511 | |
| 512 | // Remove the last message if it's from assistant (partial response) |
| 513 | setChatHistory((current) => { |
| 514 | const lastMessage = current[current.length - 1]; |
| 515 | if ( |
| 516 | lastMessage?.message.role === "assistant" && |
| 517 | !lastMessage.toolCallStates?.length |
| 518 | ) { |
| 519 | return current.slice(0, -1); |
| 520 | } |
| 521 | return current; |
| 522 | }); |
| 523 | |
| 524 | setWasInterrupted(true); |
| 525 | setIsWaitingForResponse(false); |
| 526 | setResponseStartTime(null); |
| 527 | setInputMode(true); |
| 528 | } |
| 529 | }; |
| 530 | |
| 531 | const handleFileAttached = (filePath: string, content: string) => { |
| 532 | setAttachedFiles((prev) => [...prev, { path: filePath, content }]); |
| 533 | }; |
| 534 | |
| 535 | const resetChatHistory = async () => { |
| 536 | const newHistory = await initChatHistory( |
| 537 | false, // Don't resume when resetting |
| 538 | additionalRules, |
| 539 | ); |
| 540 | setChatHistory(newHistory); |
| 541 | }; |
| 542 | |
| 543 | const handleToolPermissionResponse = async ( |
| 544 | requestId: string, |
| 545 | approved: boolean, |
| 546 | createPolicy?: boolean, |
| 547 | stopStream?: boolean, |
| 548 | ) => { |
| 549 | // Capture the current permission request before clearing it |
| 550 | const currentRequest = activePermissionRequest; |
| 551 | |
| 552 | // Clear the active permission request |
| 553 | setActivePermissionRequest(null); |
| 554 | |
| 555 | // Handle policy creation if requested |
| 556 | if (approved && createPolicy && currentRequest) { |
| 557 | try { |
| 558 | const { generatePolicyRule, addPolicyToYaml } = await import( |
| 559 | "../../permissions/policyWriter.js" |
| 560 | ); |
| 561 | |
| 562 | const policyRule = generatePolicyRule( |
| 563 | currentRequest.toolName, |
| 564 | currentRequest.toolArgs, |
| 565 | ); |
| 566 | |
| 567 | await addPolicyToYaml(policyRule); |
| 568 | logger.debug(`Policy created: ${policyRule}`); |
| 569 | |
| 570 | // Reload permissions to pick up the new policy without requiring restart |
| 571 | await services.mode.getToolPermissionService().reloadPermissions(); |
| 572 | } catch (error) { |
| 573 | logger.error("Failed to create policy or reload permissions", { |
| 574 | error, |
| 575 | }); |
| 576 | // Continue with the approval even if policy creation/reload fails |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | // Send response to permission manager |
| 581 | // The streamChatResponse will handle showing the appropriate message |
| 582 | // through its normal onToolStart/onToolError flow |
| 583 | if (approved) { |
| 584 | toolPermissionManager.approveRequest(requestId); |
| 585 | } else { |
| 586 | toolPermissionManager.rejectRequest(requestId); |
| 587 | |
| 588 | // If this is a "stop stream" rejection, abort the current request |
| 589 | if (stopStream && abortController && isWaitingForResponse) { |
| 590 | abortController.abort(); |
| 591 | setChatHistory((prev) => [ |
| 592 | ...prev, |
| 593 | { |
| 594 | message: { |
| 595 | role: "system", |
| 596 | content: |
| 597 | "[Tool canceled - please tell Continue what to do differently]", |
| 598 | }, |
| 599 | contextItems: [], |
| 600 | }, |
| 601 | ]); |
| 602 | setIsWaitingForResponse(false); |
| 603 | setResponseStartTime(null); |
| 604 | setInputMode(true); |
| 605 | } |
| 606 | } |
| 607 | }; |
| 608 | |
| 609 | return { |
| 610 | chatHistory, |
| 611 | setChatHistory: setChatHistory, |
| 612 | isWaitingForResponse, |
| 613 | responseStartTime, |
| 614 | inputMode, |
| 615 | attachedFiles, |
| 616 | activePermissionRequest, |
| 617 | wasInterrupted, |
| 618 | handleUserMessage, |
| 619 | handleInterrupt, |
| 620 | handleFileAttached, |
| 621 | resetChatHistory, |
| 622 | handleToolPermissionResponse, |
| 623 | }; |
| 624 | } |