From c5cacded4b835006d19135d00c07a52f65614624 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 17:34:18 -0700 Subject: [PATCH 01/10] 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(); From 986d633ac2431babe4543cd7ee68e299d4c7e729 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 17:34:42 -0700 Subject: [PATCH 02/10] feat: detect image media type in anthropic openai adapter --- packages/openai-adapters/src/apis/Anthropic.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index e44dfe2a0..fd8f2a2a0 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -174,11 +174,17 @@ export class AnthropicApi implements BaseLlmApi { } return part; } + // Extract media type from data URL (e.g., "data:image/png;base64,..." -> "image/png") + // @ts-ignore + const dataUrl = part.image_url.url || ""; + const mediaTypeMatch = dataUrl.match(/^data:([^;]+);base64,/); + const mediaType = mediaTypeMatch ? mediaTypeMatch[1] : "image/jpeg"; + return { type: "image", source: { type: "base64", - media_type: "image/jpeg", + media_type: mediaType, // @ts-ignore data: part.image_url.url.split(",")[1], }, From d999b447b3faeed08a010e19a4d5c44eceb12139 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 17:54:04 -0700 Subject: [PATCH 03/10] feat: use sharp to convert all images to downsized jpeg --- .../cli/src/ui/hooks/useChat.helpers.ts | 217 ++++++++++++------ .../openai-adapters/src/apis/Anthropic.ts | 8 +- 2 files changed, 153 insertions(+), 72 deletions(-) diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 920ae8bfe..21a4f7b6c 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -19,6 +19,155 @@ import { shouldAutoCompact } from "../../util/tokenizer.js"; import { SlashCommandResult } from "./useChat.types.js"; +/** + * Dynamically import Sharp without using eval + */ +async function loadSharp(): Promise { + try { + // Use Function constructor to avoid bundler issues with dynamic imports + const importSharp = new Function('return import("sharp")'); + const sharpModule = await importSharp().catch(() => null); + return sharpModule ? (sharpModule.default || sharpModule) : null; + } catch { + return null; + } +} + +/** + * Process image buffer to JPEG with resizing using Sharp (if available) + */ +async function processImageWithSharp(imageBuffer: Buffer, maxWidth = 512, maxHeight = 512): Promise<{ buffer: Buffer; isJpeg: boolean }> { + try { + // Try to load Sharp - it's an optional dependency + const sharp = await loadSharp(); + if (!sharp) { + logger.debug("Sharp not available, using original image buffer"); + return { buffer: imageBuffer, isJpeg: false }; + } + + logger.debug("Processing image with Sharp..."); + + // Process image: convert to JPEG and resize if needed + const processedBuffer = await sharp(imageBuffer) + .resize(maxWidth, maxHeight, { + fit: 'inside', + withoutEnlargement: true + }) + .jpeg({ + quality: 85, + progressive: true + }) + .toBuffer(); + + logger.debug(`Image processed with Sharp: ${imageBuffer.length} bytes -> ${processedBuffer.length} bytes`); + return { buffer: processedBuffer, isJpeg: true }; + } catch (error) { + logger.warn("Failed to process image with Sharp, using original:", error); + return { buffer: imageBuffer, isJpeg: false }; + } +} + +/** + * Detect image format from buffer header - simplified to reduce complexity + */ +function detectImageFormat(buffer: Buffer): string { + if (buffer.length < 4) return 'image/png'; + + const signature = buffer.subarray(0, 4); + + // JPEG: FF D8 FF + if (signature[0] === 0xFF && signature[1] === 0xD8 && signature[2] === 0xFF) { + return 'image/jpeg'; + } + + // PNG: 89 50 4E 47 + if (signature[0] === 0x89 && signature[1] === 0x50 && signature[2] === 0x4E && signature[3] === 0x47) { + return 'image/png'; + } + + // GIF: 47 49 46 38 + if (signature[0] === 0x47 && signature[1] === 0x49 && signature[2] === 0x46 && signature[3] === 0x38) { + return 'image/gif'; + } + + // WebP: RIFF + WEBP at offset 8 + if (signature[0] === 0x52 && signature[1] === 0x49 && buffer.length >= 12) { + const webpSig = buffer.subarray(8, 12); + if (webpSig[0] === 0x57 && webpSig[1] === 0x45 && webpSig[2] === 0x42 && webpSig[3] === 0x50) { + return 'image/webp'; + } + } + + return 'image/png'; // Default fallback +} + +/** + * Process a single image placeholder - extracted to reduce nesting depth + */ +async function processImagePlaceholder( + placeholder: string, + originalImageBuffer: Buffer, + textContent: string, + messageParts: import("core/index.js").MessagePart[] +): Promise<{ textContent: string }> { + logger.debug(`Processing image placeholder: ${placeholder}, original size: ${originalImageBuffer.length} bytes`); + + try { + // Process image with Sharp (convert to JPEG and resize) + const processResult = await processImageWithSharp(originalImageBuffer); + const processedImageBuffer = processResult.buffer; + const isProcessedJpeg = processResult.isJpeg; + + // Check processed image size + const maxSize = 10 * 1024 * 1024; // 10MB limit + if (processedImageBuffer.length > maxSize) { + logger.warn(`Processed image is still too large (${Math.round(processedImageBuffer.length / 1024 / 1024)}MB). Skipping image.`); + return { textContent: textContent.replace(placeholder, "[Large image skipped - reduce image size and try again]") }; + } + + // Convert processed buffer to base64 data URL asynchronously to avoid blocking + logger.debug("Converting processed image to base64..."); + const base64Image = await new Promise((resolve) => { + // Use setImmediate to yield to event loop + setImmediate(() => { + const result = processedImageBuffer.toString('base64'); + resolve(result); + }); + }); + + // Use correct MIME type based on whether Sharp processing was successful + const mimeType = isProcessedJpeg ? 'image/jpeg' : detectImageFormat(processedImageBuffer); + const dataUrl = `data:${mimeType};base64,${base64Image}`; + logger.debug(`Image converted to base64 with MIME type ${mimeType}, 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 + return { textContent: parts.slice(1).join(placeholder) }; + } + + return { textContent }; + } catch (error) { + logger.error(`Failed to process image ${placeholder}:`, error); + return { textContent: textContent.replace(placeholder, "[Image processing failed]") }; + } +} + /** * Initialize chat history */ @@ -250,71 +399,9 @@ export async function formatMessageWithFiles( 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); - } + for (const [placeholder, originalImageBuffer] of imageMap.entries()) { + const result = await processImagePlaceholder(placeholder, originalImageBuffer, textContent, messageParts); + textContent = result.textContent; } // Add any remaining text diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index fd8f2a2a0..e44dfe2a0 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -174,17 +174,11 @@ export class AnthropicApi implements BaseLlmApi { } return part; } - // Extract media type from data URL (e.g., "data:image/png;base64,..." -> "image/png") - // @ts-ignore - const dataUrl = part.image_url.url || ""; - const mediaTypeMatch = dataUrl.match(/^data:([^;]+);base64,/); - const mediaType = mediaTypeMatch ? mediaTypeMatch[1] : "image/jpeg"; - return { type: "image", source: { type: "base64", - media_type: mediaType, + media_type: "image/jpeg", // @ts-ignore data: part.image_url.url.split(",")[1], }, From 907a399ca86f3c686e32656809e9db62e4a25834 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 17:59:12 -0700 Subject: [PATCH 04/10] fix image bugs --- .../MemoizedMessage.formatDisplay.test.tsx | 139 ++++++++++++++++++ .../cli/src/ui/components/MemoizedMessage.tsx | 50 +++++-- .../cli/src/ui/hooks/useChat.helpers.ts | 2 +- package.json | 8 + 4 files changed, 185 insertions(+), 14 deletions(-) create mode 100644 extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx diff --git a/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx b/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx new file mode 100644 index 000000000..12aeabb7f --- /dev/null +++ b/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx @@ -0,0 +1,139 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, it, expect } from "vitest"; + +import type { ChatHistoryItem, MessageContent, MessagePart } from "../../../../../core/index.js"; +import { MemoizedMessage } from "./MemoizedMessage.js"; + +describe("MemoizedMessage formatMessageContentForDisplay", () => { + const createTestHistoryItem = (content: MessageContent): ChatHistoryItem => ({ + message: { + role: "user", + content, + }, + contextItems: [], + }); + + it("should display string content as-is", () => { + const content = "Just a simple text message"; + const historyItem = createTestHistoryItem(content); + + const { lastFrame } = render( + + ); + + expect(lastFrame()).toContain("Just a simple text message"); + }); + + it("should display message with images using placeholders", () => { + const messageParts: MessagePart[] = [ + { type: "text", text: "Here is an image: " }, + { type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } }, + { type: "text", text: " and some more text" }, + ]; + const historyItem = createTestHistoryItem(messageParts); + + const { lastFrame } = render( + + ); + + const output = lastFrame(); + expect(output).toContain("Here is an image: [Image #1] and some more text"); + expect(output).not.toContain("data:image/png;base64,abc123"); + expect(output).not.toContain("imageUrl"); + }); + + it("should display message with multiple images using incrementing placeholders", () => { + const messageParts: MessagePart[] = [ + { type: "text", text: "First " }, + { type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } }, + { type: "text", text: " then text " }, + { type: "imageUrl", imageUrl: { url: "data:image/jpeg;base64,def456" } }, + { type: "text", text: " end" }, + ]; + const historyItem = createTestHistoryItem(messageParts); + + const { lastFrame } = render( + + ); + + const output = lastFrame(); + expect(output).toContain("First [Image #1] then text [Image #2] end"); + expect(output).not.toContain("data:image/png;base64"); + expect(output).not.toContain("data:image/jpeg;base64"); + }); + + it("should display message with only images", () => { + const messageParts: MessagePart[] = [ + { type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } }, + { type: "imageUrl", imageUrl: { url: "data:image/png;base64,def456" } }, + ]; + const historyItem = createTestHistoryItem(messageParts); + + const { lastFrame } = render( + + ); + + const output = lastFrame(); + expect(output).toContain("[Image #1][Image #2]"); + }); + + it("should handle empty text parts gracefully", () => { + const messageParts: MessagePart[] = [ + { type: "text", text: "" }, + { type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } }, + { type: "text", text: "" }, + ]; + const historyItem = createTestHistoryItem(messageParts); + + const { lastFrame } = render( + + ); + + const output = lastFrame(); + expect(output).toContain("[Image #1]"); + expect(output).not.toContain("data:image/png;base64"); + }); + + it("should display text-only message parts as regular string", () => { + const messageParts: MessagePart[] = [ + { type: "text", text: "Just text, no images here" }, + ]; + const historyItem = createTestHistoryItem(messageParts); + + const { lastFrame } = render( + + ); + + expect(lastFrame()).toContain("Just text, no images here"); + }); + + it("should handle unknown part types by converting to JSON", () => { + const messageParts = [ + { type: "text", text: "Start " }, + { type: "unknown", data: { some: "data" } }, + { type: "text", text: " end" }, + ] as MessagePart[]; + const historyItem = createTestHistoryItem(messageParts); + + const { lastFrame } = render( + + ); + + const output = lastFrame(); + expect(output).toContain("Start"); + expect(output).toContain("end"); + expect(output).toContain('{"type":"unknown","data":{"some":"data"}}'); + }); + + it("should handle non-array non-string content by converting to JSON", () => { + const content = { someObject: "data" } as any; + const historyItem = createTestHistoryItem(content); + + const { lastFrame } = render( + + ); + + expect(lastFrame()).toContain('{"someObject":"data"}'); + }); +}); \ No newline at end of file diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index 58a95616d..4c9a1b953 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -7,6 +7,40 @@ import type { ChatHistoryItem } from "../../../../../core/index.js"; import { MarkdownRenderer } from "../MarkdownRenderer.js"; import { ToolResultSummary } from "../ToolResultSummary.js"; +/** + * Formats message content for display, converting message parts array back to + * user-friendly format with placeholders like [Image #1], [Pasted Text #1], etc. + */ +function formatMessageContentForDisplay( + content: import("../../../../../core/index.js").MessageContent +): string { + if (typeof content === "string") { + return content; + } + + if (!Array.isArray(content)) { + return JSON.stringify(content); + } + + // Convert message parts array back to display format with placeholders + let displayText = ""; + let imageCounter = 0; + + for (const part of content) { + if (part.type === "text") { + displayText += part.text; + } else if (part.type === "imageUrl") { + imageCounter++; + displayText += `[Image #${imageCounter}]`; + } else { + // Handle any other part types by converting to JSON + displayText += JSON.stringify(part); + } + } + + return displayText; +} + interface MemoizedMessageProps { item: ChatHistoryItem; index: number; @@ -62,11 +96,7 @@ export const MemoizedMessage = memo( ● )} @@ -132,17 +162,11 @@ export const MemoizedMessage = memo( {isUser ? ( - {typeof message.content === "string" - ? message.content - : JSON.stringify(message.content)} + {formatMessageContentForDisplay(message.content)} ) : ( )} {isStreaming && ▋} diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 21a4f7b6c..c356e6b39 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -36,7 +36,7 @@ async function loadSharp(): Promise { /** * Process image buffer to JPEG with resizing using Sharp (if available) */ -async function processImageWithSharp(imageBuffer: Buffer, maxWidth = 512, maxHeight = 512): Promise<{ buffer: Buffer; isJpeg: boolean }> { +async function processImageWithSharp(imageBuffer: Buffer, maxWidth = 1024, maxHeight = 1024): Promise<{ buffer: Buffer; isJpeg: boolean }> { try { // Try to load Sharp - it's an optional dependency const sharp = await loadSharp(); diff --git a/package.json b/package.json index 28cdb97d8..d5d14d6fc 100644 --- a/package.json +++ b/package.json @@ -16,5 +16,13 @@ "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8", "typescript": "^5.6.3" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "^0.33.5", + "@img/sharp-darwin-x64": "^0.33.5", + "@img/sharp-linux-arm": "^0.33.5", + "@img/sharp-linux-arm64": "^0.33.5", + "@img/sharp-linux-x64": "^0.33.5", + "@img/sharp-win32-x64": "^0.33.5" } } From 357dc2c46d9e6621d001813317378962acbc433f Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 17:59:58 -0700 Subject: [PATCH 05/10] chore: format --- extensions/cli/src/ui/ImagePaste.test.ts | 62 +++-- extensions/cli/src/ui/UserInput.tsx | 6 +- .../MemoizedMessage.formatDisplay.test.tsx | 43 ++-- .../cli/src/ui/components/MemoizedMessage.tsx | 4 +- .../cli/src/ui/hooks/useChat.helpers.ts | 132 +++++++---- extensions/cli/src/ui/hooks/useChat.ts | 13 +- extensions/cli/src/ui/hooks/useUserInput.ts | 39 ++-- package-lock.json | 218 ++++++++++++++++++ 8 files changed, 405 insertions(+), 112 deletions(-) diff --git a/extensions/cli/src/ui/ImagePaste.test.ts b/extensions/cli/src/ui/ImagePaste.test.ts index 221259a2c..244ac2d00 100644 --- a/extensions/cli/src/ui/ImagePaste.test.ts +++ b/extensions/cli/src/ui/ImagePaste.test.ts @@ -12,9 +12,9 @@ describe("Image Pasting Functionality", () => { 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); @@ -24,10 +24,10 @@ describe("Image Pasting Functionality", () => { 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]"); @@ -37,9 +37,9 @@ describe("Image Pasting Functionality", () => { 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(""); }); @@ -49,9 +49,9 @@ describe("Image Pasting Functionality", () => { 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]"); @@ -61,38 +61,46 @@ describe("Image Pasting Functionality", () => { describe("Message Formatting with Images", () => { it("should format message with images correctly", async () => { - const { formatMessageWithFiles } = await import("./hooks/useChat.helpers.js"); - + 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")] + ["[Image #1]", Buffer.from("fake-image-data")], ]); - const result = await formatMessageWithFiles(message, attachedFiles, imageMap); + 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: " + text: "Here is an image: ", }); expect(content[1]).toEqual({ type: "imageUrl", - imageUrl: { url: expect.stringMatching(/^data:image\/png;base64,/) } + imageUrl: { url: expect.stringMatching(/^data:image\/png;base64,/) }, }); expect(content[2]).toEqual({ type: "text", - text: " and some text" + text: " and some text", }); }); it("should handle message with only text (no images)", async () => { - const { formatMessageWithFiles } = await import("./hooks/useChat.helpers.js"); - + const { formatMessageWithFiles } = await import( + "./hooks/useChat.helpers.js" + ); + const message = "Just text, no images"; const attachedFiles: Array<{ path: string; content: string }> = []; @@ -103,20 +111,26 @@ describe("Image Pasting Functionality", () => { }); it("should handle multiple images in message", async () => { - const { formatMessageWithFiles } = await import("./hooks/useChat.helpers.js"); - + 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")] + ["[Image #2]", Buffer.from("fake-image-data-2")], ]); - const result = await formatMessageWithFiles(message, attachedFiles, imageMap); + 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"); @@ -126,4 +140,4 @@ describe("Image Pasting Functionality", () => { expect(content[4].type).toBe("text"); }); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index a5a7f5607..3cb6a278e 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -410,15 +410,15 @@ const UserInput: React.FC = ({ 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); - + // Submit with images onSubmit(submittedText, imageMap); - + textBuffer.clear(); setInputText(""); setCursorPosition(0); diff --git a/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx b/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx index 12aeabb7f..2aa171cf3 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx @@ -1,8 +1,13 @@ import { render } from "ink-testing-library"; import React from "react"; -import { describe, it, expect } from "vitest"; +import { describe, expect, it } from "vitest"; + +import type { + ChatHistoryItem, + MessageContent, + MessagePart, +} from "../../../../../core/index.js"; -import type { ChatHistoryItem, MessageContent, MessagePart } from "../../../../../core/index.js"; import { MemoizedMessage } from "./MemoizedMessage.js"; describe("MemoizedMessage formatMessageContentForDisplay", () => { @@ -17,9 +22,9 @@ describe("MemoizedMessage formatMessageContentForDisplay", () => { it("should display string content as-is", () => { const content = "Just a simple text message"; const historyItem = createTestHistoryItem(content); - + const { lastFrame } = render( - + , ); expect(lastFrame()).toContain("Just a simple text message"); @@ -32,9 +37,9 @@ describe("MemoizedMessage formatMessageContentForDisplay", () => { { type: "text", text: " and some more text" }, ]; const historyItem = createTestHistoryItem(messageParts); - + const { lastFrame } = render( - + , ); const output = lastFrame(); @@ -52,9 +57,9 @@ describe("MemoizedMessage formatMessageContentForDisplay", () => { { type: "text", text: " end" }, ]; const historyItem = createTestHistoryItem(messageParts); - + const { lastFrame } = render( - + , ); const output = lastFrame(); @@ -69,9 +74,9 @@ describe("MemoizedMessage formatMessageContentForDisplay", () => { { type: "imageUrl", imageUrl: { url: "data:image/png;base64,def456" } }, ]; const historyItem = createTestHistoryItem(messageParts); - + const { lastFrame } = render( - + , ); const output = lastFrame(); @@ -85,9 +90,9 @@ describe("MemoizedMessage formatMessageContentForDisplay", () => { { type: "text", text: "" }, ]; const historyItem = createTestHistoryItem(messageParts); - + const { lastFrame } = render( - + , ); const output = lastFrame(); @@ -100,9 +105,9 @@ describe("MemoizedMessage formatMessageContentForDisplay", () => { { type: "text", text: "Just text, no images here" }, ]; const historyItem = createTestHistoryItem(messageParts); - + const { lastFrame } = render( - + , ); expect(lastFrame()).toContain("Just text, no images here"); @@ -115,9 +120,9 @@ describe("MemoizedMessage formatMessageContentForDisplay", () => { { type: "text", text: " end" }, ] as MessagePart[]; const historyItem = createTestHistoryItem(messageParts); - + const { lastFrame } = render( - + , ); const output = lastFrame(); @@ -129,11 +134,11 @@ describe("MemoizedMessage formatMessageContentForDisplay", () => { it("should handle non-array non-string content by converting to JSON", () => { const content = { someObject: "data" } as any; const historyItem = createTestHistoryItem(content); - + const { lastFrame } = render( - + , ); expect(lastFrame()).toContain('{"someObject":"data"}'); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index 4c9a1b953..1b29a459d 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -8,11 +8,11 @@ import { MarkdownRenderer } from "../MarkdownRenderer.js"; import { ToolResultSummary } from "../ToolResultSummary.js"; /** - * Formats message content for display, converting message parts array back to + * Formats message content for display, converting message parts array back to * user-friendly format with placeholders like [Image #1], [Pasted Text #1], etc. */ function formatMessageContentForDisplay( - content: import("../../../../../core/index.js").MessageContent + content: import("../../../../../core/index.js").MessageContent, ): string { if (typeof content === "string") { return content; diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index c356e6b39..a8a744f56 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -27,7 +27,7 @@ async function loadSharp(): Promise { // Use Function constructor to avoid bundler issues with dynamic imports const importSharp = new Function('return import("sharp")'); const sharpModule = await importSharp().catch(() => null); - return sharpModule ? (sharpModule.default || sharpModule) : null; + return sharpModule ? sharpModule.default || sharpModule : null; } catch { return null; } @@ -36,7 +36,11 @@ async function loadSharp(): Promise { /** * Process image buffer to JPEG with resizing using Sharp (if available) */ -async function processImageWithSharp(imageBuffer: Buffer, maxWidth = 1024, maxHeight = 1024): Promise<{ buffer: Buffer; isJpeg: boolean }> { +async function processImageWithSharp( + imageBuffer: Buffer, + maxWidth = 1024, + maxHeight = 1024, +): Promise<{ buffer: Buffer; isJpeg: boolean }> { try { // Try to load Sharp - it's an optional dependency const sharp = await loadSharp(); @@ -46,20 +50,22 @@ async function processImageWithSharp(imageBuffer: Buffer, maxWidth = 1024, maxHe } logger.debug("Processing image with Sharp..."); - + // Process image: convert to JPEG and resize if needed const processedBuffer = await sharp(imageBuffer) - .resize(maxWidth, maxHeight, { - fit: 'inside', - withoutEnlargement: true + .resize(maxWidth, maxHeight, { + fit: "inside", + withoutEnlargement: true, }) - .jpeg({ + .jpeg({ quality: 85, - progressive: true + progressive: true, }) .toBuffer(); - logger.debug(`Image processed with Sharp: ${imageBuffer.length} bytes -> ${processedBuffer.length} bytes`); + logger.debug( + `Image processed with Sharp: ${imageBuffer.length} bytes -> ${processedBuffer.length} bytes`, + ); return { buffer: processedBuffer, isJpeg: true }; } catch (error) { logger.warn("Failed to process image with Sharp, using original:", error); @@ -71,34 +77,49 @@ async function processImageWithSharp(imageBuffer: Buffer, maxWidth = 1024, maxHe * Detect image format from buffer header - simplified to reduce complexity */ function detectImageFormat(buffer: Buffer): string { - if (buffer.length < 4) return 'image/png'; - + if (buffer.length < 4) return "image/png"; + const signature = buffer.subarray(0, 4); - + // JPEG: FF D8 FF - if (signature[0] === 0xFF && signature[1] === 0xD8 && signature[2] === 0xFF) { - return 'image/jpeg'; + if (signature[0] === 0xff && signature[1] === 0xd8 && signature[2] === 0xff) { + return "image/jpeg"; } - + // PNG: 89 50 4E 47 - if (signature[0] === 0x89 && signature[1] === 0x50 && signature[2] === 0x4E && signature[3] === 0x47) { - return 'image/png'; + if ( + signature[0] === 0x89 && + signature[1] === 0x50 && + signature[2] === 0x4e && + signature[3] === 0x47 + ) { + return "image/png"; } - + // GIF: 47 49 46 38 - if (signature[0] === 0x47 && signature[1] === 0x49 && signature[2] === 0x46 && signature[3] === 0x38) { - return 'image/gif'; + if ( + signature[0] === 0x47 && + signature[1] === 0x49 && + signature[2] === 0x46 && + signature[3] === 0x38 + ) { + return "image/gif"; } - + // WebP: RIFF + WEBP at offset 8 if (signature[0] === 0x52 && signature[1] === 0x49 && buffer.length >= 12) { const webpSig = buffer.subarray(8, 12); - if (webpSig[0] === 0x57 && webpSig[1] === 0x45 && webpSig[2] === 0x42 && webpSig[3] === 0x50) { - return 'image/webp'; + if ( + webpSig[0] === 0x57 && + webpSig[1] === 0x45 && + webpSig[2] === 0x42 && + webpSig[3] === 0x50 + ) { + return "image/webp"; } } - - return 'image/png'; // Default fallback + + return "image/png"; // Default fallback } /** @@ -108,38 +129,51 @@ async function processImagePlaceholder( placeholder: string, originalImageBuffer: Buffer, textContent: string, - messageParts: import("core/index.js").MessagePart[] + messageParts: import("core/index.js").MessagePart[], ): Promise<{ textContent: string }> { - logger.debug(`Processing image placeholder: ${placeholder}, original size: ${originalImageBuffer.length} bytes`); - + logger.debug( + `Processing image placeholder: ${placeholder}, original size: ${originalImageBuffer.length} bytes`, + ); + try { // Process image with Sharp (convert to JPEG and resize) const processResult = await processImageWithSharp(originalImageBuffer); const processedImageBuffer = processResult.buffer; const isProcessedJpeg = processResult.isJpeg; - + // Check processed image size const maxSize = 10 * 1024 * 1024; // 10MB limit if (processedImageBuffer.length > maxSize) { - logger.warn(`Processed image is still too large (${Math.round(processedImageBuffer.length / 1024 / 1024)}MB). Skipping image.`); - return { textContent: textContent.replace(placeholder, "[Large image skipped - reduce image size and try again]") }; + logger.warn( + `Processed image is still too large (${Math.round(processedImageBuffer.length / 1024 / 1024)}MB). Skipping image.`, + ); + return { + textContent: textContent.replace( + placeholder, + "[Large image skipped - reduce image size and try again]", + ), + }; } - + // Convert processed buffer to base64 data URL asynchronously to avoid blocking logger.debug("Converting processed image to base64..."); const base64Image = await new Promise((resolve) => { // Use setImmediate to yield to event loop setImmediate(() => { - const result = processedImageBuffer.toString('base64'); + const result = processedImageBuffer.toString("base64"); resolve(result); }); }); - + // Use correct MIME type based on whether Sharp processing was successful - const mimeType = isProcessedJpeg ? 'image/jpeg' : detectImageFormat(processedImageBuffer); + const mimeType = isProcessedJpeg + ? "image/jpeg" + : detectImageFormat(processedImageBuffer); const dataUrl = `data:${mimeType};base64,${base64Image}`; - logger.debug(`Image converted to base64 with MIME type ${mimeType}, dataUrl length: ${dataUrl.length}`); - + logger.debug( + `Image converted to base64 with MIME type ${mimeType}, dataUrl length: ${dataUrl.length}`, + ); + // Split text around the placeholder const parts = textContent.split(placeholder); if (parts.length > 1) { @@ -150,21 +184,26 @@ async function processImagePlaceholder( text: parts[0], }); } - + // Add image part messageParts.push({ type: "imageUrl", imageUrl: { url: dataUrl }, }); - + // Continue with remaining text return { textContent: parts.slice(1).join(placeholder) }; } - + return { textContent }; } catch (error) { logger.error(`Failed to process image ${placeholder}:`, error); - return { textContent: textContent.replace(placeholder, "[Image processing failed]") }; + return { + textContent: textContent.replace( + placeholder, + "[Image processing failed]", + ), + }; } } @@ -393,17 +432,22 @@ export async function formatMessageWithFiles( // 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, originalImageBuffer] of imageMap.entries()) { - const result = await processImagePlaceholder(placeholder, originalImageBuffer, textContent, messageParts); + const result = await processImagePlaceholder( + placeholder, + originalImageBuffer, + textContent, + messageParts, + ); textContent = result.textContent; } - + // Add any remaining text if (textContent) { messageParts.push({ diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 03ede07f9..ac67fa8d3 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -255,7 +255,10 @@ export function useChat({ } }; - const handleUserMessage = async (message: string, imageMap?: Map) => { + const handleUserMessage = async ( + message: string, + imageMap?: Map, + ) => { // Handle special commands const handled = await handleSpecialCommands({ message, @@ -309,9 +312,9 @@ export function useChat({ trackUserMessage(message, model); // Format message with attached files and images - logger.debug("Processing message with images", { + logger.debug("Processing message with images", { hasImages: !!(imageMap && imageMap.size > 0), - imageCount: imageMap?.size || 0 + imageCount: imageMap?.size || 0, }); const newUserMessage = await formatMessageWithFiles( message, @@ -319,7 +322,7 @@ export function useChat({ imageMap, ); logger.debug("Message formatted successfully"); - + if (attachedFiles.length > 0) { setAttachedFiles([]); } @@ -333,7 +336,7 @@ export function useChat({ } else { // Convert MessagePart[] to string (extracting text, noting images) messageContentString = newUserMessage.message.content - .map(part => { + .map((part) => { if (part.type === "text") { return part.text; } else if (part.type === "imageUrl") { diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index 21e6a498a..666b04121 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -24,29 +24,33 @@ async function checkClipboardForImage(): Promise { const execAsync = promisify(exec); const platform = os.platform(); - + if (platform === "darwin") { // macOS: Check clipboard using osascript - const { stdout } = await execAsync( - 'osascript -e "clipboard info"' + const { stdout } = await execAsync('osascript -e "clipboard info"'); + return ( + stdout.includes("«class PNGf»") || + stdout.includes("«class TIFF»") || + stdout.includes("picture") ); - 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"' + '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"); + 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); @@ -66,33 +70,38 @@ async function getClipboardImage(): Promise { const platform = os.platform(); const tempDir = os.tmpdir(); - const tempImagePath = path.join(tempDir, `continue-clipboard-${Date.now()}.png`); - + 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'` + `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"` + `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}"`); + 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); @@ -143,7 +152,7 @@ export function handleControlKeys(options: ControlKeysOptions): boolean { 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; diff --git a/package-lock.json b/package-lock.json index b4289d422..88967f48a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,7 @@ "requires": true, "packages": { "": { + "name": "continue", "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "concurrently": "^9.1.2", @@ -11,6 +12,14 @@ "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8", "typescript": "^5.6.3" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "^0.33.5", + "@img/sharp-darwin-x64": "^0.33.5", + "@img/sharp-linux-arm": "^0.33.5", + "@img/sharp-linux-arm64": "^0.33.5", + "@img/sharp-linux-x64": "^0.33.5", + "@img/sharp-win32-x64": "^0.33.5" } }, "node_modules/@eslint-community/eslint-utils": { @@ -173,6 +182,215 @@ "license": "BSD-3-Clause", "peer": true }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", + "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", + "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", + "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", + "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", + "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", + "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", + "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.0.5" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", + "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", + "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", From 363aafd82292075b384651ee10b9be298df43a37 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 18:04:12 -0700 Subject: [PATCH 06/10] chore: refactor to fix file too long --- .../cli/src/ui/hooks/useChat.compaction.ts | 193 +++++++++ .../cli/src/ui/hooks/useChat.helpers.ts | 389 +----------------- .../src/ui/hooks/useChat.imageProcessing.ts | 189 +++++++++ extensions/cli/src/ui/hooks/useChat.ts | 4 +- 4 files changed, 390 insertions(+), 385 deletions(-) create mode 100644 extensions/cli/src/ui/hooks/useChat.compaction.ts create mode 100644 extensions/cli/src/ui/hooks/useChat.imageProcessing.ts diff --git a/extensions/cli/src/ui/hooks/useChat.compaction.ts b/extensions/cli/src/ui/hooks/useChat.compaction.ts new file mode 100644 index 000000000..8952f7643 --- /dev/null +++ b/extensions/cli/src/ui/hooks/useChat.compaction.ts @@ -0,0 +1,193 @@ +import type { ChatHistoryItem, Session } from "core/index.js"; + +import { compactChatHistory } from "../../compaction.js"; +import { updateSessionHistory } from "../../session.js"; +import { formatError } from "../../util/formatError.js"; +import { logger } from "../../util/logger.js"; +import { shouldAutoCompact } from "../../util/tokenizer.js"; + +interface HandleCompactCommandOptions { + chatHistory: ChatHistoryItem[]; + model: any; + llmApi: any; + setChatHistory: React.Dispatch>; + setCompactionIndex: React.Dispatch>; + currentSession: Session; + setCurrentSession: React.Dispatch>; +} + +/** + * Handle compaction command + */ +export async function handleCompactCommand({ + chatHistory, + model, + llmApi, + setChatHistory, + setCompactionIndex, + currentSession, + setCurrentSession, +}: HandleCompactCommandOptions): Promise { + // Add compacting message + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: "Compacting chat history...", + }, + contextItems: [], + }, + ]); + + try { + // Compact the chat history directly (already in unified format) + const result = await compactChatHistory(chatHistory, model, llmApi); + + // Replace chat history with compacted version + setChatHistory(result.compactedHistory); + setCompactionIndex(result.compactionIndex); + + // Save the compacted session + const updatedSession: Session = { + ...currentSession, + history: result.compactedHistory, + }; + updateSessionHistory(result.compactedHistory); + setCurrentSession(updatedSession); + + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: "Chat history compacted successfully.", + }, + contextItems: [], + }, + ]); + } catch (error) { + logger.error("Compaction failed:", error); + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: `Compaction failed: ${formatError(error)}`, + }, + contextItems: [], + }, + ]); + } +} + +interface HandleAutoCompactionOptions { + chatHistory: ChatHistoryItem[]; + model: any; + llmApi: any; + compactionIndex: number | null; + setChatHistory: React.Dispatch>; + setCompactionIndex: React.Dispatch>; +} + +/** + * Handle auto-compaction when approaching context limit - TUI wrapper + */ +export async function handleAutoCompaction({ + chatHistory, + model, + llmApi, + compactionIndex: _compactionIndex, + setChatHistory, + setCompactionIndex, +}: HandleAutoCompactionOptions): Promise<{ + currentChatHistory: ChatHistoryItem[]; + currentCompactionIndex: number | null; +}> { + try { + // Check if auto-compaction is needed + // Check if auto-compaction is needed using ChatHistoryItem directly + if (!model || !shouldAutoCompact(chatHistory, model)) { + return { + currentChatHistory: chatHistory, + currentCompactionIndex: _compactionIndex, + }; + } + + logger.info("Auto-compaction triggered for TUI mode"); + + // Add compacting message + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: "Auto-compacting chat history...", + }, + contextItems: [], + }, + ]); + + // Compact the unified history + const result = await compactChatHistory(chatHistory, model, llmApi); + + // Keep the system message and append the compaction summary + // This replaces the old messages with a summary to reduce context size + const systemMessage = chatHistory.find( + (item) => item.message.role === "system", + ); + + const compactedMessage: ChatHistoryItem = { + message: { + role: "assistant" as const, + content: result.compactionContent, + }, + contextItems: [], + conversationSummary: result.compactionContent, // Mark this as a summary + }; + + // Create new history with system message (if exists) and compaction summary + const updatedHistory: ChatHistoryItem[] = systemMessage + ? [systemMessage, compactedMessage] + : [compactedMessage]; + + setChatHistory(updatedHistory); + setCompactionIndex(updatedHistory.length - 1); + + // Add success message + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: "✓ Chat history auto-compacted successfully.", + }, + contextItems: [], + }, + ]); + + return { + currentChatHistory: updatedHistory, + currentCompactionIndex: updatedHistory.length - 1, + }; + } catch (error) { + logger.error("Auto-compaction failed:", error); + + // Add error message + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: `Auto-compaction failed: ${formatError(error)}. Continuing without compaction...`, + }, + contextItems: [], + }, + ]); + + return { + currentChatHistory: chatHistory, + currentCompactionIndex: null, + }; + } +} diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index a8a744f56..f6d947d1c 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -1,212 +1,19 @@ import * as path from "node:path"; -import type { ChatHistoryItem, Session } from "core/index.js"; +import type { ChatHistoryItem } from "core/index.js"; import { getLastNPathParts } from "core/util/uri.js"; import { v4 as uuidv4 } from "uuid"; -import { compactChatHistory } from "../../compaction.js"; +import { logger } from "src/util/logger.js"; + import { DEFAULT_SESSION_TITLE } from "../../constants/session.js"; -import { - loadSession, - startNewSession, - updateSessionHistory, -} from "../../session.js"; +import { loadSession, startNewSession } from "../../session.js"; import { posthogService } from "../../telemetry/posthogService.js"; import { telemetryService } from "../../telemetry/telemetryService.js"; -import { formatError } from "../../util/formatError.js"; -import { logger } from "../../util/logger.js"; -import { shouldAutoCompact } from "../../util/tokenizer.js"; +import { processImagePlaceholder } from "./useChat.imageProcessing.js"; import { SlashCommandResult } from "./useChat.types.js"; -/** - * Dynamically import Sharp without using eval - */ -async function loadSharp(): Promise { - try { - // Use Function constructor to avoid bundler issues with dynamic imports - const importSharp = new Function('return import("sharp")'); - const sharpModule = await importSharp().catch(() => null); - return sharpModule ? sharpModule.default || sharpModule : null; - } catch { - return null; - } -} - -/** - * Process image buffer to JPEG with resizing using Sharp (if available) - */ -async function processImageWithSharp( - imageBuffer: Buffer, - maxWidth = 1024, - maxHeight = 1024, -): Promise<{ buffer: Buffer; isJpeg: boolean }> { - try { - // Try to load Sharp - it's an optional dependency - const sharp = await loadSharp(); - if (!sharp) { - logger.debug("Sharp not available, using original image buffer"); - return { buffer: imageBuffer, isJpeg: false }; - } - - logger.debug("Processing image with Sharp..."); - - // Process image: convert to JPEG and resize if needed - const processedBuffer = await sharp(imageBuffer) - .resize(maxWidth, maxHeight, { - fit: "inside", - withoutEnlargement: true, - }) - .jpeg({ - quality: 85, - progressive: true, - }) - .toBuffer(); - - logger.debug( - `Image processed with Sharp: ${imageBuffer.length} bytes -> ${processedBuffer.length} bytes`, - ); - return { buffer: processedBuffer, isJpeg: true }; - } catch (error) { - logger.warn("Failed to process image with Sharp, using original:", error); - return { buffer: imageBuffer, isJpeg: false }; - } -} - -/** - * Detect image format from buffer header - simplified to reduce complexity - */ -function detectImageFormat(buffer: Buffer): string { - if (buffer.length < 4) return "image/png"; - - const signature = buffer.subarray(0, 4); - - // JPEG: FF D8 FF - if (signature[0] === 0xff && signature[1] === 0xd8 && signature[2] === 0xff) { - return "image/jpeg"; - } - - // PNG: 89 50 4E 47 - if ( - signature[0] === 0x89 && - signature[1] === 0x50 && - signature[2] === 0x4e && - signature[3] === 0x47 - ) { - return "image/png"; - } - - // GIF: 47 49 46 38 - if ( - signature[0] === 0x47 && - signature[1] === 0x49 && - signature[2] === 0x46 && - signature[3] === 0x38 - ) { - return "image/gif"; - } - - // WebP: RIFF + WEBP at offset 8 - if (signature[0] === 0x52 && signature[1] === 0x49 && buffer.length >= 12) { - const webpSig = buffer.subarray(8, 12); - if ( - webpSig[0] === 0x57 && - webpSig[1] === 0x45 && - webpSig[2] === 0x42 && - webpSig[3] === 0x50 - ) { - return "image/webp"; - } - } - - return "image/png"; // Default fallback -} - -/** - * Process a single image placeholder - extracted to reduce nesting depth - */ -async function processImagePlaceholder( - placeholder: string, - originalImageBuffer: Buffer, - textContent: string, - messageParts: import("core/index.js").MessagePart[], -): Promise<{ textContent: string }> { - logger.debug( - `Processing image placeholder: ${placeholder}, original size: ${originalImageBuffer.length} bytes`, - ); - - try { - // Process image with Sharp (convert to JPEG and resize) - const processResult = await processImageWithSharp(originalImageBuffer); - const processedImageBuffer = processResult.buffer; - const isProcessedJpeg = processResult.isJpeg; - - // Check processed image size - const maxSize = 10 * 1024 * 1024; // 10MB limit - if (processedImageBuffer.length > maxSize) { - logger.warn( - `Processed image is still too large (${Math.round(processedImageBuffer.length / 1024 / 1024)}MB). Skipping image.`, - ); - return { - textContent: textContent.replace( - placeholder, - "[Large image skipped - reduce image size and try again]", - ), - }; - } - - // Convert processed buffer to base64 data URL asynchronously to avoid blocking - logger.debug("Converting processed image to base64..."); - const base64Image = await new Promise((resolve) => { - // Use setImmediate to yield to event loop - setImmediate(() => { - const result = processedImageBuffer.toString("base64"); - resolve(result); - }); - }); - - // Use correct MIME type based on whether Sharp processing was successful - const mimeType = isProcessedJpeg - ? "image/jpeg" - : detectImageFormat(processedImageBuffer); - const dataUrl = `data:${mimeType};base64,${base64Image}`; - logger.debug( - `Image converted to base64 with MIME type ${mimeType}, 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 - return { textContent: parts.slice(1).join(placeholder) }; - } - - return { textContent }; - } catch (error) { - logger.error(`Failed to process image ${placeholder}:`, error); - return { - textContent: textContent.replace( - placeholder, - "[Image processing failed]", - ), - }; - } -} - /** * Initialize chat history */ @@ -235,81 +42,6 @@ export function handleConfigCommand(onShowConfigSelector: () => void): void { onShowConfigSelector(); } -interface HandleCompactCommandOptions { - chatHistory: ChatHistoryItem[]; - model: any; - llmApi: any; - setChatHistory: React.Dispatch>; - setCompactionIndex: React.Dispatch>; - currentSession: Session; - setCurrentSession: React.Dispatch>; -} - -/** - * Handle compaction command - */ -export async function handleCompactCommand({ - chatHistory, - model, - llmApi, - setChatHistory, - setCompactionIndex, - currentSession, - setCurrentSession, -}: HandleCompactCommandOptions): Promise { - // Add compacting message - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Compacting chat history...", - }, - contextItems: [], - }, - ]); - - try { - // Compact the chat history directly (already in unified format) - const result = await compactChatHistory(chatHistory, model, llmApi); - - // Replace chat history with compacted version - setChatHistory(result.compactedHistory); - setCompactionIndex(result.compactionIndex); - - // Save the compacted session - const updatedSession: Session = { - ...currentSession, - history: result.compactedHistory, - }; - updateSessionHistory(result.compactedHistory); - setCurrentSession(updatedSession); - - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Chat history compacted successfully.", - }, - contextItems: [], - }, - ]); - } catch (error) { - logger.error("Compaction failed:", error); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: `Compaction failed: ${formatError(error)}`, - }, - contextItems: [], - }, - ]); - } -} - interface ProcessSlashCommandResultOptions { result: SlashCommandResult; chatHistory: ChatHistoryItem[]; @@ -521,117 +253,6 @@ export async function handleSpecialCommands({ return false; } -interface HandleAutoCompactionOptions { - chatHistory: ChatHistoryItem[]; - model: any; - llmApi: any; - compactionIndex: number | null; - setChatHistory: React.Dispatch>; - setCompactionIndex: React.Dispatch>; -} - -/** - * Handle auto-compaction when approaching context limit - TUI wrapper - */ -export async function handleAutoCompaction({ - chatHistory, - model, - llmApi, - compactionIndex: _compactionIndex, - setChatHistory, - setCompactionIndex, -}: HandleAutoCompactionOptions): Promise<{ - currentChatHistory: ChatHistoryItem[]; - currentCompactionIndex: number | null; -}> { - try { - // Check if auto-compaction is needed - // Check if auto-compaction is needed using ChatHistoryItem directly - if (!model || !shouldAutoCompact(chatHistory, model)) { - return { - currentChatHistory: chatHistory, - currentCompactionIndex: _compactionIndex, - }; - } - - logger.info("Auto-compaction triggered for TUI mode"); - - // Add compacting message - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Auto-compacting chat history...", - }, - contextItems: [], - }, - ]); - - // Compact the unified history - const result = await compactChatHistory(chatHistory, model, llmApi); - - // Keep the system message and append the compaction summary - // This replaces the old messages with a summary to reduce context size - const systemMessage = chatHistory.find( - (item) => item.message.role === "system", - ); - - const compactedMessage: ChatHistoryItem = { - message: { - role: "assistant" as const, - content: result.compactionContent, - }, - contextItems: [], - conversationSummary: result.compactionContent, // Mark this as a summary - }; - - // Create new history with system message (if exists) and compaction summary - const updatedHistory: ChatHistoryItem[] = systemMessage - ? [systemMessage, compactedMessage] - : [compactedMessage]; - - setChatHistory(updatedHistory); - setCompactionIndex(updatedHistory.length - 1); - - // Add success message - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "✓ Chat history auto-compacted successfully.", - }, - contextItems: [], - }, - ]); - - return { - currentChatHistory: updatedHistory, - currentCompactionIndex: updatedHistory.length - 1, - }; - } catch (error) { - logger.error("Auto-compaction failed:", error); - - // Add error message - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: `Auto-compaction failed: ${formatError(error)}. Continuing without compaction...`, - }, - contextItems: [], - }, - ]); - - return { - currentChatHistory: chatHistory, - currentCompactionIndex: null, - }; - } -} - /** * Generate a title for the session based on the first assistant response */ diff --git a/extensions/cli/src/ui/hooks/useChat.imageProcessing.ts b/extensions/cli/src/ui/hooks/useChat.imageProcessing.ts new file mode 100644 index 000000000..83db7a3cd --- /dev/null +++ b/extensions/cli/src/ui/hooks/useChat.imageProcessing.ts @@ -0,0 +1,189 @@ +import { logger } from "../../util/logger.js"; + +/** + * Dynamically import Sharp without using eval + */ +async function loadSharp(): Promise { + try { + // Use Function constructor to avoid bundler issues with dynamic imports + const importSharp = new Function('return import("sharp")'); + const sharpModule = await importSharp().catch(() => null); + return sharpModule ? sharpModule.default || sharpModule : null; + } catch { + return null; + } +} + +/** + * Process image buffer to JPEG with resizing using Sharp (if available) + */ +async function processImageWithSharp( + imageBuffer: Buffer, + maxWidth = 1024, + maxHeight = 1024, +): Promise<{ buffer: Buffer; isJpeg: boolean }> { + try { + // Try to load Sharp - it's an optional dependency + const sharp = await loadSharp(); + if (!sharp) { + logger.debug("Sharp not available, using original image buffer"); + return { buffer: imageBuffer, isJpeg: false }; + } + + logger.debug("Processing image with Sharp..."); + + // Process image: convert to JPEG and resize if needed + const processedBuffer = await sharp(imageBuffer) + .resize(maxWidth, maxHeight, { + fit: "inside", + withoutEnlargement: true, + }) + .jpeg({ + quality: 85, + progressive: true, + }) + .toBuffer(); + + logger.debug( + `Image processed with Sharp: ${imageBuffer.length} bytes -> ${processedBuffer.length} bytes`, + ); + return { buffer: processedBuffer, isJpeg: true }; + } catch (error) { + logger.warn("Failed to process image with Sharp, using original:", error); + return { buffer: imageBuffer, isJpeg: false }; + } +} + +/** + * Detect image format from buffer header - simplified to reduce complexity + */ +function detectImageFormat(buffer: Buffer): string { + if (buffer.length < 4) return "image/png"; + + const signature = buffer.subarray(0, 4); + + // JPEG: FF D8 FF + if (signature[0] === 0xff && signature[1] === 0xd8 && signature[2] === 0xff) { + return "image/jpeg"; + } + + // PNG: 89 50 4E 47 + if ( + signature[0] === 0x89 && + signature[1] === 0x50 && + signature[2] === 0x4e && + signature[3] === 0x47 + ) { + return "image/png"; + } + + // GIF: 47 49 46 38 + if ( + signature[0] === 0x47 && + signature[1] === 0x49 && + signature[2] === 0x46 && + signature[3] === 0x38 + ) { + return "image/gif"; + } + + // WebP: RIFF + WEBP at offset 8 + if (signature[0] === 0x52 && signature[1] === 0x49 && buffer.length >= 12) { + const webpSig = buffer.subarray(8, 12); + if ( + webpSig[0] === 0x57 && + webpSig[1] === 0x45 && + webpSig[2] === 0x42 && + webpSig[3] === 0x50 + ) { + return "image/webp"; + } + } + + return "image/png"; // Default fallback +} + +/** + * Process a single image placeholder - extracted to reduce nesting depth + */ +export async function processImagePlaceholder( + placeholder: string, + originalImageBuffer: Buffer, + textContent: string, + messageParts: import("core/index.js").MessagePart[], +): Promise<{ textContent: string }> { + logger.debug( + `Processing image placeholder: ${placeholder}, original size: ${originalImageBuffer.length} bytes`, + ); + + try { + // Process image with Sharp (convert to JPEG and resize) + const processResult = await processImageWithSharp(originalImageBuffer); + const processedImageBuffer = processResult.buffer; + const isProcessedJpeg = processResult.isJpeg; + + // Check processed image size + const maxSize = 10 * 1024 * 1024; // 10MB limit + if (processedImageBuffer.length > maxSize) { + logger.warn( + `Processed image is still too large (${Math.round(processedImageBuffer.length / 1024 / 1024)}MB). Skipping image.`, + ); + return { + textContent: textContent.replace( + placeholder, + "[Large image skipped - reduce image size and try again]", + ), + }; + } + + // Convert processed buffer to base64 data URL asynchronously to avoid blocking + logger.debug("Converting processed image to base64..."); + const base64Image = await new Promise((resolve) => { + // Use setImmediate to yield to event loop + setImmediate(() => { + const result = processedImageBuffer.toString("base64"); + resolve(result); + }); + }); + + // Use correct MIME type based on whether Sharp processing was successful + const mimeType = isProcessedJpeg + ? "image/jpeg" + : detectImageFormat(processedImageBuffer); + const dataUrl = `data:${mimeType};base64,${base64Image}`; + logger.debug( + `Image converted to base64 with MIME type ${mimeType}, 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 + return { textContent: parts.slice(1).join(placeholder) }; + } + + return { textContent }; + } catch (error) { + logger.error(`Failed to process image ${placeholder}:`, error); + return { + textContent: textContent.replace( + placeholder, + "[Image processing failed]", + ), + }; + } +} diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index ac67fa8d3..4e5f5ceb9 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -16,9 +16,11 @@ import { formatError } from "../../util/formatError.js"; import { logger } from "../../util/logger.js"; import { - formatMessageWithFiles, handleAutoCompaction, handleCompactCommand, +} from "./useChat.compaction.js"; +import { + formatMessageWithFiles, handleSpecialCommands, initChatHistory, processSlashCommandResult, From 13876a240268882149721d1ce4a74a1fff88143d Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 18:08:10 -0700 Subject: [PATCH 07/10] fix long func --- extensions/cli/src/ui/hooks/useChat.ts | 177 ++++++++++++++----------- 1 file changed, 100 insertions(+), 77 deletions(-) diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index c4e0883ce..479fab094 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -255,36 +255,103 @@ export function useChat({ } }; + const handleResumeRequest = async (message: string) => { + if (message !== "" || !wasInterrupted) return false; + + // Find the index of the last user or tool message to resume from + let lastUserOrToolIndex = -1; + for (let i = chatHistory.length - 1; i >= 0; i--) { + if ( + chatHistory[i].message.role === "user" || + !!chatHistory[i].toolCallStates?.length + ) { + lastUserOrToolIndex = i; + break; + } + } + + if (lastUserOrToolIndex >= 0) { + // Truncate history to include up to and including the user/tool message + const truncatedHistory = chatHistory.slice(0, lastUserOrToolIndex + 1); + setChatHistory(truncatedHistory); + + // Clear the interrupted state and resume + setWasInterrupted(false); + + // Re-execute streaming with the truncated history + await executeStreamingResponse(truncatedHistory, compactionIndex); + return true; + } + + return false; + }; + + const handleSlashCommandProcessing = async ( + message: string, + ): Promise => { + // Handle slash commands (skip in remote mode except for /exit which we handled above) + if (isRemoteMode || !assistant) { + return message; + } + + const commandResult = await handleSlashCommands(message, assistant); + if (!commandResult) { + return message; + } + + if (commandResult.compact) { + await handleCompactCommand({ + chatHistory, + model, + llmApi, + setChatHistory, + setCompactionIndex, + currentSession, + setCurrentSession, + }); + return null; + } + + const newInput = processSlashCommandResult({ + result: commandResult, + chatHistory, + setChatHistory, + exit, + onShowConfigSelector, + onShowModelSelector, + onShowMCPSelector, + onShowSessionSelector, + onClear, + }); + + return newInput || null; + }; + + const convertMessageContentToString = (content: any): string => { + if (typeof content === "string") { + return content; + } + + // Convert MessagePart[] to string (extracting text, noting images) + return content + .map((part: any) => { + if (part.type === "text") { + return part.text; + } else if (part.type === "imageUrl") { + return "[Image]"; + } + return ""; + }) + .join(""); + }; + const handleUserMessage = async ( message: string, imageMap?: Map, ) => { // Check if this is a resume request (empty message after interruption) - if (message === "" && wasInterrupted) { - // Find the index of the last user or tool message to resume from - let lastUserOrToolIndex = -1; - for (let i = chatHistory.length - 1; i >= 0; i--) { - if ( - chatHistory[i].message.role === "user" || - !!chatHistory[i].toolCallStates?.length - ) { - lastUserOrToolIndex = i; - break; - } - } - - if (lastUserOrToolIndex >= 0) { - // Truncate history to include up to and including the user/tool message - const truncatedHistory = chatHistory.slice(0, lastUserOrToolIndex + 1); - setChatHistory(truncatedHistory); - - // Clear the interrupted state and resume - setWasInterrupted(false); - - // Re-execute streaming with the truncated history - await executeStreamingResponse(truncatedHistory, compactionIndex); - return; - } + if (await handleResumeRequest(message)) { + return; } // Clear interrupted state if user types a new message @@ -304,42 +371,12 @@ export function useChat({ if (handled) return; - // Handle slash commands (skip in remote mode except for /exit which we handled above) - if (!isRemoteMode && assistant) { - const commandResult = await handleSlashCommands(message, assistant); - if (commandResult) { - if (commandResult.compact) { - await handleCompactCommand({ - chatHistory, - model, - llmApi, - setChatHistory, - setCompactionIndex, - currentSession, - setCurrentSession, - }); - return; - } - - const newInput = processSlashCommandResult({ - result: commandResult, - chatHistory, - setChatHistory, - exit, - onShowConfigSelector, - onShowModelSelector, - onShowMCPSelector, - onShowSessionSelector, - onClear, - }); - - if (newInput) { - message = newInput; - } else { - return; - } - } + // Handle slash commands + const processedMessage = await handleSlashCommandProcessing(message); + if (processedMessage === null) { + return; // Command was handled and no further processing needed } + message = processedMessage; // Track telemetry trackUserMessage(message, model); @@ -362,23 +399,9 @@ export function useChat({ // 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(""); - } + const messageContentString = convertMessageContentToString( + newUserMessage.message.content, + ); await handleRemoteMessage({ remoteUrl, From 39dde5a460fd4e11722ec8cdbdfe35f43d85a944 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 18:29:58 -0700 Subject: [PATCH 08/10] fix failing tests --- .../cli/src/ui/__tests__/TUIChat.interruption.minimal.test.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/ui/__tests__/TUIChat.interruption.minimal.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.interruption.minimal.test.tsx index 49a060fbf..6dc292cad 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.interruption.minimal.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.interruption.minimal.test.tsx @@ -117,7 +117,7 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { stdin.write("\r"); // Should call onSubmit with empty string (for resume) - expect(mockOnSubmit).toHaveBeenCalledWith(""); + expect(mockOnSubmit).toHaveBeenCalledWith("", expect.any(Map)); } finally { unmount(); } @@ -145,6 +145,7 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => { // Should call onSubmit with the typed content expect(mockOnSubmit).toHaveBeenCalledWith( "New message after interruption", + expect.any(Map), ); } finally { unmount(); From c87032b0373c963e0e1d50dfb99f5dc8c1b6dfce Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 31 Aug 2025 18:59:28 -0700 Subject: [PATCH 09/10] fix: address feedback --- extensions/cli/src/ui/TextBuffer.ts | 29 +++++++++++++++++++ .../MemoizedMessage.formatDisplay.test.tsx | 7 +++-- extensions/cli/src/ui/hooks/useUserInput.ts | 2 +- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/extensions/cli/src/ui/TextBuffer.ts b/extensions/cli/src/ui/TextBuffer.ts index aa24caf19..121deb46c 100644 --- a/extensions/cli/src/ui/TextBuffer.ts +++ b/extensions/cli/src/ui/TextBuffer.ts @@ -2,6 +2,9 @@ import { Key } from "ink"; export const COLLAPSE_SIZE = 800; // Characters threshold for collapsing pasted content export const RAPID_INPUT_THRESHOLD = 200; // Minimum characters to trigger rapid input detection +export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB per image +export const MAX_IMAGE_COUNT = 20; // Maximum number of images +export const MAX_TOTAL_IMAGE_MEMORY = 50 * 1024 * 1024; // 50MB total image memory export class TextBuffer { private _text: string = ""; @@ -195,6 +198,32 @@ export class TextBuffer { // Add image to buffer and return placeholder addImage(imageBuffer: Buffer): string { + // Validate image size + if (imageBuffer.length > MAX_IMAGE_SIZE) { + throw new Error( + `Image size ${(imageBuffer.length / 1024 / 1024).toFixed(1)}MB exceeds maximum allowed size of ${MAX_IMAGE_SIZE / 1024 / 1024}MB`, + ); + } + + // Check image count limit + if (this._imageMap.size >= MAX_IMAGE_COUNT) { + throw new Error(`Cannot add more than ${MAX_IMAGE_COUNT} images`); + } + + // Check total memory usage + const currentMemoryUsage = Array.from(this._imageMap.values()).reduce( + (total, buffer) => total + buffer.length, + 0, + ); + + if (currentMemoryUsage + imageBuffer.length > MAX_TOTAL_IMAGE_MEMORY) { + const currentUsageMB = (currentMemoryUsage / 1024 / 1024).toFixed(1); + const maxUsageMB = MAX_TOTAL_IMAGE_MEMORY / 1024 / 1024; + throw new Error( + `Adding image would exceed total memory limit. Current usage: ${currentUsageMB}MB, Maximum: ${maxUsageMB}MB`, + ); + } + this._imageCounter++; const placeholder = `[Image #${this._imageCounter}]`; this._imageMap.set(placeholder, imageBuffer); diff --git a/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx b/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx index 2aa171cf3..7183bdf82 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx @@ -126,9 +126,10 @@ describe("MemoizedMessage formatMessageContentForDisplay", () => { ); const output = lastFrame(); - expect(output).toContain("Start"); - expect(output).toContain("end"); - expect(output).toContain('{"type":"unknown","data":{"some":"data"}}'); + // Verify whitespace preservation - trailing space after "Start" and leading space before "end" + expect(output).toContain( + 'Start {"type":"unknown","data":{"some":"data"}} end', + ); }); it("should handle non-array non-string content by converting to JSON", () => { diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index 666b04121..558df58d6 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -83,7 +83,7 @@ async function getClipboardImage(): Promise { } 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"`, + `powershell -command "$image = Get-Clipboard -Format Image; if ($image) { $image.Save('${tempImagePath}') }"`, ); } else if (platform === "linux") { // Linux: Use xclip to save clipboard image From 1a7ab26c37a202cf66aff67239828ac77453cb47 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 1 Sep 2025 11:01:42 -0700 Subject: [PATCH 10/10] fix: install sharp in right place --- extensions/cli/package-lock.json | 223 +++++++++++++++++++++++++++++++ extensions/cli/package.json | 78 ++++++----- package-lock.json | 217 ------------------------------ package.json | 8 -- 4 files changed, 266 insertions(+), 260 deletions(-) diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index 6da2ba6db..b6154c67b 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -9,6 +9,12 @@ "version": "0.0.0-dev", "license": "Apache-2.0", "dependencies": { + "@img/sharp-darwin-arm64": "^0.33.5", + "@img/sharp-darwin-x64": "^0.33.5", + "@img/sharp-linux-arm": "^0.33.5", + "@img/sharp-linux-arm64": "^0.33.5", + "@img/sharp-linux-x64": "^0.33.5", + "@img/sharp-win32-x64": "^0.33.5", "@sentry/profiling-node": "^9.43.0" }, "bin": { @@ -98,6 +104,14 @@ "vitest": "^3.2.4", "winston": "^3.17.0", "yaml": "^2.8.0" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "^0.33.5", + "@img/sharp-darwin-x64": "^0.33.5", + "@img/sharp-linux-arm": "^0.33.5", + "@img/sharp-linux-arm64": "^0.33.5", + "@img/sharp-linux-x64": "^0.33.5", + "@img/sharp-win32-x64": "^0.33.5" } }, "../../core": { @@ -1256,6 +1270,215 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", + "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", + "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", + "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", + "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", + "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", + "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", + "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.0.5" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", + "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", + "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/@isaacs/balanced-match": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz", diff --git a/extensions/cli/package.json b/extensions/cli/package.json index bdc480e60..68490c7c4 100644 --- a/extensions/cli/package.json +++ b/extensions/cli/package.json @@ -59,79 +59,87 @@ "@opentelemetry/resources": "^2.0.1", "@opentelemetry/sdk-node": "^0.203.0", "@opentelemetry/semantic-conventions": "^1.36.0", - "@sentry/node": "^9.43.0", - "@types/express": "^5.0.3", - "@types/react": "^19.1.8", - "@types/turndown": "^5.0.5", - "@workos-inc/node": "^7.45.0", - "chalk": "^5.4.1", - "commander": "^14.0.0", - "core": "file:../../core", - "date-fns": "^4.1.0", - "diff": "^7.0.0", - "dotenv": "^16.5.0", - "express": "^5.1.0", - "glob": "^11.0.3", - "gpt-tokenizer": "^3.0.1", - "gradient-string": "^3.0.0", - "ignore": "^7.0.5", - "ignore-walk": "^7.0.0", - "ink": "^6.1.0", - "jszip": "^3.10.1", - "lowlight": "^3.3.0", - "minimatch": "^10.0.3", - "node-fetch": "^3.3.2", - "node-machine-id": "^1.1.12", - "open": "^10.1.0", - "posthog-node": "^5.6.0", - "react": "^19.1.0", - "readline-sync": "^1.4.10", - "shell-quote": "^1.8.3", - "swr": "^2.3.4", - "turndown": "^7.2.0", - "typescript": "^5.8.3", - "uuid": "^9.0.1", - "winston": "^3.17.0", - "yaml": "^2.8.0", "@semantic-release/changelog": "^6.0.3", "@semantic-release/git": "^10.0.1", "@semantic-release/github": "^11.0.3", "@semantic-release/npm": "^12.0.2", + "@sentry/node": "^9.43.0", "@testing-library/react": "^16.3.0", "@types/date-fns": "^2.5.3", "@types/diff": "^7.0.2", + "@types/express": "^5.0.3", "@types/glob": "^8.1.0", "@types/ignore-walk": "^4.0.3", "@types/ink-testing-library": "^1.0.4", "@types/jszip": "^3.4.0", "@types/nock": "^10.0.3", + "@types/react": "^19.1.8", "@types/readline-sync": "^1.4.8", "@types/shell-quote": "^1.7.5", "@types/supertest": "^6.0.3", + "@types/turndown": "^5.0.5", "@types/uuid": "^10.0.0", "@typescript-eslint/eslint-plugin": "^8.39.0", "@typescript-eslint/parser": "^8.39.0", "@vitest/ui": "^3.2.4", + "@workos-inc/node": "^7.45.0", + "chalk": "^5.4.1", + "commander": "^14.0.0", "conventional-changelog-conventionalcommits": "^9.1.0", + "core": "file:../../core", "cross-env": "^7.0.3", + "date-fns": "^4.1.0", + "diff": "^7.0.0", + "dotenv": "^16.5.0", "esbuild": "^0.25.9", "eslint": "^9.32.0", "eslint-import-resolver-typescript": "^4.4.4", "eslint-plugin-import": "^2.32.0", "eslint-plugin-unused-imports": "^4.1.4", "execa": "^9.6.0", + "express": "^5.1.0", + "glob": "^11.0.3", + "gpt-tokenizer": "^3.0.1", + "gradient-string": "^3.0.0", "happy-dom": "^18.0.1", + "ignore": "^7.0.5", + "ignore-walk": "^7.0.0", + "ink": "^6.1.0", "ink-testing-library": "^4.0.0", "jsdom": "^26.1.0", + "jszip": "^3.10.1", + "lowlight": "^3.3.0", + "minimatch": "^10.0.3", "nock": "^14.0.5", + "node-fetch": "^3.3.2", + "node-machine-id": "^1.1.12", + "open": "^10.1.0", + "posthog-node": "^5.6.0", "prettier": "^3.6.2", + "react": "^19.1.0", + "readline-sync": "^1.4.10", "semantic-release": "^24.2.7", + "shell-quote": "^1.8.3", "supertest": "^7.1.3", + "swr": "^2.3.4", "ts-node": "^10.9.2", "tsx": "^4.20.3", - "vitest": "^3.2.4" + "turndown": "^7.2.0", + "typescript": "^5.8.3", + "uuid": "^9.0.1", + "vitest": "^3.2.4", + "winston": "^3.17.0", + "yaml": "^2.8.0" }, "engine": { "node": ">=18" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "^0.33.5", + "@img/sharp-darwin-x64": "^0.33.5", + "@img/sharp-linux-arm": "^0.33.5", + "@img/sharp-linux-arm64": "^0.33.5", + "@img/sharp-linux-x64": "^0.33.5", + "@img/sharp-win32-x64": "^0.33.5" } } diff --git a/package-lock.json b/package-lock.json index 88967f48a..b3ddaef8f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,14 +12,6 @@ "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8", "typescript": "^5.6.3" - }, - "optionalDependencies": { - "@img/sharp-darwin-arm64": "^0.33.5", - "@img/sharp-darwin-x64": "^0.33.5", - "@img/sharp-linux-arm": "^0.33.5", - "@img/sharp-linux-arm64": "^0.33.5", - "@img/sharp-linux-x64": "^0.33.5", - "@img/sharp-win32-x64": "^0.33.5" } }, "node_modules/@eslint-community/eslint-utils": { @@ -182,215 +174,6 @@ "license": "BSD-3-Clause", "peer": true }, - "node_modules/@img/sharp-darwin-arm64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", - "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.0.4" - } - }, - "node_modules/@img/sharp-darwin-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", - "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.0.4" - } - }, - "node_modules/@img/sharp-libvips-darwin-arm64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", - "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", - "cpu": [ - "arm64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "darwin" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-darwin-x64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", - "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", - "cpu": [ - "x64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "darwin" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-arm": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", - "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", - "cpu": [ - "arm" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-arm64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", - "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", - "cpu": [ - "arm64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-x64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", - "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", - "cpu": [ - "x64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-linux-arm": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", - "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", - "cpu": [ - "arm" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.0.5" - } - }, - "node_modules/@img/sharp-linux-arm64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", - "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.0.4" - } - }, - "node_modules/@img/sharp-linux-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", - "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.0.4" - } - }, - "node_modules/@img/sharp-win32-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", - "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", diff --git a/package.json b/package.json index d5d14d6fc..28cdb97d8 100644 --- a/package.json +++ b/package.json @@ -16,13 +16,5 @@ "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8", "typescript": "^5.6.3" - }, - "optionalDependencies": { - "@img/sharp-darwin-arm64": "^0.33.5", - "@img/sharp-darwin-x64": "^0.33.5", - "@img/sharp-linux-arm": "^0.33.5", - "@img/sharp-linux-arm64": "^0.33.5", - "@img/sharp-linux-x64": "^0.33.5", - "@img/sharp-win32-x64": "^0.33.5" } }