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