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