Elffuss BraidHub

kikocis/continue public

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