Elffuss BraidHub

kikocis/continue public

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