| 1 | import * as path from "node:path"; |
| 2 | |
| 3 | import type { ChatHistoryItem } from "core/index.js"; |
| 4 | import { getLastNPathParts } from "core/util/uri.js"; |
| 5 | import { v4 as uuidv4 } from "uuid"; |
| 6 | |
| 7 | import { logger } from "src/util/logger.js"; |
| 8 | |
| 9 | import { DEFAULT_SESSION_TITLE } from "../../constants/session.js"; |
| 10 | import { loadSession, startNewSession } from "../../session.js"; |
| 11 | import { posthogService } from "../../telemetry/posthogService.js"; |
| 12 | import { telemetryService } from "../../telemetry/telemetryService.js"; |
| 13 | |
| 14 | import { processImagePlaceholder } from "./useChat.imageProcessing.js"; |
| 15 | import { SlashCommandResult } from "./useChat.types.js"; |
| 16 | |
| 17 | /** |
| 18 | * Initialize chat history |
| 19 | */ |
| 20 | export async function initChatHistory( |
| 21 | resume?: boolean, |
| 22 | _additionalRules?: string[], |
| 23 | ): Promise<ChatHistoryItem[]> { |
| 24 | if (resume) { |
| 25 | const savedSession = loadSession(); |
| 26 | if (savedSession) { |
| 27 | return savedSession.history; |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // Start with empty history - system message will be injected when needed |
| 32 | return []; |
| 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 ProcessSlashCommandResultOptions { |
| 46 | result: SlashCommandResult; |
| 47 | chatHistory: ChatHistoryItem[]; |
| 48 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 49 | onShowConfigSelector: () => void; |
| 50 | onShowModelSelector?: () => void; |
| 51 | onShowUpdateSelector?: () => void; |
| 52 | onShowMCPSelector?: () => void; |
| 53 | onShowSessionSelector?: () => void; |
| 54 | onClear?: () => void; |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Process slash command results |
| 59 | */ |
| 60 | export function processSlashCommandResult({ |
| 61 | result, |
| 62 | chatHistory, |
| 63 | setChatHistory, |
| 64 | onShowConfigSelector, |
| 65 | onShowUpdateSelector, |
| 66 | onShowModelSelector, |
| 67 | onShowMCPSelector, |
| 68 | onShowSessionSelector, |
| 69 | onClear, |
| 70 | }: ProcessSlashCommandResultOptions): string | null { |
| 71 | if (result.exit) { |
| 72 | import("../../util/exit.js").then(({ gracefulExit }) => gracefulExit(0)); |
| 73 | } |
| 74 | |
| 75 | if (result.openMcpSelector) { |
| 76 | onShowMCPSelector?.(); |
| 77 | return null; |
| 78 | } |
| 79 | |
| 80 | if (result.openUpdateSelector) { |
| 81 | onShowUpdateSelector?.(); |
| 82 | return null; |
| 83 | } |
| 84 | |
| 85 | if (result.openConfigSelector) { |
| 86 | onShowConfigSelector(); |
| 87 | return null; |
| 88 | } |
| 89 | |
| 90 | if (result.openModelSelector && onShowModelSelector) { |
| 91 | onShowModelSelector(); |
| 92 | return null; |
| 93 | } |
| 94 | |
| 95 | if (result.openSessionSelector && onShowSessionSelector) { |
| 96 | onShowSessionSelector(); |
| 97 | return null; |
| 98 | } |
| 99 | |
| 100 | if (result.clear) { |
| 101 | const systemMessage = chatHistory.find( |
| 102 | (item) => item.message.role === "system", |
| 103 | ); |
| 104 | const newHistory = systemMessage ? [systemMessage] : []; |
| 105 | |
| 106 | // Start a new session with a new sessionId |
| 107 | startNewSession(newHistory); |
| 108 | |
| 109 | setChatHistory(newHistory); |
| 110 | |
| 111 | // Reset intro message state to show it again after clearing |
| 112 | if (onClear) { |
| 113 | onClear(); |
| 114 | } |
| 115 | |
| 116 | if (result.output) { |
| 117 | setChatHistory([ |
| 118 | { |
| 119 | message: { |
| 120 | role: "system", |
| 121 | content: result.output, |
| 122 | }, |
| 123 | contextItems: [], |
| 124 | }, |
| 125 | ]); |
| 126 | } |
| 127 | return null; |
| 128 | } |
| 129 | |
| 130 | if (result.output) { |
| 131 | setChatHistory((prev) => [ |
| 132 | ...prev, |
| 133 | { |
| 134 | message: { |
| 135 | role: "system", |
| 136 | content: result.output || "", |
| 137 | }, |
| 138 | contextItems: [], |
| 139 | }, |
| 140 | ]); |
| 141 | } |
| 142 | |
| 143 | return result.newInput || null; |
| 144 | } |
| 145 | |
| 146 | /** |
| 147 | * Format message with attached files and images - returns a complete ChatHistoryItem |
| 148 | */ |
| 149 | export async function formatMessageWithFiles( |
| 150 | message: string, |
| 151 | attachedFiles: Array<{ path: string; content: string }>, |
| 152 | imageMap?: Map<string, Buffer>, |
| 153 | ): Promise<import("core/index.js").ChatHistoryItem> { |
| 154 | // Convert attached files to context items |
| 155 | const contextItems = attachedFiles.map((file) => ({ |
| 156 | id: { |
| 157 | providerTitle: "file", |
| 158 | itemId: uuidv4(), |
| 159 | }, |
| 160 | content: file.content, |
| 161 | name: path.basename(file.path), |
| 162 | description: getLastNPathParts(file.path, 2), |
| 163 | uri: { |
| 164 | type: "file" as const, |
| 165 | value: `file://${file.path}`, |
| 166 | }, |
| 167 | })); |
| 168 | |
| 169 | // Process message content for images |
| 170 | let messageContent: import("core/index.js").MessageContent = message; |
| 171 | |
| 172 | if (imageMap && imageMap.size > 0) { |
| 173 | const messageParts: import("core/index.js").MessagePart[] = []; |
| 174 | let textContent = message; |
| 175 | |
| 176 | // Replace image placeholders with image parts |
| 177 | for (const [placeholder, originalImageBuffer] of imageMap.entries()) { |
| 178 | const result = await processImagePlaceholder( |
| 179 | placeholder, |
| 180 | originalImageBuffer, |
| 181 | textContent, |
| 182 | messageParts, |
| 183 | ); |
| 184 | textContent = result.textContent; |
| 185 | } |
| 186 | |
| 187 | // Add any remaining text |
| 188 | if (textContent) { |
| 189 | messageParts.push({ |
| 190 | type: "text", |
| 191 | text: textContent, |
| 192 | }); |
| 193 | } |
| 194 | |
| 195 | // Use message parts if we have images, otherwise keep as string |
| 196 | if (messageParts.length > 0) { |
| 197 | messageContent = messageParts; |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | return { |
| 202 | message: { |
| 203 | role: "user", |
| 204 | content: messageContent, |
| 205 | }, |
| 206 | contextItems, |
| 207 | }; |
| 208 | } |
| 209 | |
| 210 | /** |
| 211 | * Track telemetry for user message |
| 212 | */ |
| 213 | export function trackUserMessage(message: string, model?: any): void { |
| 214 | telemetryService.startActiveTime(); |
| 215 | telemetryService.logUserPrompt(message.length, message); |
| 216 | posthogService.capture("chat", { |
| 217 | model: model?.name, |
| 218 | provider: model?.provider, |
| 219 | }); |
| 220 | } |
| 221 | |
| 222 | interface HandleSpecialCommandsOptions { |
| 223 | message: string; |
| 224 | isRemoteMode: boolean; |
| 225 | remoteUrl?: string; |
| 226 | onShowConfigSelector: () => void; |
| 227 | exit: () => void; |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Handle special TUI commands |
| 232 | */ |
| 233 | export async function handleSpecialCommands({ |
| 234 | message, |
| 235 | isRemoteMode, |
| 236 | remoteUrl, |
| 237 | onShowConfigSelector, |
| 238 | exit, |
| 239 | }: HandleSpecialCommandsOptions): Promise<boolean> { |
| 240 | const trimmedMessage = message.trim(); |
| 241 | |
| 242 | // Special handling for /config command in TUI |
| 243 | if (trimmedMessage === "/config") { |
| 244 | handleConfigCommand(onShowConfigSelector); |
| 245 | return true; |
| 246 | } |
| 247 | |
| 248 | // Handle /exit command in remote mode |
| 249 | if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") { |
| 250 | const { handleRemoteExit } = await import("./useChat.remote.helpers.js"); |
| 251 | await handleRemoteExit(remoteUrl, exit); |
| 252 | return true; |
| 253 | } |
| 254 | |
| 255 | return false; |
| 256 | } |
| 257 | |
| 258 | /** |
| 259 | * Generate a title for the session based on the first assistant response |
| 260 | */ |
| 261 | export async function generateSessionTitle( |
| 262 | assistantResponse: string, |
| 263 | llmApi: any, |
| 264 | model: any, |
| 265 | currentSessionTitle?: string, |
| 266 | ): Promise<string | undefined> { |
| 267 | // Only generate title for untitled sessions |
| 268 | if (currentSessionTitle && currentSessionTitle !== DEFAULT_SESSION_TITLE) { |
| 269 | return undefined; |
| 270 | } |
| 271 | |
| 272 | if (!assistantResponse || !llmApi || !model) { |
| 273 | return undefined; |
| 274 | } |
| 275 | |
| 276 | try { |
| 277 | const { ChatDescriber } = await import("core/util/chatDescriber.js"); |
| 278 | const generatedTitle = await ChatDescriber.describeWithBaseLlmApi( |
| 279 | llmApi, |
| 280 | model, |
| 281 | assistantResponse, |
| 282 | ); |
| 283 | |
| 284 | logger.debug("Generated session title", { |
| 285 | original: currentSessionTitle, |
| 286 | generated: generatedTitle, |
| 287 | }); |
| 288 | |
| 289 | return generatedTitle; |
| 290 | } catch (error) { |
| 291 | logger.error("Failed to generate session title:", error); |
| 292 | return undefined; |
| 293 | } |
| 294 | } |