Elffuss BraidHub

kikocis/continue public

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