| 1 | import * as path from "node:path"; |
| 2 | |
| 3 | import type { ChatHistoryItem, Session } from "core/index.js"; |
| 4 | import { getLastNPathParts } from "core/util/uri.js"; |
| 5 | import { v4 as uuidv4 } from "uuid"; |
| 6 | |
| 7 | import { initializeChatHistory } from "../../commands/chat.js"; |
| 8 | import { compactChatHistory } from "../../compaction.js"; |
| 9 | import { loadSession, updateSessionHistory } from "../../session.js"; |
| 10 | import { posthogService } from "../../telemetry/posthogService.js"; |
| 11 | import { telemetryService } from "../../telemetry/telemetryService.js"; |
| 12 | import { formatError } from "../../util/formatError.js"; |
| 13 | import { logger } from "../../util/logger.js"; |
| 14 | import { shouldAutoCompact } from "../../util/tokenizer.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<ChatHistoryItem[]> { |
| 25 | if (resume) { |
| 26 | const savedSession = loadSession(); |
| 27 | if (savedSession) { |
| 28 | return savedSession.history; |
| 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: ChatHistoryItem[]; |
| 51 | model: any; |
| 52 | llmApi: any; |
| 53 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 54 | setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>; |
| 55 | currentSession: Session; |
| 56 | setCurrentSession: React.Dispatch<React.SetStateAction<Session>>; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Handle compaction command |
| 61 | */ |
| 62 | export async function handleCompactCommand({ |
| 63 | chatHistory, |
| 64 | model, |
| 65 | llmApi, |
| 66 | setChatHistory, |
| 67 | setCompactionIndex, |
| 68 | currentSession, |
| 69 | setCurrentSession, |
| 70 | }: HandleCompactCommandOptions): Promise<void> { |
| 71 | // Add compacting message |
| 72 | setChatHistory((prev) => [ |
| 73 | ...prev, |
| 74 | { |
| 75 | message: { |
| 76 | role: "system", |
| 77 | content: "Compacting chat history...", |
| 78 | }, |
| 79 | contextItems: [], |
| 80 | }, |
| 81 | ]); |
| 82 | |
| 83 | try { |
| 84 | // Compact the chat history directly (already in unified format) |
| 85 | const result = await compactChatHistory(chatHistory, model, llmApi); |
| 86 | |
| 87 | // Replace chat history with compacted version |
| 88 | setChatHistory(result.compactedHistory); |
| 89 | setCompactionIndex(result.compactionIndex); |
| 90 | |
| 91 | // Save the compacted session |
| 92 | const updatedSession: Session = { |
| 93 | ...currentSession, |
| 94 | history: result.compactedHistory, |
| 95 | }; |
| 96 | updateSessionHistory(result.compactedHistory); |
| 97 | setCurrentSession(updatedSession); |
| 98 | |
| 99 | setChatHistory((prev) => [ |
| 100 | ...prev, |
| 101 | { |
| 102 | message: { |
| 103 | role: "system", |
| 104 | content: "Chat history compacted successfully.", |
| 105 | }, |
| 106 | contextItems: [], |
| 107 | }, |
| 108 | ]); |
| 109 | } catch (error) { |
| 110 | logger.error("Compaction failed:", error); |
| 111 | setChatHistory((prev) => [ |
| 112 | ...prev, |
| 113 | { |
| 114 | message: { |
| 115 | role: "system", |
| 116 | content: `Compaction failed: ${formatError(error)}`, |
| 117 | }, |
| 118 | contextItems: [], |
| 119 | }, |
| 120 | ]); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | interface ProcessSlashCommandResultOptions { |
| 125 | result: SlashCommandResult; |
| 126 | chatHistory: ChatHistoryItem[]; |
| 127 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 128 | exit: () => void; |
| 129 | onShowConfigSelector: () => void; |
| 130 | onShowModelSelector?: () => void; |
| 131 | onShowMCPSelector?: () => void; |
| 132 | onShowSessionSelector?: () => void; |
| 133 | onClear?: () => void; |
| 134 | } |
| 135 | |
| 136 | /** |
| 137 | * Process slash command results |
| 138 | */ |
| 139 | export function processSlashCommandResult({ |
| 140 | result, |
| 141 | chatHistory, |
| 142 | setChatHistory, |
| 143 | exit, |
| 144 | onShowConfigSelector, |
| 145 | onShowModelSelector, |
| 146 | onShowMCPSelector, |
| 147 | onShowSessionSelector, |
| 148 | onClear, |
| 149 | }: ProcessSlashCommandResultOptions): string | null { |
| 150 | if (result.exit) { |
| 151 | exit(); |
| 152 | return null; |
| 153 | } |
| 154 | |
| 155 | if (result.openMcpSelector) { |
| 156 | onShowMCPSelector?.(); |
| 157 | return null; |
| 158 | } |
| 159 | |
| 160 | if (result.openConfigSelector) { |
| 161 | onShowConfigSelector(); |
| 162 | return null; |
| 163 | } |
| 164 | |
| 165 | if (result.openModelSelector && onShowModelSelector) { |
| 166 | onShowModelSelector(); |
| 167 | return null; |
| 168 | } |
| 169 | |
| 170 | if (result.openSessionSelector && onShowSessionSelector) { |
| 171 | onShowSessionSelector(); |
| 172 | return null; |
| 173 | } |
| 174 | |
| 175 | if (result.clear) { |
| 176 | const systemMessage = chatHistory.find( |
| 177 | (item) => item.message.role === "system", |
| 178 | ); |
| 179 | const newHistory = systemMessage ? [systemMessage] : []; |
| 180 | setChatHistory(newHistory); |
| 181 | |
| 182 | // Reset intro message state to show it again after clearing |
| 183 | if (onClear) { |
| 184 | onClear(); |
| 185 | } |
| 186 | |
| 187 | if (result.output) { |
| 188 | setChatHistory([ |
| 189 | { |
| 190 | message: { |
| 191 | role: "system", |
| 192 | content: result.output, |
| 193 | }, |
| 194 | contextItems: [], |
| 195 | }, |
| 196 | ]); |
| 197 | } |
| 198 | return null; |
| 199 | } |
| 200 | |
| 201 | if (result.output) { |
| 202 | setChatHistory((prev) => [ |
| 203 | ...prev, |
| 204 | { |
| 205 | message: { |
| 206 | role: "system", |
| 207 | content: result.output || "", |
| 208 | }, |
| 209 | contextItems: [], |
| 210 | }, |
| 211 | ]); |
| 212 | } |
| 213 | |
| 214 | return result.newInput || null; |
| 215 | } |
| 216 | |
| 217 | /** |
| 218 | * Format message with attached files - returns message text and context items separately |
| 219 | */ |
| 220 | export function formatMessageWithFiles( |
| 221 | message: string, |
| 222 | attachedFiles: Array<{ path: string; content: string }>, |
| 223 | ): { |
| 224 | messageText: string; |
| 225 | contextItems: import("core/index.js").ContextItemWithId[]; |
| 226 | } { |
| 227 | if (attachedFiles.length === 0) { |
| 228 | return { messageText: message, contextItems: [] }; |
| 229 | } |
| 230 | |
| 231 | // Convert attached files to context items |
| 232 | const contextItems = attachedFiles.map((file) => ({ |
| 233 | id: { |
| 234 | providerTitle: "file", |
| 235 | itemId: uuidv4(), |
| 236 | }, |
| 237 | content: file.content, |
| 238 | name: path.basename(file.path), |
| 239 | description: getLastNPathParts(file.path, 2), |
| 240 | uri: { |
| 241 | type: "file" as const, |
| 242 | value: `file://${file.path}`, |
| 243 | }, |
| 244 | })); |
| 245 | |
| 246 | // Keep the original message text unchanged (preserving @filename references) |
| 247 | return { messageText: message, contextItems }; |
| 248 | } |
| 249 | |
| 250 | /** |
| 251 | * Track telemetry for user message |
| 252 | */ |
| 253 | export function trackUserMessage(message: string, model?: any): void { |
| 254 | telemetryService.startActiveTime(); |
| 255 | telemetryService.logUserPrompt(message.length, message); |
| 256 | posthogService.capture("chat", { |
| 257 | model: model?.name, |
| 258 | provider: model?.provider, |
| 259 | }); |
| 260 | } |
| 261 | |
| 262 | interface HandleSpecialCommandsOptions { |
| 263 | message: string; |
| 264 | isRemoteMode: boolean; |
| 265 | remoteUrl?: string; |
| 266 | onShowConfigSelector: () => void; |
| 267 | exit: () => void; |
| 268 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 269 | } |
| 270 | |
| 271 | /** |
| 272 | * Handle special TUI commands |
| 273 | */ |
| 274 | export async function handleSpecialCommands({ |
| 275 | message, |
| 276 | isRemoteMode, |
| 277 | remoteUrl, |
| 278 | onShowConfigSelector, |
| 279 | exit, |
| 280 | setChatHistory, |
| 281 | }: HandleSpecialCommandsOptions): Promise<boolean> { |
| 282 | const trimmedMessage = message.trim(); |
| 283 | |
| 284 | // Special handling for /config command in TUI |
| 285 | if (trimmedMessage === "/config") { |
| 286 | handleConfigCommand(onShowConfigSelector); |
| 287 | return true; |
| 288 | } |
| 289 | |
| 290 | // Handle /exit command in remote mode |
| 291 | if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") { |
| 292 | const { handleRemoteExit } = await import("./useChat.remote.helpers.js"); |
| 293 | await handleRemoteExit(remoteUrl, setChatHistory, exit); |
| 294 | return true; |
| 295 | } |
| 296 | |
| 297 | return false; |
| 298 | } |
| 299 | |
| 300 | interface HandleAutoCompactionOptions { |
| 301 | chatHistory: ChatHistoryItem[]; |
| 302 | model: any; |
| 303 | llmApi: any; |
| 304 | compactionIndex: number | null; |
| 305 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 306 | setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>; |
| 307 | } |
| 308 | |
| 309 | /** |
| 310 | * Handle auto-compaction when approaching context limit - TUI wrapper |
| 311 | */ |
| 312 | export async function handleAutoCompaction({ |
| 313 | chatHistory, |
| 314 | model, |
| 315 | llmApi, |
| 316 | compactionIndex: _compactionIndex, |
| 317 | setChatHistory, |
| 318 | setCompactionIndex, |
| 319 | }: HandleAutoCompactionOptions): Promise<{ |
| 320 | currentChatHistory: ChatHistoryItem[]; |
| 321 | currentCompactionIndex: number | null; |
| 322 | }> { |
| 323 | try { |
| 324 | // Check if auto-compaction is needed |
| 325 | // Check if auto-compaction is needed using ChatHistoryItem directly |
| 326 | if (!model || !shouldAutoCompact(chatHistory, model)) { |
| 327 | return { |
| 328 | currentChatHistory: chatHistory, |
| 329 | currentCompactionIndex: _compactionIndex, |
| 330 | }; |
| 331 | } |
| 332 | |
| 333 | logger.info("Auto-compaction triggered for TUI mode"); |
| 334 | |
| 335 | // Add compacting message |
| 336 | setChatHistory((prev) => [ |
| 337 | ...prev, |
| 338 | { |
| 339 | message: { |
| 340 | role: "system", |
| 341 | content: "Auto-compacting chat history...", |
| 342 | }, |
| 343 | contextItems: [], |
| 344 | }, |
| 345 | ]); |
| 346 | |
| 347 | // Compact the unified history |
| 348 | const result = await compactChatHistory(chatHistory, model, llmApi); |
| 349 | |
| 350 | // Keep the system message and append the compaction summary |
| 351 | // This replaces the old messages with a summary to reduce context size |
| 352 | const systemMessage = chatHistory.find( |
| 353 | (item) => item.message.role === "system", |
| 354 | ); |
| 355 | |
| 356 | const compactedMessage: ChatHistoryItem = { |
| 357 | message: { |
| 358 | role: "assistant" as const, |
| 359 | content: result.compactionContent, |
| 360 | }, |
| 361 | contextItems: [], |
| 362 | conversationSummary: result.compactionContent, // Mark this as a summary |
| 363 | }; |
| 364 | |
| 365 | // Create new history with system message (if exists) and compaction summary |
| 366 | const updatedHistory: ChatHistoryItem[] = systemMessage |
| 367 | ? [systemMessage, compactedMessage] |
| 368 | : [compactedMessage]; |
| 369 | |
| 370 | setChatHistory(updatedHistory); |
| 371 | setCompactionIndex(updatedHistory.length - 1); |
| 372 | |
| 373 | // Add success message |
| 374 | setChatHistory((prev) => [ |
| 375 | ...prev, |
| 376 | { |
| 377 | message: { |
| 378 | role: "system", |
| 379 | content: "✓ Chat history auto-compacted successfully.", |
| 380 | }, |
| 381 | contextItems: [], |
| 382 | }, |
| 383 | ]); |
| 384 | |
| 385 | return { |
| 386 | currentChatHistory: updatedHistory, |
| 387 | currentCompactionIndex: updatedHistory.length - 1, |
| 388 | }; |
| 389 | } catch (error) { |
| 390 | logger.error("Auto-compaction failed:", error); |
| 391 | |
| 392 | // Add error message |
| 393 | setChatHistory((prev) => [ |
| 394 | ...prev, |
| 395 | { |
| 396 | message: { |
| 397 | role: "system", |
| 398 | content: `Auto-compaction failed: ${formatError(error)}. Continuing without compaction...`, |
| 399 | }, |
| 400 | contextItems: [], |
| 401 | }, |
| 402 | ]); |
| 403 | |
| 404 | return { |
| 405 | currentChatHistory: chatHistory, |
| 406 | currentCompactionIndex: null, |
| 407 | }; |
| 408 | } |
| 409 | } |