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