| 1 | import type { ChatHistoryItem, Session } from "core/index.js"; |
| 2 | |
| 3 | import { compactChatHistory } from "../../compaction.js"; |
| 4 | import { updateSessionHistory } from "../../session.js"; |
| 5 | import { formatError } from "../../util/formatError.js"; |
| 6 | import { logger } from "../../util/logger.js"; |
| 7 | import { shouldAutoCompact } from "../../util/tokenizer.js"; |
| 8 | |
| 9 | interface HandleCompactCommandOptions { |
| 10 | chatHistory: ChatHistoryItem[]; |
| 11 | model: any; |
| 12 | llmApi: any; |
| 13 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 14 | setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>; |
| 15 | currentSession: Session; |
| 16 | setCurrentSession: React.Dispatch<React.SetStateAction<Session>>; |
| 17 | setIsCompacting: (value: boolean) => void; |
| 18 | setCompactionStartTime: (time: number | null) => void; |
| 19 | setCompactionAbortController: (controller: AbortController | null) => void; |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * Handle compaction command |
| 24 | */ |
| 25 | export async function handleCompactCommand({ |
| 26 | chatHistory, |
| 27 | model, |
| 28 | llmApi, |
| 29 | setChatHistory, |
| 30 | setCompactionIndex, |
| 31 | currentSession, |
| 32 | setCurrentSession, |
| 33 | setIsCompacting, |
| 34 | setCompactionStartTime, |
| 35 | setCompactionAbortController, |
| 36 | }: HandleCompactCommandOptions): Promise<void> { |
| 37 | // Create abort controller for cancellation support |
| 38 | const compactionController = new AbortController(); |
| 39 | setCompactionAbortController(compactionController); |
| 40 | |
| 41 | // Start compaction status display |
| 42 | setIsCompacting(true); |
| 43 | setCompactionStartTime(Date.now()); |
| 44 | |
| 45 | try { |
| 46 | // Compact the chat history directly (already in unified format) with abort controller |
| 47 | const result = await compactChatHistory( |
| 48 | chatHistory, |
| 49 | model, |
| 50 | llmApi, |
| 51 | undefined, |
| 52 | compactionController, |
| 53 | ); |
| 54 | |
| 55 | // Check if operation was aborted before proceeding with success actions |
| 56 | if (compactionController.signal.aborted) { |
| 57 | return; |
| 58 | } |
| 59 | |
| 60 | // Replace chat history with compacted version |
| 61 | setChatHistory(result.compactedHistory); |
| 62 | setCompactionIndex(result.compactionIndex); |
| 63 | |
| 64 | // Save the compacted session |
| 65 | const updatedSession: Session = { |
| 66 | ...currentSession, |
| 67 | history: result.compactedHistory, |
| 68 | }; |
| 69 | updateSessionHistory(result.compactedHistory); |
| 70 | setCurrentSession(updatedSession); |
| 71 | |
| 72 | // Add success message to chat |
| 73 | setChatHistory((prev) => [ |
| 74 | ...prev, |
| 75 | { |
| 76 | message: { |
| 77 | role: "system", |
| 78 | content: "Chat history compacted successfully.", |
| 79 | }, |
| 80 | contextItems: [], |
| 81 | }, |
| 82 | ]); |
| 83 | } catch (error) { |
| 84 | // Check if the error was due to abortion |
| 85 | if (compactionController.signal.aborted) { |
| 86 | logger.info("Manual compaction was cancelled by user"); |
| 87 | setChatHistory((prev) => [ |
| 88 | ...prev, |
| 89 | { |
| 90 | message: { |
| 91 | role: "system", |
| 92 | content: "Compaction cancelled.", |
| 93 | }, |
| 94 | contextItems: [], |
| 95 | }, |
| 96 | ]); |
| 97 | } else { |
| 98 | logger.error("Compaction failed:", error); |
| 99 | setChatHistory((prev) => [ |
| 100 | ...prev, |
| 101 | { |
| 102 | message: { |
| 103 | role: "system", |
| 104 | content: `Compaction failed: ${formatError(error)}`, |
| 105 | }, |
| 106 | contextItems: [], |
| 107 | }, |
| 108 | ]); |
| 109 | } |
| 110 | } finally { |
| 111 | // Stop compaction status display |
| 112 | setIsCompacting(false); |
| 113 | setCompactionStartTime(null); |
| 114 | setCompactionAbortController(null); |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | interface HandleAutoCompactionOptions { |
| 119 | chatHistory: ChatHistoryItem[]; |
| 120 | model: any; |
| 121 | llmApi: any; |
| 122 | compactionIndex: number | null; |
| 123 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 124 | setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>; |
| 125 | abortController?: AbortController; |
| 126 | } |
| 127 | |
| 128 | /** |
| 129 | * Handle auto-compaction when approaching context limit - TUI wrapper |
| 130 | */ |
| 131 | export async function handleAutoCompaction({ |
| 132 | chatHistory, |
| 133 | model, |
| 134 | llmApi, |
| 135 | compactionIndex: _compactionIndex, |
| 136 | setChatHistory, |
| 137 | setCompactionIndex, |
| 138 | abortController, |
| 139 | }: HandleAutoCompactionOptions): Promise<{ |
| 140 | currentChatHistory: ChatHistoryItem[]; |
| 141 | currentCompactionIndex: number | null; |
| 142 | }> { |
| 143 | try { |
| 144 | // Check if auto-compaction is needed |
| 145 | // Check if auto-compaction is needed using ChatHistoryItem directly |
| 146 | if (!model || !shouldAutoCompact(chatHistory, model)) { |
| 147 | return { |
| 148 | currentChatHistory: chatHistory, |
| 149 | currentCompactionIndex: _compactionIndex, |
| 150 | }; |
| 151 | } |
| 152 | |
| 153 | logger.info("Auto-compaction triggered for TUI mode"); |
| 154 | |
| 155 | // Compact the unified history |
| 156 | const result = await compactChatHistory( |
| 157 | chatHistory, |
| 158 | model, |
| 159 | llmApi, |
| 160 | undefined, |
| 161 | abortController, |
| 162 | ); |
| 163 | |
| 164 | // Keep the system message and append the compaction summary |
| 165 | // This replaces the old messages with a summary to reduce context size |
| 166 | const systemMessage = chatHistory.find( |
| 167 | (item) => item.message.role === "system", |
| 168 | ); |
| 169 | |
| 170 | const compactedMessage: ChatHistoryItem = { |
| 171 | message: { |
| 172 | role: "assistant" as const, |
| 173 | content: result.compactionContent, |
| 174 | }, |
| 175 | contextItems: [], |
| 176 | conversationSummary: result.compactionContent, // Mark this as a summary |
| 177 | }; |
| 178 | |
| 179 | // Create new history with system message (if exists) and compaction summary |
| 180 | const updatedHistory: ChatHistoryItem[] = systemMessage |
| 181 | ? [systemMessage, compactedMessage] |
| 182 | : [compactedMessage]; |
| 183 | |
| 184 | // Add success message to the history that will be returned |
| 185 | const successMessage: ChatHistoryItem = { |
| 186 | message: { |
| 187 | role: "system", |
| 188 | content: "Chat history auto-compacted successfully.", |
| 189 | }, |
| 190 | contextItems: [], |
| 191 | }; |
| 192 | |
| 193 | const finalHistory = [...updatedHistory, successMessage]; |
| 194 | |
| 195 | setChatHistory(finalHistory); |
| 196 | setCompactionIndex(updatedHistory.length - 1); |
| 197 | |
| 198 | return { |
| 199 | currentChatHistory: finalHistory, |
| 200 | currentCompactionIndex: updatedHistory.length - 1, |
| 201 | }; |
| 202 | } catch (error) { |
| 203 | logger.error("Auto-compaction failed:", error); |
| 204 | |
| 205 | // Add error message |
| 206 | setChatHistory((prev) => [ |
| 207 | ...prev, |
| 208 | { |
| 209 | message: { |
| 210 | role: "system", |
| 211 | content: `Auto-compaction failed: ${formatError(error)}. Continuing without compaction...`, |
| 212 | }, |
| 213 | contextItems: [], |
| 214 | }, |
| 215 | ]); |
| 216 | |
| 217 | return { |
| 218 | currentChatHistory: chatHistory, |
| 219 | currentCompactionIndex: null, |
| 220 | }; |
| 221 | } |
| 222 | } |