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