| 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.diffContent) { |
| 131 | setChatHistory((prev) => [ |
| 132 | ...prev, |
| 133 | { |
| 134 | message: { |
| 135 | role: "system", |
| 136 | content: `Diff:\n${result.diffContent}`, |
| 137 | }, |
| 138 | contextItems: [], |
| 139 | }, |
| 140 | ]); |
| 141 | return null; |
| 142 | } else if (result.output) { |
| 143 | setChatHistory((prev) => [ |
| 144 | ...prev, |
| 145 | { |
| 146 | message: { |
| 147 | role: "system", |
| 148 | content: result.output || "", |
| 149 | }, |
| 150 | contextItems: [], |
| 151 | }, |
| 152 | ]); |
| 153 | return null; |
| 154 | } |
| 155 | |
| 156 | return result.newInput || null; |
| 157 | } |
| 158 | |
| 159 | /** |
| 160 | * Format message with attached files and images - returns a complete ChatHistoryItem |
| 161 | */ |
| 162 | export async function formatMessageWithFiles( |
| 163 | message: string, |
| 164 | attachedFiles: Array<{ path: string; content: string }>, |
| 165 | imageMap?: Map<string, Buffer>, |
| 166 | ): Promise<import("core/index.js").ChatHistoryItem> { |
| 167 | // Convert attached files to context items |
| 168 | const contextItems = attachedFiles.map((file) => ({ |
| 169 | id: { |
| 170 | providerTitle: "file", |
| 171 | itemId: uuidv4(), |
| 172 | }, |
| 173 | content: file.content, |
| 174 | name: path.basename(file.path), |
| 175 | description: getLastNPathParts(file.path, 2), |
| 176 | uri: { |
| 177 | type: "file" as const, |
| 178 | value: `file://${file.path}`, |
| 179 | }, |
| 180 | })); |
| 181 | |
| 182 | // Process message content for images |
| 183 | let messageContent: import("core/index.js").MessageContent = message; |
| 184 | |
| 185 | if (imageMap && imageMap.size > 0) { |
| 186 | const messageParts: import("core/index.js").MessagePart[] = []; |
| 187 | let textContent = message; |
| 188 | |
| 189 | // Replace image placeholders with image parts |
| 190 | for (const [placeholder, originalImageBuffer] of imageMap.entries()) { |
| 191 | const result = await processImagePlaceholder( |
| 192 | placeholder, |
| 193 | originalImageBuffer, |
| 194 | textContent, |
| 195 | messageParts, |
| 196 | ); |
| 197 | textContent = result.textContent; |
| 198 | } |
| 199 | |
| 200 | // Add any remaining text |
| 201 | if (textContent) { |
| 202 | messageParts.push({ |
| 203 | type: "text", |
| 204 | text: textContent, |
| 205 | }); |
| 206 | } |
| 207 | |
| 208 | // Use message parts if we have images, otherwise keep as string |
| 209 | if (messageParts.length > 0) { |
| 210 | messageContent = messageParts; |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | return { |
| 215 | message: { |
| 216 | role: "user", |
| 217 | content: messageContent, |
| 218 | }, |
| 219 | contextItems, |
| 220 | }; |
| 221 | } |
| 222 | |
| 223 | /** |
| 224 | * Track telemetry for user message |
| 225 | */ |
| 226 | export function trackUserMessage(message: string, model?: any): void { |
| 227 | telemetryService.startActiveTime(); |
| 228 | telemetryService.logUserPrompt(message.length, message); |
| 229 | posthogService.capture("chat", { |
| 230 | model: model?.name, |
| 231 | provider: model?.provider, |
| 232 | }); |
| 233 | } |
| 234 | |
| 235 | interface HandleSpecialCommandsOptions { |
| 236 | message: string; |
| 237 | isRemoteMode: boolean; |
| 238 | remoteUrl?: string; |
| 239 | onShowConfigSelector: () => void; |
| 240 | exit: () => void; |
| 241 | onShowDiff?: (diffContent: string) => void; |
| 242 | onShowStatusMessage?: (message: string) => void; |
| 243 | } |
| 244 | |
| 245 | /** |
| 246 | * Handle /diff command in remote mode |
| 247 | */ |
| 248 | async function handleRemoteDiffCommand( |
| 249 | remoteUrl: string, |
| 250 | onShowDiff?: (diffContent: string) => void, |
| 251 | ): Promise<void> { |
| 252 | try { |
| 253 | const response = await fetch(`${remoteUrl}/diff`); |
| 254 | if (!response.ok) { |
| 255 | throw new Error(`Failed to fetch diff: ${response.statusText}`); |
| 256 | } |
| 257 | |
| 258 | const responseData = await response.json(); |
| 259 | const diffContent = responseData.diff || ""; |
| 260 | |
| 261 | if (onShowDiff) { |
| 262 | onShowDiff(diffContent); |
| 263 | } |
| 264 | } catch (error: any) { |
| 265 | logger.error("Failed to fetch diff from remote server:", error); |
| 266 | if (onShowDiff) { |
| 267 | onShowDiff(`Error: Failed to fetch diff - ${error.message}`); |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | /** |
| 273 | * Handle /apply command in remote mode |
| 274 | */ |
| 275 | async function handleRemoteApplyCommand( |
| 276 | remoteUrl: string, |
| 277 | onShowStatusMessage?: (message: string) => void, |
| 278 | ): Promise<void> { |
| 279 | try { |
| 280 | const response = await fetch(`${remoteUrl}/diff`); |
| 281 | if (!response.ok) { |
| 282 | throw new Error(`Failed to fetch diff: ${response.statusText}`); |
| 283 | } |
| 284 | |
| 285 | const responseData = await response.json(); |
| 286 | const diffContent = responseData.diff || ""; |
| 287 | |
| 288 | if (!diffContent || diffContent.trim() === "") { |
| 289 | if (onShowStatusMessage) { |
| 290 | onShowStatusMessage("No changes to apply"); |
| 291 | } |
| 292 | return; |
| 293 | } |
| 294 | |
| 295 | // Apply the diff using git apply |
| 296 | const { execFileSync } = await import("child_process"); |
| 297 | |
| 298 | try { |
| 299 | execFileSync("git", ["apply"], { |
| 300 | input: diffContent, |
| 301 | stdio: ["pipe", "pipe", "pipe"], |
| 302 | }); |
| 303 | |
| 304 | if (onShowStatusMessage) { |
| 305 | onShowStatusMessage( |
| 306 | "✓ Successfully applied diff to local working tree", |
| 307 | ); |
| 308 | } |
| 309 | } catch (gitError: any) { |
| 310 | if (onShowStatusMessage) { |
| 311 | onShowStatusMessage(`✗ Failed to apply diff: ${gitError.message}`); |
| 312 | } |
| 313 | } |
| 314 | } catch (error: any) { |
| 315 | logger.error("Failed to fetch diff from remote server:", error); |
| 316 | if (onShowStatusMessage) { |
| 317 | onShowStatusMessage(`✗ Failed to fetch diff: ${error.message}`); |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | /** |
| 323 | * Handle special TUI commands |
| 324 | */ |
| 325 | export async function handleSpecialCommands({ |
| 326 | message, |
| 327 | isRemoteMode, |
| 328 | remoteUrl, |
| 329 | onShowConfigSelector, |
| 330 | exit, |
| 331 | onShowDiff, |
| 332 | onShowStatusMessage, |
| 333 | }: HandleSpecialCommandsOptions): Promise<boolean> { |
| 334 | const trimmedMessage = message.trim(); |
| 335 | |
| 336 | // Special handling for /config command in TUI |
| 337 | if (trimmedMessage === "/config") { |
| 338 | handleConfigCommand(onShowConfigSelector); |
| 339 | return true; |
| 340 | } |
| 341 | |
| 342 | // Handle /exit command in remote mode |
| 343 | if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") { |
| 344 | const { handleRemoteExit } = await import("./useChat.remote.helpers.js"); |
| 345 | await handleRemoteExit(remoteUrl, exit); |
| 346 | return true; |
| 347 | } |
| 348 | |
| 349 | // Handle /diff command in remote mode - show overlay instead of adding to history |
| 350 | if ( |
| 351 | isRemoteMode && |
| 352 | remoteUrl && |
| 353 | (trimmedMessage === "/diff" || trimmedMessage.startsWith("/diff ")) |
| 354 | ) { |
| 355 | await handleRemoteDiffCommand(remoteUrl, onShowDiff); |
| 356 | return true; |
| 357 | } |
| 358 | |
| 359 | // Handle /apply command in remote mode - show temporary status message |
| 360 | if ( |
| 361 | isRemoteMode && |
| 362 | remoteUrl && |
| 363 | (trimmedMessage === "/apply" || trimmedMessage.startsWith("/apply ")) |
| 364 | ) { |
| 365 | await handleRemoteApplyCommand(remoteUrl, onShowStatusMessage); |
| 366 | return true; |
| 367 | } |
| 368 | |
| 369 | return false; |
| 370 | } |
| 371 | |
| 372 | /** |
| 373 | * Generate a title for the session based on the first assistant response |
| 374 | */ |
| 375 | export async function generateSessionTitle( |
| 376 | assistantResponse: string, |
| 377 | llmApi: any, |
| 378 | model: any, |
| 379 | currentSessionTitle?: string, |
| 380 | ): Promise<string | undefined> { |
| 381 | // Only generate title for untitled sessions |
| 382 | if (currentSessionTitle && currentSessionTitle !== DEFAULT_SESSION_TITLE) { |
| 383 | return undefined; |
| 384 | } |
| 385 | |
| 386 | if (!assistantResponse || !llmApi || !model) { |
| 387 | return undefined; |
| 388 | } |
| 389 | |
| 390 | try { |
| 391 | const { ChatDescriber } = await import("core/util/chatDescriber.js"); |
| 392 | const generatedTitle = await ChatDescriber.describeWithBaseLlmApi( |
| 393 | llmApi, |
| 394 | model, |
| 395 | assistantResponse, |
| 396 | ); |
| 397 | |
| 398 | logger.debug("Generated session title", { |
| 399 | original: currentSessionTitle, |
| 400 | generated: generatedTitle, |
| 401 | }); |
| 402 | |
| 403 | return generatedTitle; |
| 404 | } catch (error) { |
| 405 | logger.error("Failed to generate session title:", error); |
| 406 | return undefined; |
| 407 | } |
| 408 | } |