Elffuss BraidHub

kikocis/continue public

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