Elffuss BraidHub

kikocis/continue public

a6ac770a1291 · 8.7 KiBRawPermalink
1import { ChatCompletionMessageParam } from "openai/resources.mjs";
2
3import { initializeChatHistory } from "../../commands/chat.js";
4import { compactChatHistory } from "../../compaction.js";
5import { loadSession, saveSession } from "../../session.js";
6import { posthogService } from "../../telemetry/posthogService.js";
7import { telemetryService } from "../../telemetry/telemetryService.js";
8import { formatError } from "../../util/formatError.js";
9import { logger } from "../../util/logger.js";
10import { shouldAutoCompact } from "../../util/tokenizer.js";
11import { DisplayMessage } from "../types.js";
12
13import { SlashCommandResult } from "./useChat.types.js";
14
15/**
16 * Initialize chat history with proper system message
17 */
18export async function initChatHistory(
19 resume?: boolean,
20 additionalRules?: string[],
21): Promise<ChatCompletionMessageParam[]> {
22 if (resume) {
23 const savedHistory = loadSession();
24 if (savedHistory) {
25 return savedHistory;
26 }
27 }
28
29 const history = await initializeChatHistory({
30 resume,
31 rule: additionalRules,
32 });
33 return history;
34}
35
36/**
37 * Handle /config command
38 */
39export function handleConfigCommand(onShowConfigSelector: () => void): void {
40 posthogService.capture("useSlashCommand", {
41 name: "config",
42 });
43 onShowConfigSelector();
44}
45
46interface HandleCompactCommandOptions {
47 chatHistory: ChatCompletionMessageParam[];
48 model: any;
49 llmApi: any;
50 setChatHistory: React.Dispatch<
51 React.SetStateAction<ChatCompletionMessageParam[]>
52 >;
53 setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
54 setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
55}
56
57/**
58 * Handle compaction command
59 */
60export async function handleCompactCommand({
61 chatHistory,
62 model,
63 llmApi,
64 setChatHistory,
65 setMessages,
66 setCompactionIndex,
67}: HandleCompactCommandOptions): Promise<void> {
68 setMessages((prev) => [
69 ...prev,
70 {
71 role: "system",
72 content: "Compacting chat history...",
73 messageType: "system" as const,
74 },
75 ]);
76
77 try {
78 const result = await compactChatHistory(chatHistory, model, llmApi);
79
80 // Replace chat history with compacted version
81 setChatHistory(result.compactedHistory);
82 setCompactionIndex(result.compactionIndex);
83
84 // Save the compacted session
85 saveSession(result.compactedHistory);
86
87 setMessages((prev) => [
88 ...prev,
89 {
90 role: "system",
91 content: "Chat history compacted successfully.",
92 messageType: "system" as const,
93 },
94 ]);
95 } catch (error) {
96 logger.error("Compaction failed:", error);
97 setMessages((prev) => [
98 ...prev,
99 {
100 role: "system",
101 content: `Compaction failed: ${formatError(error)}`,
102 messageType: "system" as const,
103 },
104 ]);
105 }
106}
107
108interface ProcessSlashCommandResultOptions {
109 result: SlashCommandResult;
110 chatHistory: ChatCompletionMessageParam[];
111 setChatHistory: React.Dispatch<
112 React.SetStateAction<ChatCompletionMessageParam[]>
113 >;
114 setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
115 exit: () => void;
116 onShowConfigSelector: () => void;
117 onShowModelSelector?: () => void;
118 onShowMCPSelector?: () => void;
119 onShowSessionSelector?: () => void;
120 onClear?: () => void;
121}
122
123/**
124 * Process slash command results
125 */
126export function processSlashCommandResult({
127 result,
128 chatHistory,
129 setChatHistory,
130 setMessages,
131 exit,
132 onShowConfigSelector,
133 onShowModelSelector,
134 onShowMCPSelector,
135 onShowSessionSelector,
136 onClear,
137}: ProcessSlashCommandResultOptions): string | null {
138 if (result.exit) {
139 exit();
140 return null;
141 }
142
143 if (result.openMcpSelector) {
144 onShowMCPSelector?.();
145 return null;
146 }
147
148 if (result.openConfigSelector) {
149 onShowConfigSelector();
150 return null;
151 }
152
153 if (result.openModelSelector && onShowModelSelector) {
154 onShowModelSelector();
155 return null;
156 }
157
158 if (result.openSessionSelector && onShowSessionSelector) {
159 onShowSessionSelector();
160 return null;
161 }
162
163 if (result.clear) {
164 const systemMessage = chatHistory.find((msg) => msg.role === "system");
165 const newHistory = systemMessage ? [systemMessage] : [];
166 setChatHistory(newHistory);
167 setMessages([]);
168
169 // Reset intro message state to show it again after clearing
170 if (onClear) {
171 onClear();
172 }
173
174 if (result.output) {
175 setMessages([
176 {
177 role: "system",
178 content: result.output,
179 messageType: "system" as const,
180 },
181 ]);
182 }
183 return null;
184 }
185
186 if (result.output) {
187 setMessages((prev) => [
188 ...prev,
189 {
190 role: "system" as const,
191 content: result.output || "",
192 messageType: "system" as const,
193 } as DisplayMessage,
194 ]);
195 }
196
197 return result.newInput || null;
198}
199
200/**
201 * Format message with attached files
202 */
203export function formatMessageWithFiles(
204 message: string,
205 attachedFiles: Array<{ path: string; content: string }>,
206): string {
207 if (attachedFiles.length === 0) {
208 return message;
209 }
210
211 const fileContents = attachedFiles
212 .map((file) => `\n\n<file path="${file.path}">\n${file.content}\n</file>`)
213 .join("");
214
215 return message + fileContents;
216}
217
218/**
219 * Track telemetry for user message
220 */
221export function trackUserMessage(message: string, model?: any): void {
222 telemetryService.startActiveTime();
223 telemetryService.logUserPrompt(message.length, message);
224 posthogService.capture("chat", {
225 model: model?.name,
226 provider: model?.provider,
227 });
228}
229
230interface HandleSpecialCommandsOptions {
231 message: string;
232 isRemoteMode: boolean;
233 remoteUrl?: string;
234 onShowConfigSelector: () => void;
235 exit: () => void;
236 setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
237}
238
239/**
240 * Handle special TUI commands
241 */
242export async function handleSpecialCommands({
243 message,
244 isRemoteMode,
245 remoteUrl,
246 onShowConfigSelector,
247 exit,
248 setMessages,
249}: HandleSpecialCommandsOptions): Promise<boolean> {
250 const trimmedMessage = message.trim();
251
252 // Special handling for /config command in TUI
253 if (trimmedMessage === "/config") {
254 handleConfigCommand(onShowConfigSelector);
255 return true;
256 }
257
258 // Handle /exit command in remote mode
259 if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") {
260 const { handleRemoteExit } = await import("./useChat.remote.helpers.js");
261 await handleRemoteExit(remoteUrl, setMessages, exit);
262 return true;
263 }
264
265 return false;
266}
267
268interface HandleAutoCompactionOptions {
269 chatHistory: ChatCompletionMessageParam[];
270 model: any;
271 llmApi: any;
272 compactionIndex: number | null;
273 setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>;
274 setChatHistory: React.Dispatch<
275 React.SetStateAction<ChatCompletionMessageParam[]>
276 >;
277 setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
278}
279
280/**
281 * Handle auto-compaction when approaching context limit
282 */
283export async function handleAutoCompaction({
284 chatHistory,
285 model,
286 llmApi,
287 compactionIndex,
288 setMessages,
289 setChatHistory,
290 setCompactionIndex,
291}: HandleAutoCompactionOptions): Promise<{
292 currentChatHistory: ChatCompletionMessageParam[];
293 currentCompactionIndex: number | null;
294}> {
295 if (!model || !shouldAutoCompact(chatHistory, model)) {
296 return {
297 currentChatHistory: chatHistory,
298 currentCompactionIndex: compactionIndex,
299 };
300 }
301
302 logger.info("Auto-compacting triggered in TUI mode");
303
304 setMessages((prev) => [
305 ...prev,
306 {
307 role: "system",
308 content: "Approaching context limit. Auto-compacting chat history...",
309 messageType: "system" as const,
310 },
311 ]);
312
313 try {
314 if (!llmApi) {
315 throw new Error("LLM API is not available for auto-compaction");
316 }
317
318 // Compact the history WITHOUT the current user message
319 const result = await compactChatHistory(chatHistory, model, llmApi);
320
321 // Update state
322 setChatHistory(result.compactedHistory);
323 setCompactionIndex(result.compactionIndex);
324
325 // Save the compacted session
326 saveSession(result.compactedHistory);
327
328 setMessages((prev) => [
329 ...prev,
330 {
331 role: "system",
332 content: "✓ Chat history auto-compacted successfully.",
333 messageType: "system" as const,
334 },
335 ]);
336
337 return {
338 currentChatHistory: result.compactedHistory,
339 currentCompactionIndex: result.compactionIndex,
340 };
341 } catch (error: any) {
342 const errorMessage = `Auto-compaction error: ${formatError(error)}`;
343 logger.error(errorMessage);
344
345 setMessages((prev) => [
346 ...prev,
347 {
348 role: "system",
349 content: `Warning: ${errorMessage}. Continuing without compaction...`,
350 messageType: "system" as const,
351 },
352 ]);
353
354 // Continue without compaction on error
355 return {
356 currentChatHistory: chatHistory,
357 currentCompactionIndex: compactionIndex,
358 };
359 }
360}