| 1 | import { ChatCompletionMessageParam } from "openai/resources.mjs"; |
| 2 | |
| 3 | import { initializeChatHistory } from "../../commands/chat.js"; |
| 4 | import { compactChatHistory } from "../../compaction.js"; |
| 5 | import { loadSession, saveSession } from "../../session.js"; |
| 6 | import { posthogService } from "../../telemetry/posthogService.js"; |
| 7 | import { telemetryService } from "../../telemetry/telemetryService.js"; |
| 8 | import { formatError } from "../../util/formatError.js"; |
| 9 | import { logger } from "../../util/logger.js"; |
| 10 | import { shouldAutoCompact } from "../../util/tokenizer.js"; |
| 11 | import { DisplayMessage } from "../types.js"; |
| 12 | |
| 13 | import { SlashCommandResult } from "./useChat.types.js"; |
| 14 | |
| 15 | /** |
| 16 | * Initialize chat history with proper system message |
| 17 | */ |
| 18 | export 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 | */ |
| 39 | export function handleConfigCommand(onShowConfigSelector: () => void): void { |
| 40 | posthogService.capture("useSlashCommand", { |
| 41 | name: "config", |
| 42 | }); |
| 43 | onShowConfigSelector(); |
| 44 | } |
| 45 | |
| 46 | interface 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 | */ |
| 60 | export 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 | |
| 108 | interface 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 | } |
| 121 | |
| 122 | /** |
| 123 | * Process slash command results |
| 124 | */ |
| 125 | export function processSlashCommandResult({ |
| 126 | result, |
| 127 | chatHistory, |
| 128 | setChatHistory, |
| 129 | setMessages, |
| 130 | exit, |
| 131 | onShowConfigSelector, |
| 132 | onShowModelSelector, |
| 133 | onShowMCPSelector, |
| 134 | onShowSessionSelector, |
| 135 | }: ProcessSlashCommandResultOptions): string | null { |
| 136 | if (result.exit) { |
| 137 | exit(); |
| 138 | return null; |
| 139 | } |
| 140 | |
| 141 | if (result.openMcpSelector) { |
| 142 | onShowMCPSelector?.(); |
| 143 | return null; |
| 144 | } |
| 145 | |
| 146 | if (result.openConfigSelector) { |
| 147 | onShowConfigSelector(); |
| 148 | return null; |
| 149 | } |
| 150 | |
| 151 | if (result.openModelSelector && onShowModelSelector) { |
| 152 | onShowModelSelector(); |
| 153 | return null; |
| 154 | } |
| 155 | |
| 156 | if (result.openSessionSelector && onShowSessionSelector) { |
| 157 | onShowSessionSelector(); |
| 158 | return null; |
| 159 | } |
| 160 | |
| 161 | if (result.clear) { |
| 162 | const systemMessage = chatHistory.find((msg) => msg.role === "system"); |
| 163 | const newHistory = systemMessage ? [systemMessage] : []; |
| 164 | setChatHistory(newHistory); |
| 165 | setMessages([]); |
| 166 | |
| 167 | if (result.output) { |
| 168 | setMessages([ |
| 169 | { |
| 170 | role: "system", |
| 171 | content: result.output, |
| 172 | messageType: "system" as const, |
| 173 | }, |
| 174 | ]); |
| 175 | } |
| 176 | return null; |
| 177 | } |
| 178 | |
| 179 | if (result.output) { |
| 180 | setMessages((prev) => [ |
| 181 | ...prev, |
| 182 | { |
| 183 | role: "system" as const, |
| 184 | content: result.output || "", |
| 185 | messageType: "system" as const, |
| 186 | } as DisplayMessage, |
| 187 | ]); |
| 188 | } |
| 189 | |
| 190 | return result.newInput || null; |
| 191 | } |
| 192 | |
| 193 | /** |
| 194 | * Format message with attached files |
| 195 | */ |
| 196 | export function formatMessageWithFiles( |
| 197 | message: string, |
| 198 | attachedFiles: Array<{ path: string; content: string }>, |
| 199 | ): string { |
| 200 | if (attachedFiles.length === 0) { |
| 201 | return message; |
| 202 | } |
| 203 | |
| 204 | const fileContents = attachedFiles |
| 205 | .map((file) => `\n\n<file path="${file.path}">\n${file.content}\n</file>`) |
| 206 | .join(""); |
| 207 | |
| 208 | return message + fileContents; |
| 209 | } |
| 210 | |
| 211 | /** |
| 212 | * Track telemetry for user message |
| 213 | */ |
| 214 | export function trackUserMessage(message: string, model?: any): void { |
| 215 | telemetryService.startActiveTime(); |
| 216 | telemetryService.logUserPrompt(message.length, message); |
| 217 | posthogService.capture("chat", { |
| 218 | model: model?.name, |
| 219 | provider: model?.provider, |
| 220 | }); |
| 221 | } |
| 222 | |
| 223 | interface HandleSpecialCommandsOptions { |
| 224 | message: string; |
| 225 | isRemoteMode: boolean; |
| 226 | remoteUrl?: string; |
| 227 | onShowConfigSelector: () => void; |
| 228 | exit: () => void; |
| 229 | setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>; |
| 230 | } |
| 231 | |
| 232 | /** |
| 233 | * Handle special TUI commands |
| 234 | */ |
| 235 | export async function handleSpecialCommands({ |
| 236 | message, |
| 237 | isRemoteMode, |
| 238 | remoteUrl, |
| 239 | onShowConfigSelector, |
| 240 | exit, |
| 241 | setMessages, |
| 242 | }: HandleSpecialCommandsOptions): Promise<boolean> { |
| 243 | const trimmedMessage = message.trim(); |
| 244 | |
| 245 | // Special handling for /config command in TUI |
| 246 | if (trimmedMessage === "/config") { |
| 247 | handleConfigCommand(onShowConfigSelector); |
| 248 | return true; |
| 249 | } |
| 250 | |
| 251 | // Handle /exit command in remote mode |
| 252 | if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") { |
| 253 | const { handleRemoteExit } = await import("./useChat.remote.helpers.js"); |
| 254 | await handleRemoteExit(remoteUrl, setMessages, exit); |
| 255 | return true; |
| 256 | } |
| 257 | |
| 258 | return false; |
| 259 | } |
| 260 | |
| 261 | interface HandleAutoCompactionOptions { |
| 262 | chatHistory: ChatCompletionMessageParam[]; |
| 263 | model: any; |
| 264 | llmApi: any; |
| 265 | compactionIndex: number | null; |
| 266 | setMessages: React.Dispatch<React.SetStateAction<DisplayMessage[]>>; |
| 267 | setChatHistory: React.Dispatch< |
| 268 | React.SetStateAction<ChatCompletionMessageParam[]> |
| 269 | >; |
| 270 | setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>; |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | * Handle auto-compaction when approaching context limit |
| 275 | */ |
| 276 | export async function handleAutoCompaction({ |
| 277 | chatHistory, |
| 278 | model, |
| 279 | llmApi, |
| 280 | compactionIndex, |
| 281 | setMessages, |
| 282 | setChatHistory, |
| 283 | setCompactionIndex, |
| 284 | }: HandleAutoCompactionOptions): Promise<{ |
| 285 | currentChatHistory: ChatCompletionMessageParam[]; |
| 286 | currentCompactionIndex: number | null; |
| 287 | }> { |
| 288 | if (!model || !shouldAutoCompact(chatHistory, model)) { |
| 289 | return { |
| 290 | currentChatHistory: chatHistory, |
| 291 | currentCompactionIndex: compactionIndex, |
| 292 | }; |
| 293 | } |
| 294 | |
| 295 | logger.info("Auto-compacting triggered in TUI mode"); |
| 296 | |
| 297 | setMessages((prev) => [ |
| 298 | ...prev, |
| 299 | { |
| 300 | role: "system", |
| 301 | content: "Approaching context limit. Auto-compacting chat history...", |
| 302 | messageType: "system" as const, |
| 303 | }, |
| 304 | ]); |
| 305 | |
| 306 | try { |
| 307 | if (!llmApi) { |
| 308 | throw new Error("LLM API is not available for auto-compaction"); |
| 309 | } |
| 310 | |
| 311 | // Compact the history WITHOUT the current user message |
| 312 | const result = await compactChatHistory(chatHistory, model, llmApi); |
| 313 | |
| 314 | // Update state |
| 315 | setChatHistory(result.compactedHistory); |
| 316 | setCompactionIndex(result.compactionIndex); |
| 317 | |
| 318 | // Save the compacted session |
| 319 | saveSession(result.compactedHistory); |
| 320 | |
| 321 | setMessages((prev) => [ |
| 322 | ...prev, |
| 323 | { |
| 324 | role: "system", |
| 325 | content: "✓ Chat history auto-compacted successfully.", |
| 326 | messageType: "system" as const, |
| 327 | }, |
| 328 | ]); |
| 329 | |
| 330 | return { |
| 331 | currentChatHistory: result.compactedHistory, |
| 332 | currentCompactionIndex: result.compactionIndex, |
| 333 | }; |
| 334 | } catch (error: any) { |
| 335 | const errorMessage = `Auto-compaction error: ${formatError(error)}`; |
| 336 | logger.error(errorMessage); |
| 337 | |
| 338 | setMessages((prev) => [ |
| 339 | ...prev, |
| 340 | { |
| 341 | role: "system", |
| 342 | content: `Warning: ${errorMessage}. Continuing without compaction...`, |
| 343 | messageType: "system" as const, |
| 344 | }, |
| 345 | ]); |
| 346 | |
| 347 | // Continue without compaction on error |
| 348 | return { |
| 349 | currentChatHistory: chatHistory, |
| 350 | currentCompactionIndex: compactionIndex, |
| 351 | }; |
| 352 | } |
| 353 | } |