Elffuss BraidHub

kikocis/continue public

57d99ced5e24 · 14.1 KiBRawPermalink
1import { useApp } from "ink";
2import { ChatCompletionMessageParam } from "openai/resources.mjs";
3import { useEffect, useState } from "react";
4
5import { findCompactionIndex } from "../../compaction.js";
6import { toolPermissionManager } from "../../permissions/permissionManager.js";
7import { services } from "../../services/index.js";
8import { loadSession, saveSession } from "../../session.js";
9import { handleSlashCommands } from "../../slashCommands.js";
10import { telemetryService } from "../../telemetry/telemetryService.js";
11import { formatError } from "../../util/formatError.js";
12import { logger } from "../../util/logger.js";
13import { DisplayMessage } from "../types.js";
14
15import {
16 formatMessageWithFiles,
17 handleAutoCompaction,
18 handleCompactCommand,
19 handleSpecialCommands,
20 initChatHistory,
21 processSlashCommandResult,
22 trackUserMessage,
23} from "./useChat.helpers.js";
24import {
25 handleRemoteMessage,
26 setupRemotePolling,
27} from "./useChat.remote.helpers.js";
28import {
29 createStreamCallbacks,
30 executeStreaming,
31} from "./useChat.stream.helpers.js";
32import {
33 ActivePermissionRequest,
34 AttachedFile,
35 UseChatProps,
36} from "./useChat.types.js";
37
38export function useChat({
39 assistant,
40 model,
41 llmApi,
42 initialPrompt,
43 resume,
44 additionalRules,
45 additionalPrompts,
46 onShowConfigSelector,
47 onShowModelSelector,
48 onShowMCPSelector,
49 onShowSessionSelector,
50 onLoginPrompt: _onLoginPrompt,
51 onClear,
52 isRemoteMode = false,
53 remoteUrl,
54}: UseChatProps) {
55 const { exit } = useApp();
56
57 const [chatHistory, setChatHistory] = useState<ChatCompletionMessageParam[]>(
58 () => {
59 // In remote mode, start with empty history (will be populated by polling)
60 if (isRemoteMode) {
61 return [];
62 }
63
64 // Synchronously initialize chat history to prevent race conditions
65 // Load previous session if resume flag is used
66 // If no session loaded or not resuming, we'll need to add system message
67 // We can't make this async, so we'll handle it in the useEffect
68 return resume ? (loadSession() ?? []) : [];
69 },
70 );
71
72 const [messages, setMessages] = useState<DisplayMessage[]>(() => {
73 if (resume) {
74 const savedHistory = loadSession();
75 if (savedHistory) {
76 return savedHistory
77 .filter((msg) => msg.role !== "system")
78 .map((msg) => ({
79 role: msg.role,
80 content: msg.content as string,
81 }));
82 }
83 }
84 return [];
85 });
86
87 const [isWaitingForResponse, setIsWaitingForResponse] = useState(false);
88 const [responseStartTime, setResponseStartTime] = useState<number | null>(
89 null,
90 );
91 const [inputMode, setInputMode] = useState(true);
92 const [abortController, setAbortController] =
93 useState<AbortController | null>(null);
94 const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState(
95 // If we're resuming and found a saved session, we're already initialized
96 // If we're in remote mode, we're initialized (will be populated by polling)
97 isRemoteMode || (resume && loadSession() !== null),
98 );
99
100 // Capture initial rules to prevent re-initialization when rules change
101 const [initialRules] = useState(additionalRules);
102 const [attachedFiles, setAttachedFiles] = useState<AttachedFile[]>([]);
103 const [activePermissionRequest, setActivePermissionRequest] =
104 useState<ActivePermissionRequest | null>(null);
105 const [compactionIndex, setCompactionIndex] = useState<number | null>(() => {
106 // When resuming, check for compaction markers in the loaded history
107 if (resume) {
108 const savedHistory = loadSession();
109 if (savedHistory) {
110 return findCompactionIndex(savedHistory);
111 }
112 }
113 return null;
114 });
115
116 // Clean up abort controller on unmount
117 useEffect(() => {
118 return () => {
119 if (abortController && !abortController.signal.aborted) {
120 abortController.abort();
121 }
122 };
123 }, [abortController]);
124
125 // Remote mode polling
126 useEffect(() => {
127 if (!isRemoteMode || !remoteUrl || process.env.NODE_ENV === "test") return;
128
129 return setupRemotePolling({
130 remoteUrl,
131 setMessages,
132 setChatHistory,
133 setIsWaitingForResponse,
134 responseStartTime,
135 setResponseStartTime,
136 });
137 }, [isRemoteMode, remoteUrl, responseStartTime]);
138
139 useEffect(() => {
140 // Skip initialization in remote mode or if already initialized
141 if (isRemoteMode || isChatHistoryInitialized) return;
142
143 // Initialize chat history with system message only if we don't have a session
144 const initializeHistory = async () => {
145 // Only add system message if we don't have any messages yet
146 if (chatHistory.length === 0) {
147 const history = await initChatHistory(resume, initialRules);
148 setChatHistory(history);
149 }
150 setIsChatHistoryInitialized(true);
151 };
152
153 initializeHistory();
154 // Note: Using initialRules instead of additionalRules to prevent re-initialization
155 // when rules change during the conversation
156 }, [
157 isRemoteMode,
158 isChatHistoryInitialized,
159 chatHistory.length,
160 resume,
161 initialRules,
162 ]);
163
164 useEffect(() => {
165 // Only handle initial prompt after chat history is initialized
166 // This prevents race conditions where the prompt runs before system message is loaded
167 if (
168 (initialPrompt || (additionalPrompts && additionalPrompts.length > 0)) &&
169 isChatHistoryInitialized
170 ) {
171 const processPrompts = async () => {
172 const { processAndCombinePrompts } = await import(
173 "../../util/promptProcessor.js"
174 );
175 const finalMessage = await processAndCombinePrompts(
176 additionalPrompts,
177 initialPrompt,
178 );
179
180 if (finalMessage) {
181 await handleUserMessage(finalMessage);
182 }
183 };
184
185 processPrompts().catch(console.error);
186 }
187 }, [initialPrompt, additionalPrompts, isChatHistoryInitialized]);
188
189 const executeStreamingResponse = async (
190 newHistory: ChatCompletionMessageParam[],
191 currentCompactionIndex: number | null,
192 message: string,
193 ) => {
194 // Clean up previous abort controller if it exists
195 if (abortController && !abortController.signal.aborted) {
196 abortController.abort();
197 }
198
199 // Start streaming response
200 const controller = new AbortController();
201 setAbortController(controller);
202 setIsWaitingForResponse(true);
203 setResponseStartTime(Date.now());
204 setInputMode(false);
205 logger.debug("Starting chat response stream", {
206 messageLength: message.length,
207 historyLength: newHistory.length,
208 });
209
210 try {
211 const currentStreamingMessageRef = {
212 current: null as DisplayMessage | null,
213 };
214 const streamCallbacks = createStreamCallbacks(
215 { setMessages, setActivePermissionRequest },
216 currentStreamingMessageRef,
217 );
218
219 // Execute streaming chat response
220 await executeStreaming({
221 newHistory,
222 model,
223 llmApi,
224 controller,
225 streamCallbacks,
226 currentCompactionIndex,
227 });
228
229 if (
230 currentStreamingMessageRef.current &&
231 currentStreamingMessageRef.current.content
232 ) {
233 const messageContent = currentStreamingMessageRef.current.content;
234 setMessages((prev) => [
235 ...prev,
236 {
237 role: "assistant",
238 content: messageContent,
239 isStreaming: false,
240 },
241 ]);
242 }
243
244 // Update the chat history with the complete conversation after streaming
245 setChatHistory(newHistory);
246 logger.debug("Chat history updated", {
247 finalHistoryLength: newHistory.length,
248 });
249
250 // Save the updated history to session
251 logger.debug("Saving session", { historyLength: newHistory.length });
252 saveSession(newHistory);
253 logger.debug("Session saved");
254 } catch (error: any) {
255 const errorMessage = `Error: ${formatError(error)}`;
256 setMessages((prev) => [
257 ...prev,
258 {
259 role: "system",
260 content: errorMessage,
261 messageType: "system" as const,
262 },
263 ]);
264 } finally {
265 // Stop active time tracking
266 telemetryService.stopActiveTime();
267
268 setAbortController(null);
269 setIsWaitingForResponse(false);
270 setResponseStartTime(null);
271 setInputMode(true);
272 }
273 };
274
275 const handleUserMessage = async (message: string) => {
276 // Handle special commands
277 const handled = await handleSpecialCommands({
278 message,
279 isRemoteMode,
280 remoteUrl,
281 onShowConfigSelector,
282 exit,
283 setMessages,
284 });
285
286 if (handled) return;
287
288 // Handle slash commands (skip in remote mode except for /exit which we handled above)
289 if (!isRemoteMode && assistant) {
290 const commandResult = await handleSlashCommands(message, assistant);
291 if (commandResult) {
292 if (commandResult.compact) {
293 await handleCompactCommand({
294 chatHistory,
295 model,
296 llmApi,
297 setChatHistory,
298 setMessages,
299 setCompactionIndex,
300 });
301 return;
302 }
303
304 const newInput = processSlashCommandResult({
305 result: commandResult,
306 chatHistory,
307 setChatHistory,
308 setMessages,
309 exit,
310 onShowConfigSelector,
311 onShowModelSelector,
312 onShowMCPSelector,
313 onShowSessionSelector,
314 onClear,
315 });
316
317 if (newInput) {
318 message = newInput;
319 } else {
320 return;
321 }
322 }
323 }
324
325 // Track telemetry
326 trackUserMessage(message, model);
327
328 // Add user message to history and display
329 const messageContent = formatMessageWithFiles(message, attachedFiles);
330 if (attachedFiles.length > 0) {
331 setAttachedFiles([]);
332 }
333
334 // In remote mode, send message to server instead of processing locally
335 if (isRemoteMode && remoteUrl) {
336 await handleRemoteMessage({
337 remoteUrl,
338 messageContent,
339 setMessages,
340 });
341 return;
342 }
343
344 // Check if auto-compacting is needed BEFORE adding user message
345 const { currentChatHistory, currentCompactionIndex } =
346 await handleAutoCompaction({
347 chatHistory,
348 model,
349 llmApi,
350 compactionIndex,
351 setMessages,
352 setChatHistory,
353 setCompactionIndex,
354 });
355
356 // NOW add user message to history and UI
357 const newUserMessage: ChatCompletionMessageParam = {
358 role: "user",
359 content: messageContent,
360 };
361 const newHistory = [...currentChatHistory, newUserMessage];
362 setChatHistory(newHistory);
363 setMessages((prev) => [...prev, { role: "user", content: message }]);
364
365 // Execute the streaming response
366 await executeStreamingResponse(newHistory, currentCompactionIndex, message);
367 };
368
369 const handleInterrupt = () => {
370 // In remote mode, send interrupt signal to server
371 if (isRemoteMode && remoteUrl) {
372 // Send a message to interrupt the remote server
373 fetch(`${remoteUrl}/message`, {
374 method: "POST",
375 headers: {
376 "Content-Type": "application/json",
377 },
378 body: JSON.stringify({ message: "" }), // Empty message triggers interrupt
379 }).catch((error) => {
380 logger.error("Failed to send interrupt to remote server:", error);
381 });
382 return;
383 }
384
385 // Local mode: abort the controller
386 if (abortController && isWaitingForResponse) {
387 abortController.abort();
388 setMessages((prev) => [
389 ...prev,
390 {
391 role: "system",
392 content: "[Interrupted by user]",
393 messageType: "system" as const,
394 },
395 ]);
396 }
397 };
398
399 const handleFileAttached = (filePath: string, content: string) => {
400 setAttachedFiles((prev) => [...prev, { path: filePath, content }]);
401 };
402
403 const resetChatHistory = async () => {
404 const newHistory = await initChatHistory(
405 false, // Don't resume when resetting
406 additionalRules,
407 );
408 setChatHistory(newHistory);
409 setMessages([]);
410 };
411
412 const handleToolPermissionResponse = async (
413 requestId: string,
414 approved: boolean,
415 createPolicy?: boolean,
416 stopStream?: boolean,
417 ) => {
418 // Capture the current permission request before clearing it
419 const currentRequest = activePermissionRequest;
420
421 // Clear the active permission request
422 setActivePermissionRequest(null);
423
424 // Handle policy creation if requested
425 if (approved && createPolicy && currentRequest) {
426 try {
427 const { generatePolicyRule, addPolicyToYaml } = await import(
428 "../../permissions/policyWriter.js"
429 );
430
431 const policyRule = generatePolicyRule(
432 currentRequest.toolName,
433 currentRequest.toolArgs,
434 );
435
436 await addPolicyToYaml(policyRule);
437 logger.debug(`Policy created: ${policyRule}`);
438
439 // Reload permissions to pick up the new policy without requiring restart
440 await services.mode.getToolPermissionService().reloadPermissions();
441 } catch (error) {
442 logger.error("Failed to create policy or reload permissions", {
443 error,
444 });
445 // Continue with the approval even if policy creation/reload fails
446 }
447 }
448
449 // Send response to permission manager
450 // The streamChatResponse will handle showing the appropriate message
451 // through its normal onToolStart/onToolError flow
452 if (approved) {
453 toolPermissionManager.approveRequest(requestId);
454 } else {
455 toolPermissionManager.rejectRequest(requestId);
456
457 // If this is a "stop stream" rejection, abort the current request
458 if (stopStream && abortController && isWaitingForResponse) {
459 abortController.abort();
460 setMessages((prev) => [
461 ...prev,
462 {
463 role: "system",
464 content:
465 "[Tool canceled - please tell Continue what to do differently]",
466 messageType: "system" as const,
467 },
468 ]);
469 setIsWaitingForResponse(false);
470 setResponseStartTime(null);
471 setInputMode(true);
472 }
473 }
474 };
475
476 return {
477 messages,
478 setMessages,
479 chatHistory,
480 setChatHistory,
481 isWaitingForResponse,
482 responseStartTime,
483 inputMode,
484 attachedFiles,
485 activePermissionRequest,
486 handleUserMessage,
487 handleInterrupt,
488 handleFileAttached,
489 resetChatHistory,
490 handleToolPermissionResponse,
491 };
492}