Elffuss BraidHub

kikocis/continue public

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