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