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