Elffuss BraidHub

kikocis/continue public

dc42dd67a510 · 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 llmApi,
207 model,
208 });
209
210 // Execute streaming chat response
211 await executeStreaming({
212 chatHistory: newHistory,
213 model,
214 llmApi,
215 controller,
216 streamCallbacks,
217 currentCompactionIndex,
218 });
219
220 // Save the updated session with the latest chat history that includes the assistant's reply
221 // The streamCallbacks update setChatHistory during streaming, so we need to get the current state
222 setChatHistory((currentHistory) => {
223 logger.debug("Saving session", {
224 historyLength: currentHistory.length,
225 });
226 const updatedSession: Session = {
227 ...currentSession,
228 history: currentHistory,
229 };
230 updateSessionHistory(currentHistory);
231 setCurrentSession(updatedSession);
232 logger.debug("Session saved");
233 return currentHistory;
234 });
235 } catch (error: any) {
236 const errorMessage = `Error: ${formatError(error)}`;
237 setChatHistory((prev) => [
238 ...prev,
239 {
240 message: {
241 role: "system",
242 content: errorMessage,
243 },
244 contextItems: [],
245 },
246 ]);
247 } finally {
248 // Stop active time tracking
249 telemetryService.stopActiveTime();
250
251 setAbortController(null);
252 setIsWaitingForResponse(false);
253 setResponseStartTime(null);
254 setInputMode(true);
255 }
256 };
257
258 const handleUserMessage = async (message: string) => {
259 // Handle special commands
260 const handled = await handleSpecialCommands({
261 message,
262 isRemoteMode,
263 remoteUrl,
264 onShowConfigSelector,
265 exit,
266 setChatHistory,
267 });
268
269 if (handled) return;
270
271 // Handle slash commands (skip in remote mode except for /exit which we handled above)
272 if (!isRemoteMode && assistant) {
273 const commandResult = await handleSlashCommands(message, assistant);
274 if (commandResult) {
275 if (commandResult.compact) {
276 await handleCompactCommand({
277 chatHistory,
278 model,
279 llmApi,
280 setChatHistory,
281 setCompactionIndex,
282 currentSession,
283 setCurrentSession,
284 });
285 return;
286 }
287
288 const newInput = processSlashCommandResult({
289 result: commandResult,
290 chatHistory,
291 setChatHistory,
292 exit,
293 onShowConfigSelector,
294 onShowModelSelector,
295 onShowMCPSelector,
296 onShowSessionSelector,
297 onClear,
298 });
299
300 if (newInput) {
301 message = newInput;
302 } else {
303 return;
304 }
305 }
306 }
307
308 // Track telemetry
309 trackUserMessage(message, model);
310
311 // Add user message to history and display
312 const { messageText, contextItems } = formatMessageWithFiles(
313 message,
314 attachedFiles,
315 );
316 if (attachedFiles.length > 0) {
317 setAttachedFiles([]);
318 }
319
320 // In remote mode, send message to server instead of processing locally
321 if (isRemoteMode && remoteUrl) {
322 await handleRemoteMessage({
323 remoteUrl,
324 messageContent: messageText,
325 setChatHistory,
326 });
327 return;
328 }
329
330 // Check if auto-compacting is needed BEFORE adding user message
331 const { currentChatHistory, currentCompactionIndex } =
332 await handleAutoCompaction({
333 chatHistory,
334 model,
335 llmApi,
336 compactionIndex,
337 setChatHistory,
338 setCompactionIndex,
339 });
340
341 // NOW add user message to history with context items
342 const newUserMessage: ChatHistoryItem = {
343 message: {
344 role: "user",
345 content: messageText,
346 },
347 contextItems,
348 };
349 const newHistory = [...currentChatHistory, newUserMessage];
350 setChatHistory(newHistory);
351
352 // Execute the streaming response
353 await executeStreamingResponse(newHistory, currentCompactionIndex, message);
354 };
355
356 const handleInterrupt = () => {
357 // In remote mode, send interrupt signal to server
358 if (isRemoteMode && remoteUrl) {
359 // Send a message to interrupt the remote server
360 fetch(`${remoteUrl}/message`, {
361 method: "POST",
362 headers: {
363 "Content-Type": "application/json",
364 },
365 body: JSON.stringify({ message: "" }), // Empty message triggers interrupt
366 }).catch((error) => {
367 logger.error("Failed to send interrupt to remote server:", error);
368 });
369 return;
370 }
371
372 // Local mode: abort the controller
373 if (abortController && isWaitingForResponse) {
374 abortController.abort();
375 setChatHistory((prev) => [
376 ...prev,
377 {
378 message: {
379 role: "system",
380 content: "[Interrupted by user]",
381 },
382 contextItems: [],
383 },
384 ]);
385 }
386 };
387
388 const handleFileAttached = (filePath: string, content: string) => {
389 setAttachedFiles((prev) => [...prev, { path: filePath, content }]);
390 };
391
392 const resetChatHistory = async () => {
393 const newHistory = await initChatHistory(
394 false, // Don't resume when resetting
395 additionalRules,
396 );
397 setChatHistory(newHistory);
398 };
399
400 const handleToolPermissionResponse = async (
401 requestId: string,
402 approved: boolean,
403 createPolicy?: boolean,
404 stopStream?: boolean,
405 ) => {
406 // Capture the current permission request before clearing it
407 const currentRequest = activePermissionRequest;
408
409 // Clear the active permission request
410 setActivePermissionRequest(null);
411
412 // Handle policy creation if requested
413 if (approved && createPolicy && currentRequest) {
414 try {
415 const { generatePolicyRule, addPolicyToYaml } = await import(
416 "../../permissions/policyWriter.js"
417 );
418
419 const policyRule = generatePolicyRule(
420 currentRequest.toolName,
421 currentRequest.toolArgs,
422 );
423
424 await addPolicyToYaml(policyRule);
425 logger.debug(`Policy created: ${policyRule}`);
426
427 // Reload permissions to pick up the new policy without requiring restart
428 await services.mode.getToolPermissionService().reloadPermissions();
429 } catch (error) {
430 logger.error("Failed to create policy or reload permissions", {
431 error,
432 });
433 // Continue with the approval even if policy creation/reload fails
434 }
435 }
436
437 // Send response to permission manager
438 // The streamChatResponse will handle showing the appropriate message
439 // through its normal onToolStart/onToolError flow
440 if (approved) {
441 toolPermissionManager.approveRequest(requestId);
442 } else {
443 toolPermissionManager.rejectRequest(requestId);
444
445 // If this is a "stop stream" rejection, abort the current request
446 if (stopStream && abortController && isWaitingForResponse) {
447 abortController.abort();
448 setChatHistory((prev) => [
449 ...prev,
450 {
451 message: {
452 role: "system",
453 content:
454 "[Tool canceled - please tell Continue what to do differently]",
455 },
456 contextItems: [],
457 },
458 ]);
459 setIsWaitingForResponse(false);
460 setResponseStartTime(null);
461 setInputMode(true);
462 }
463 }
464 };
465
466 return {
467 chatHistory,
468 setChatHistory,
469 isWaitingForResponse,
470 responseStartTime,
471 inputMode,
472 attachedFiles,
473 activePermissionRequest,
474 handleUserMessage,
475 handleInterrupt,
476 handleFileAttached,
477 resetChatHistory,
478 handleToolPermissionResponse,
479 };
480}