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