From c5cacded4b835006d19135d00c07a52f65614624 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 17:34:18 -0700 Subject: [PATCH] feat: image inputs --- extensions/cli/src/ui/ImagePaste.test.ts | 129 ++++++++++++++++++ extensions/cli/src/ui/TextBuffer.ts | 24 ++++ extensions/cli/src/ui/UserInput.tsx | 23 +++- .../cli/src/ui/components/ScreenContent.tsx | 2 +- .../cli/src/ui/hooks/useChat.helpers.ts | 114 ++++++++++++++-- extensions/cli/src/ui/hooks/useChat.ts | 42 ++++-- extensions/cli/src/ui/hooks/useUserInput.ts | 120 ++++++++++++++++ 7 files changed, 426 insertions(+), 28 deletions(-) create mode 100644 extensions/cli/src/ui/ImagePaste.test.ts diff --git a/extensions/cli/src/ui/ImagePaste.test.ts b/extensions/cli/src/ui/ImagePaste.test.ts new file mode 100644 index 000000000..221259a2c --- /dev/null +++ b/extensions/cli/src/ui/ImagePaste.test.ts @@ -0,0 +1,129 @@ +import { describe, it, expect, beforeEach } from "vitest"; + +import { TextBuffer } from "./TextBuffer.js"; + +describe("Image Pasting Functionality", () => { + let textBuffer: TextBuffer; + + beforeEach(() => { + textBuffer = new TextBuffer(); + }); + + describe("TextBuffer Image Support", () => { + it("should add image placeholder to text buffer", () => { + const mockImageBuffer = Buffer.from("fake-image-data"); + + const placeholder = textBuffer.addImage(mockImageBuffer); + + expect(placeholder).toBe("[Image #1]"); + expect(textBuffer.text).toBe("[Image #1]"); + expect(textBuffer.getAllImages().size).toBe(1); + expect(textBuffer.getAllImages().get(placeholder)).toBe(mockImageBuffer); + }); + + it("should handle multiple images with incrementing counters", () => { + const mockImageBuffer1 = Buffer.from("fake-image-data-1"); + const mockImageBuffer2 = Buffer.from("fake-image-data-2"); + + const placeholder1 = textBuffer.addImage(mockImageBuffer1); + const placeholder2 = textBuffer.addImage(mockImageBuffer2); + + expect(placeholder1).toBe("[Image #1]"); + expect(placeholder2).toBe("[Image #2]"); + expect(textBuffer.text).toBe("[Image #1][Image #2]"); + expect(textBuffer.getAllImages().size).toBe(2); + }); + + it("should clear images when buffer is cleared", () => { + const mockImageBuffer = Buffer.from("fake-image-data"); + textBuffer.addImage(mockImageBuffer); + + textBuffer.clear(); + + expect(textBuffer.getAllImages().size).toBe(0); + expect(textBuffer.text).toBe(""); + }); + + it("should clear only images with clearImages()", () => { + const mockImageBuffer = Buffer.from("fake-image-data"); + textBuffer.insertText("Some text "); + textBuffer.addImage(mockImageBuffer); + textBuffer.insertText(" more text"); + + textBuffer.clearImages(); + + expect(textBuffer.getAllImages().size).toBe(0); + expect(textBuffer.text).toContain("Some text"); + expect(textBuffer.text).toContain("[Image #1]"); + expect(textBuffer.text).toContain("more text"); + }); + }); + + describe("Message Formatting with Images", () => { + it("should format message with images correctly", async () => { + const { formatMessageWithFiles } = await import("./hooks/useChat.helpers.js"); + + const message = "Here is an image: [Image #1] and some text"; + const attachedFiles: Array<{ path: string; content: string }> = []; + const imageMap = new Map([ + ["[Image #1]", Buffer.from("fake-image-data")] + ]); + + const result = await formatMessageWithFiles(message, attachedFiles, imageMap); + + expect(result.message.role).toBe("user"); + expect(Array.isArray(result.message.content)).toBe(true); + + const content = result.message.content as any[]; + expect(content).toHaveLength(3); + expect(content[0]).toEqual({ + type: "text", + text: "Here is an image: " + }); + expect(content[1]).toEqual({ + type: "imageUrl", + imageUrl: { url: expect.stringMatching(/^data:image\/png;base64,/) } + }); + expect(content[2]).toEqual({ + type: "text", + text: " and some text" + }); + }); + + it("should handle message with only text (no images)", async () => { + const { formatMessageWithFiles } = await import("./hooks/useChat.helpers.js"); + + const message = "Just text, no images"; + const attachedFiles: Array<{ path: string; content: string }> = []; + + const result = await formatMessageWithFiles(message, attachedFiles); + + expect(result.message.role).toBe("user"); + expect(result.message.content).toBe("Just text, no images"); + }); + + it("should handle multiple images in message", async () => { + const { formatMessageWithFiles } = await import("./hooks/useChat.helpers.js"); + + const message = "First [Image #1] then text [Image #2] end"; + const attachedFiles: Array<{ path: string; content: string }> = []; + const imageMap = new Map([ + ["[Image #1]", Buffer.from("fake-image-data-1")], + ["[Image #2]", Buffer.from("fake-image-data-2")] + ]); + + const result = await formatMessageWithFiles(message, attachedFiles, imageMap); + + expect(Array.isArray(result.message.content)).toBe(true); + const content = result.message.content as any[]; + + // Should have: text, image, text, image, text = 5 parts + expect(content).toHaveLength(5); + expect(content[0].type).toBe("text"); + expect(content[1].type).toBe("imageUrl"); + expect(content[2].type).toBe("text"); + expect(content[3].type).toBe("imageUrl"); + expect(content[4].type).toBe("text"); + }); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/ui/TextBuffer.ts b/extensions/cli/src/ui/TextBuffer.ts index 4c0ef4bb4..aa24caf19 100644 --- a/extensions/cli/src/ui/TextBuffer.ts +++ b/extensions/cli/src/ui/TextBuffer.ts @@ -15,6 +15,8 @@ export class TextBuffer { private _onStateChange?: () => void; private _pasteMap = new Map(); // placeholder -> original content private _pasteCounter: number = 0; + private _imageMap = new Map(); // placeholder -> image buffer + private _imageCounter: number = 0; constructor(initialText: string = "") { this._text = initialText; @@ -153,6 +155,8 @@ export class TextBuffer { this._cursor = 0; this._pasteMap.clear(); this._pasteCounter = 0; + this._imageMap.clear(); + this._imageCounter = 0; this._pasteBuffer = ""; this._inPasteMode = false; this._rapidInputBuffer = ""; @@ -189,6 +193,26 @@ export class TextBuffer { this._pasteMap.clear(); } + // Add image to buffer and return placeholder + addImage(imageBuffer: Buffer): string { + this._imageCounter++; + const placeholder = `[Image #${this._imageCounter}]`; + this._imageMap.set(placeholder, imageBuffer); + this.insertText(placeholder); + return placeholder; + } + + // Get all images for message formatting + getAllImages(): Map { + return new Map(this._imageMap); + } + + // Clear images after message submission + clearImages(): void { + this._imageMap.clear(); + this._imageCounter = 0; + } + // Test helper: forces immediate finalization without waiting for timers flushPendingInput(): void { if (this._rapidInputTimer) { diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index cb0014952..a5a7f5607 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -20,7 +20,7 @@ import { SlashCommandUI } from "./SlashCommandUI.js"; import { TextBuffer } from "./TextBuffer.js"; interface UserInputProps { - onSubmit: (message: string) => void; + onSubmit: (message: string, imageMap?: Map) => void; isWaitingForResponse: boolean; inputMode: boolean; onInterrupt?: () => void; @@ -408,11 +408,17 @@ const UserInput: React.FC = ({ // Normal Enter behavior - submit if there's content if (textBuffer.text.trim() && !isWaitingForResponse) { + // Get images before expanding paste blocks + const imageMap = textBuffer.getAllImages(); + // Expand all paste blocks before submitting textBuffer.expandAllPasteBlocks(); const submittedText = textBuffer.text.trim(); inputHistory.addEntry(submittedText); - onSubmit(submittedText); + + // Submit with images + onSubmit(submittedText, imageMap); + textBuffer.clear(); setInputText(""); setCursorPosition(0); @@ -473,6 +479,17 @@ const UserInput: React.FC = ({ inputHistory.resetNavigation(); }; + // Handle text buffer updates for async operations like image pasting + const handleTextBufferUpdate = () => { + const newText = textBuffer.text; + const newCursor = textBuffer.cursor; + setInputText(newText); + setCursorPosition(newCursor); + updateSlashCommandState(newText, newCursor); + updateFileSearchState(newText, newCursor); + inputHistory.resetNavigation(); + }; + useInput((input, key) => { // Don't handle any input when disabled if (disabled) { @@ -489,6 +506,8 @@ const UserInput: React.FC = ({ showFileSearch, cycleModes, clearInput, + textBuffer, + onTextBufferUpdate: handleTextBufferUpdate, }) ) { return; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 16b9ebb5a..81f2085ed 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -30,7 +30,7 @@ interface ScreenContentProps { createPolicy?: boolean, stopStream?: boolean, ) => void; - handleUserMessage: (message: string) => void; + handleUserMessage: (message: string, imageMap?: Map) => void; isWaitingForResponse: boolean; inputMode: boolean; handleInterrupt: () => void; diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 21a1b63b6..920ae8bfe 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -8,8 +8,8 @@ import { compactChatHistory } from "../../compaction.js"; import { DEFAULT_SESSION_TITLE } from "../../constants/session.js"; import { loadSession, - updateSessionHistory, startNewSession, + updateSessionHistory, } from "../../session.js"; import { posthogService } from "../../telemetry/posthogService.js"; import { telemetryService } from "../../telemetry/telemetryService.js"; @@ -220,19 +220,13 @@ export function processSlashCommandResult({ } /** - * Format message with attached files - returns message text and context items separately + * Format message with attached files and images - returns a complete ChatHistoryItem */ -export function formatMessageWithFiles( +export async function formatMessageWithFiles( message: string, attachedFiles: Array<{ path: string; content: string }>, -): { - messageText: string; - contextItems: import("core/index.js").ContextItemWithId[]; -} { - if (attachedFiles.length === 0) { - return { messageText: message, contextItems: [] }; - } - + imageMap?: Map, +): Promise { // Convert attached files to context items const contextItems = attachedFiles.map((file) => ({ id: { @@ -248,8 +242,102 @@ export function formatMessageWithFiles( }, })); - // Keep the original message text unchanged (preserving @filename references) - return { messageText: message, contextItems }; + // Process message content for images + let messageContent: import("core/index.js").MessageContent = message; + + if (imageMap && imageMap.size > 0) { + const messageParts: import("core/index.js").MessagePart[] = []; + let textContent = message; + + // Replace image placeholders with image parts + for (const [placeholder, imageBuffer] of imageMap.entries()) { + logger.debug(`Processing image placeholder: ${placeholder}, size: ${imageBuffer.length} bytes`); + + // Check image size and warn/limit if too large + const maxSize = 10 * 1024 * 1024; // 10MB limit + if (imageBuffer.length > maxSize) { + logger.warn(`Image is too large (${Math.round(imageBuffer.length / 1024 / 1024)}MB). Skipping image.`); + // Skip this image and replace with text placeholder + textContent = textContent.replace(placeholder, "[Large image skipped - reduce image size and try again]"); + continue; + } + + // Detect image format from buffer header + const isPNG = (buffer: Buffer) => buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47; + const isJPEG = (buffer: Buffer) => buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF; + const isGIF = (buffer: Buffer) => buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x38; + const isWebP = (buffer: Buffer) => buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46 && + buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50; + + const getImageMimeType = (buffer: Buffer): string => { + if (buffer.length < 8) return 'image/png'; + + if (isPNG(buffer)) return 'image/png'; + if (isJPEG(buffer)) return 'image/jpeg'; + if (isGIF(buffer)) return 'image/gif'; + if (isWebP(buffer)) return 'image/webp'; + + return 'image/png'; // Default fallback + }; + + const mimeType = getImageMimeType(imageBuffer); + logger.debug(`Detected image format: ${mimeType}`); + + // Convert buffer to base64 data URL asynchronously to avoid blocking + logger.debug("Converting image to base64..."); + const base64Image = await new Promise((resolve) => { + // Use setImmediate to yield to event loop + setImmediate(() => { + const result = imageBuffer.toString('base64'); + resolve(result); + }); + }); + const dataUrl = `data:${mimeType};base64,${base64Image}`; + logger.debug(`Image converted to base64, dataUrl length: ${dataUrl.length}`); + + // Split text around the placeholder + const parts = textContent.split(placeholder); + if (parts.length > 1) { + // Add text before placeholder + if (parts[0]) { + messageParts.push({ + type: "text", + text: parts[0], + }); + } + + // Add image part + messageParts.push({ + type: "imageUrl", + imageUrl: { url: dataUrl }, + }); + + // Continue with remaining text + textContent = parts.slice(1).join(placeholder); + } + } + + // Add any remaining text + if (textContent) { + messageParts.push({ + type: "text", + text: textContent, + }); + } + + // Use message parts if we have images, otherwise keep as string + if (messageParts.length > 0) { + messageContent = messageParts; + } + } + + return { + message: { + role: "user", + content: messageContent, + }, + contextItems, + }; } /** diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 290fcd3b7..03ede07f9 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -255,7 +255,7 @@ export function useChat({ } }; - const handleUserMessage = async (message: string) => { + const handleUserMessage = async (message: string, imageMap?: Map) => { // Handle special commands const handled = await handleSpecialCommands({ message, @@ -308,20 +308,45 @@ export function useChat({ // Track telemetry trackUserMessage(message, model); - // Add user message to history and display - const { messageText, contextItems } = formatMessageWithFiles( + // Format message with attached files and images + logger.debug("Processing message with images", { + hasImages: !!(imageMap && imageMap.size > 0), + imageCount: imageMap?.size || 0 + }); + const newUserMessage = await formatMessageWithFiles( message, attachedFiles, + imageMap, ); + logger.debug("Message formatted successfully"); + if (attachedFiles.length > 0) { setAttachedFiles([]); } // In remote mode, send message to server instead of processing locally if (isRemoteMode && remoteUrl) { + // For remote mode, convert MessageContent to string + let messageContentString: string; + if (typeof newUserMessage.message.content === "string") { + messageContentString = newUserMessage.message.content; + } else { + // Convert MessagePart[] to string (extracting text, noting images) + messageContentString = newUserMessage.message.content + .map(part => { + if (part.type === "text") { + return part.text; + } else if (part.type === "imageUrl") { + return "[Image]"; + } + return ""; + }) + .join(""); + } + await handleRemoteMessage({ remoteUrl, - messageContent: messageText, + messageContent: messageContentString, setChatHistory, }); return; @@ -338,14 +363,7 @@ export function useChat({ setCompactionIndex, }); - // NOW add user message to history with context items - const newUserMessage: ChatHistoryItem = { - message: { - role: "user", - content: messageText, - }, - contextItems, - }; + // Add the formatted user message to history const newHistory = [...currentChatHistory, newUserMessage]; setChatHistory(newHistory); diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index ea8799b77..21e6a498a 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -1,5 +1,6 @@ import type { PermissionMode } from "../../permissions/types.js"; import { logger } from "../../util/logger.js"; +import type { TextBuffer } from "../TextBuffer.js"; // Helper function to handle control keys interface ControlKeysOptions { @@ -10,6 +11,93 @@ interface ControlKeysOptions { showFileSearch: boolean; cycleModes: () => Promise; clearInput?: () => void; + textBuffer?: TextBuffer; + onTextBufferUpdate?: () => void; +} + +// Helper function to check if clipboard contains an image +async function checkClipboardForImage(): Promise { + try { + const os = await import("os"); + const { exec } = await import("child_process"); + const { promisify } = await import("util"); + const execAsync = promisify(exec); + + const platform = os.platform(); + + if (platform === "darwin") { + // macOS: Check clipboard using osascript + const { stdout } = await execAsync( + 'osascript -e "clipboard info"' + ); + return stdout.includes("«class PNGf»") || stdout.includes("«class TIFF»") || stdout.includes("picture"); + } else if (platform === "win32") { + // Windows: Use PowerShell to check clipboard + const { stdout } = await execAsync( + 'powershell -command "Get-Clipboard -Format Image | Measure-Object | Select-Object -ExpandProperty Count"' + ); + return parseInt(stdout.trim()) > 0; + } else if (platform === "linux") { + // Linux: Check if xclip can get image data + try { + await execAsync("xclip -selection clipboard -t image/png -o > /dev/null 2>&1"); + return true; + } catch { + return false; + } + } + + return false; + } catch (error) { + logger.debug("Error checking clipboard for image:", error); + return false; + } +} + +// Helper function to get image from clipboard +async function getClipboardImage(): Promise { + try { + const os = await import("os"); + const { exec } = await import("child_process"); + const { promisify } = await import("util"); + const execAsync = promisify(exec); + const fs = await import("fs/promises"); + const path = await import("path"); + + const platform = os.platform(); + const tempDir = os.tmpdir(); + const tempImagePath = path.join(tempDir, `continue-clipboard-${Date.now()}.png`); + + if (platform === "darwin") { + // macOS: Save clipboard image using osascript + await execAsync( + `osascript -e 'set the clipboard to (the clipboard as «class PNGf»)' -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set file_ref to open for access "${tempImagePath}" with write permission' -e 'write png_data to file_ref' -e 'close access file_ref'` + ); + } else if (platform === "win32") { + // Windows: Use PowerShell to save clipboard image + await execAsync( + `powershell -command "Get-Clipboard -Format Image | Set-Content -Path '${tempImagePath}' -Encoding Byte"` + ); + } else if (platform === "linux") { + // Linux: Use xclip to save clipboard image + await execAsync(`xclip -selection clipboard -t image/png -o > "${tempImagePath}"`); + } else { + return null; + } + + // Read the temporary file + const imageBuffer = await fs.readFile(tempImagePath); + + // Clean up the temporary file + await fs.unlink(tempImagePath).catch(() => { + // Ignore cleanup errors + }); + + return imageBuffer; + } catch (error) { + logger.debug("Error reading image from clipboard:", error); + return null; + } } export function handleControlKeys(options: ControlKeysOptions): boolean { @@ -21,6 +109,8 @@ export function handleControlKeys(options: ControlKeysOptions): boolean { showFileSearch, cycleModes, clearInput, + textBuffer, + onTextBufferUpdate, } = options; // Handle Ctrl+C to clear input @@ -29,6 +119,36 @@ export function handleControlKeys(options: ControlKeysOptions): boolean { return true; } + // Handle Ctrl+V for clipboard paste (including images) + if (key.ctrl && input === "v" && textBuffer) { + logger.debug("Handling clipboard paste"); + // Check for images asynchronously + checkClipboardForImage() + .then(async (hasImage) => { + if (hasImage) { + const imageBuffer = await getClipboardImage(); + if (imageBuffer) { + textBuffer.addImage(imageBuffer); + // Trigger UI update + if (onTextBufferUpdate) { + onTextBufferUpdate(); + } + return; + } + } + // If no image or image reading failed, let normal text paste handling continue + // We return false here to allow the normal paste processing to happen + }) + .catch((error) => { + logger.debug("Error checking clipboard for image:", error); + // Continue with normal text paste handling + }); + + // Don't consume the event - let normal paste handling continue + // This allows text pastes to work normally when no image is present + return false; + } + // Handle Ctrl+D to exit if (key.ctrl && input === "d") { exit();