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