Elffuss BraidHub

kikocis/continue public

8245094b4ec8 · 21.2 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 // Format message with attached files and images
489 logger.debug("Processing message with images", {
490 hasImages: !!(imageMap && imageMap.size > 0),
491 imageCount: imageMap?.size || 0,
492 });
493 const newUserMessage = await formatMessageWithFiles(
494 message,
495 attachedFiles,
496 imageMap,
497 );
498 logger.debug("Message formatted successfully");
499
500 if (attachedFiles.length > 0) {
501 setAttachedFiles([]);
502 }
503
504 // Check if auto-compacting is needed BEFORE adding user message
505 const { currentChatHistory, currentCompactionIndex } =
506 await handleAutoCompaction({
507 chatHistory,
508 model,
509 llmApi,
510 compactionIndex,
511 setChatHistory: setChatHistory,
512 setCompactionIndex,
513 });
514
515 // Add the formatted user message to history
516 const newHistory = [...currentChatHistory, newUserMessage];
517 setChatHistory(newHistory);
518
519 logger.debug("debug1 streaming started again");
520
521 // Execute the streaming response
522 await executeStreamingResponse(newHistory, currentCompactionIndex);
523 } else {
524 // For queued messages, chat history is already updated
525 // Check if auto-compacting is needed with current history
526 const { currentChatHistory, currentCompactionIndex } =
527 await handleAutoCompaction({
528 chatHistory,
529 model,
530 llmApi,
531 compactionIndex,
532 setChatHistory: setChatHistory,
533 setCompactionIndex,
534 });
535
536 // Execute the streaming response with the current history (which already includes the queued message)
537 await executeStreamingResponse(
538 currentChatHistory,
539 currentCompactionIndex,
540 );
541 }
542 };
543
544 const processQueuedMessage = async (
545 message: string,
546 imageMap?: Map<string, Buffer>,
547 ) => {
548 // For queued messages, we can reuse the core message processing logic
549 // by calling the internal processing function directly
550 await processMessage(message, imageMap, true);
551 };
552
553 const handleUserMessage = async (
554 message: string,
555 imageMap?: Map<string, Buffer>,
556 ) => {
557 // Check if this is a resume request (empty message after interruption)
558 if (await handleResumeRequest(message)) {
559 return;
560 }
561
562 // Clear interrupted state if user types a new message
563 if (wasInterrupted && message !== "") {
564 setWasInterrupted(false);
565 }
566
567 // Use the common message processing logic
568 await processMessage(message, imageMap, false);
569 };
570
571 const handleInterrupt = () => {
572 // In remote mode, send interrupt signal to server
573 if (isRemoteMode && remoteUrl) {
574 // Send a message to interrupt the remote server
575 fetch(`${remoteUrl}/message`, {
576 method: "POST",
577 headers: {
578 "Content-Type": "application/json",
579 },
580 body: JSON.stringify({ message: "" }), // Empty message triggers interrupt
581 }).catch((error) => {
582 logger.error("Failed to send interrupt to remote server:", error);
583 });
584 return;
585 }
586
587 // Local mode: abort the controller
588 if (abortController && isWaitingForResponse) {
589 abortController.abort();
590
591 // Remove the last message if it's from assistant (partial response)
592 setChatHistory((current) => {
593 const lastMessage = current[current.length - 1];
594 if (
595 lastMessage?.message.role === "assistant" &&
596 !lastMessage.toolCallStates?.length
597 ) {
598 return current.slice(0, -1);
599 }
600 return current;
601 });
602
603 setWasInterrupted(true);
604 setIsWaitingForResponse(false);
605 setResponseStartTime(null);
606 setInputMode(true);
607 }
608 };
609
610 const handleFileAttached = (filePath: string, content: string) => {
611 setAttachedFiles((prev) => [...prev, { path: filePath, content }]);
612 };
613
614 const resetChatHistory = async () => {
615 const newHistory = await initChatHistory(
616 false, // Don't resume when resetting
617 additionalRules,
618 );
619 setChatHistory(newHistory);
620 // Clear any queued messages when resetting chat
621 setQueuedMessages([]);
622 };
623
624 const handleToolPermissionResponse = async (
625 requestId: string,
626 approved: boolean,
627 createPolicy?: boolean,
628 stopStream?: boolean,
629 ) => {
630 // Capture the current permission request before clearing it
631 const currentRequest = activePermissionRequest;
632
633 // Clear the active permission request
634 setActivePermissionRequest(null);
635
636 // Handle policy creation if requested
637 if (approved && createPolicy && currentRequest) {
638 try {
639 const { generatePolicyRule, addPolicyToYaml } = await import(
640 "../../permissions/policyWriter.js"
641 );
642
643 const policyRule = generatePolicyRule(
644 currentRequest.toolName,
645 currentRequest.toolArgs,
646 );
647
648 await addPolicyToYaml(policyRule);
649 logger.debug(`Policy created: ${policyRule}`);
650
651 // Reload permissions to pick up the new policy without requiring restart
652 await services.mode.getToolPermissionService().reloadPermissions();
653 } catch (error) {
654 logger.error("Failed to create policy or reload permissions", {
655 error,
656 });
657 // Continue with the approval even if policy creation/reload fails
658 }
659 }
660
661 // Send response to permission manager
662 // The streamChatResponse will handle showing the appropriate message
663 // through its normal onToolStart/onToolError flow
664 if (approved) {
665 toolPermissionManager.approveRequest(requestId);
666 } else {
667 toolPermissionManager.rejectRequest(requestId);
668
669 // If this is a "stop stream" rejection, abort the current request
670 if (stopStream && abortController && isWaitingForResponse) {
671 abortController.abort();
672 setChatHistory((prev) => [
673 ...prev,
674 {
675 message: {
676 role: "system",
677 content:
678 "[Tool canceled - please tell Continue what to do differently]",
679 },
680 contextItems: [],
681 },
682 ]);
683 setIsWaitingForResponse(false);
684 setResponseStartTime(null);
685 setInputMode(true);
686 }
687 }
688 };
689
690 return {
691 chatHistory,
692 setChatHistory: setChatHistory,
693 isWaitingForResponse,
694 responseStartTime,
695 inputMode,
696 attachedFiles,
697 activePermissionRequest,
698 wasInterrupted,
699 queuedMessages,
700 handleUserMessage,
701 handleInterrupt,
702 handleFileAttached,
703 resetChatHistory,
704 handleToolPermissionResponse,
705 };
706}