Elffuss BraidHub

kikocis/continue public

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