Elffuss BraidHub

kikocis/continue public

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