Elffuss BraidHub

kikocis/continue public

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