The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): downscale large images in composer preview to prevent UI freeze
David Metcalfe24fc613318af
diff --git a/apps/desktop/src/app/chat/hooks/use-composer-actions.ts b/apps/desktop/src/app/chat/hooks/use-composer-actions.tsindex 0ff553d0334..ea8afa19be5 100644--- a/apps/desktop/src/app/chat/hooks/use-composer-actions.ts+++ b/apps/desktop/src/app/chat/hooks/use-composer-actions.ts@@ -7,6 +7,7 @@ import { useI18n } from '@/i18n'import { attachmentId, contextPath, pathLabel } from '@/lib/chat-runtime'import { readDesktopFileDataUrl, selectDesktopPaths } from '@/lib/desktop-fs'import { desktopGit } from '@/lib/desktop-git'+import { downscaleDataUrlForPreview } from '@/lib/image-resize'import { normalize } from '@/lib/text'import {addComposerAttachment,@@ -52,17 +53,29 @@ export function isImagePath(filePath: string): boolean {* In local mode the facade IS the local bridge, so this stays a single read.*/export async function attachmentPreviewDataUrl(filePath: string): Promise<string> {+ let dataUrl: string+try {const local = await window.hermesDesktop?.readFileDataUrl?.(filePath)if (local) {- return local+ dataUrl = local+ } else {+ dataUrl = await readDesktopFileDataUrl(filePath)}} catch {// Not on this machine (or unreadable locally) — try the gateway.+ dataUrl = await readDesktopFileDataUrl(filePath)+ }++ // Downscale large images for preview to prevent main-thread decode freezes.+ // macOS ImageIO/vImage blocks the Chromium renderer on Retina screenshots+ // (6000×4000+, >5 MB). The full-resolution bytes are still on disk for the model.+ if (dataUrl.startsWith('data:image/')) {+ return downscaleDataUrlForPreview(dataUrl)}- return readDesktopFileDataUrl(filePath)+ return dataUrl}export interface DroppedFile {diff --git a/apps/desktop/src/lib/image-resize.test.ts b/apps/desktop/src/lib/image-resize.test.tsnew file mode 100644index 00000000000..5d44a13c712--- /dev/null+++ b/apps/desktop/src/lib/image-resize.test.ts@@ -0,0 +1,168 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { downscaleDataUrlForPreview } from './image-resize'++// A minimal valid 1x1 red PNG (67 bytes) for testing+const TINY_PNG_B64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+GkZcAAAAASUVORK5CYII='+const TINY_PNG_DATA_URL = `data:image/png;base64,${TINY_PNG_B64}`++// A 1×1 transparent PNG used as the fallback placeholder+const FALLBACK_PLACEHOLDER =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+GkZcAAAAASUVORK5CYII='++describe('downscaleDataUrlForPreview', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ })++ describe('without createImageBitmap (jsdom default)', () => {+ it('returns the original when createImageBitmap is unavailable', async () => {+ await expect(downscaleDataUrlForPreview(TINY_PNG_DATA_URL)).resolves.toBe(+ TINY_PNG_DATA_URL+ )+ })++ it('returns the original for a non-data-URL string', async () => {+ await expect(downscaleDataUrlForPreview('not-a-data-url')).resolves.toBe(+ 'not-a-data-url'+ )+ })++ it('returns the original for a data URL without a comma', async () => {+ await expect(downscaleDataUrlForPreview('data:text/plain')).resolves.toBe(+ 'data:text/plain'+ )+ })+ })++ describe('with mocked createImageBitmap + OffscreenCanvas', () => {+ /**+ * Set up the full mock chain: fetch → createImageBitmap → OffscreenCanvas → FileReader.+ * Mocks a bitmap of the given dimensions so the downscaling logic is exercised.+ */+ function setupMocks(bitmapWidth: number, bitmapHeight: number) {+ const close = vi.fn()+ const drawImage = vi.fn()+ const convertToBlob = vi.fn(async () => new Blob(['x'], { type: 'image/png' }))++ const bitmap = { width: bitmapWidth, height: bitmapHeight, close }+ const ctx = { drawImage }++ class MockOffscreenCanvas {+ getContext = vi.fn(() => ctx)+ convertToBlob = convertToBlob+ constructor(_w: number, _h: number) {}+ }++ // Mock fetch to return a Blob from the data URL+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({+ blob: async () => new Blob([new Uint8Array([0])], { type: 'image/png' })+ }))+ )+ vi.stubGlobal('createImageBitmap', vi.fn(async () => bitmap))+ vi.stubGlobal('OffscreenCanvas', MockOffscreenCanvas)++ return { bitmap, close, drawImage, convertToBlob, ctx }+ }++ it('returns the original when image is smaller than maxLongEdge', async () => {+ setupMocks(500, 300)++ const result = await downscaleDataUrlForPreview(TINY_PNG_DATA_URL, 2048)+ expect(result).toBe(TINY_PNG_DATA_URL)+ })++ it('downscales when image exceeds maxLongEdge', async () => {+ const { drawImage, close } = setupMocks(4000, 3000)++ // In jsdom, FileReader.readAsDataURL won't actually produce a data URL,+ // so the function falls through to the fallback placeholder. But the+ // important thing is that drawImage was called with scaled dimensions+ // and the bitmap was closed.+ const result = await downscaleDataUrlForPreview(TINY_PNG_DATA_URL, 2048)++ // scale = 2048 / 4000 = 0.512 → width=2048, height=1536+ expect(drawImage).toHaveBeenCalledWith(expect.anything(), 0, 0, 2048, 1536)+ expect(close).toHaveBeenCalled()++ // Result should be the downscaled data URL (from our mocked blob),+ // NOT the original tiny PNG — the function attempted downscaling.+ expect(result).not.toBe(TINY_PNG_DATA_URL)+ // The drawImage was called with correct dimensions and bitmap was cleaned up+ expect(drawImage).toHaveBeenCalled()+ expect(close).toHaveBeenCalled()+ })++ it('returns placeholder when createImageBitmap throws', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({+ blob: async () => new Blob([new Uint8Array([0])], { type: 'image/png' })+ }))+ )+ vi.stubGlobal(+ 'createImageBitmap',+ vi.fn(async () => {+ throw new Error('decode failed')+ })+ )+ vi.stubGlobal('OffscreenCanvas', vi.fn(() => ({})))++ const result = await downscaleDataUrlForPreview(TINY_PNG_DATA_URL, 2048)+ expect(result).toBe(FALLBACK_PLACEHOLDER)+ })++ it('closes bitmap even when canvas getContext returns null', async () => {+ const close = vi.fn()+ const bitmap = { width: 4000, height: 3000, close }++ class NullCanvas {+ getContext = () => null+ constructor(_w: number, _h: number) {}+ }++ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({+ blob: async () => new Blob([new Uint8Array([0])], { type: 'image/png' })+ }))+ )+ vi.stubGlobal('createImageBitmap', vi.fn(async () => bitmap))+ vi.stubGlobal('OffscreenCanvas', NullCanvas)++ const result = await downscaleDataUrlForPreview(TINY_PNG_DATA_URL, 2048)+ expect(result).toBe(FALLBACK_PLACEHOLDER)+ expect(close).toHaveBeenCalled()+ })++ it('uses placeholder instead of original on convertToBlob failure', async () => {+ const close = vi.fn()+ const bitmap = { width: 4000, height: 3000, close }++ class BrokenCanvas {+ getContext = () => ({ drawImage: vi.fn() })+ convertToBlob = vi.fn(async () => {+ throw new Error('blob failed')+ })+ constructor(_w: number, _h: number) {}+ }++ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({+ blob: async () => new Blob([new Uint8Array([0])], { type: 'image/png' })+ }))+ )+ vi.stubGlobal('createImageBitmap', vi.fn(async () => bitmap))+ vi.stubGlobal('OffscreenCanvas', BrokenCanvas)++ const result = await downscaleDataUrlForPreview(TINY_PNG_DATA_URL, 2048)+ expect(result).toBe(FALLBACK_PLACEHOLDER)+ expect(close).toHaveBeenCalled()+ })+ })+})diff --git a/apps/desktop/src/lib/image-resize.ts b/apps/desktop/src/lib/image-resize.tsnew file mode 100644index 00000000000..534dfa76591--- /dev/null+++ b/apps/desktop/src/lib/image-resize.ts@@ -0,0 +1,92 @@+/**+ * Downscale a data URL for preview rendering.+ *+ * Large images (Retina screenshots, 6000×4000+) cause the Chromium main thread+ * to block during <img> decode because macOS ImageIO/vImage decodes synchronously.+ * This utility uses createImageBitmap + OffscreenCanvas to resize *before* the+ * data URL is assigned to an <img> element, keeping the preview fast.+ *+ * Full-resolution bytes are still saved to disk for the model — only the preview+ * thumbnail is downscaled.+ *+ * @param dataUrl The full-resolution data URL (data:image/...;base64,...)+ * @param maxLongEdge Maximum pixel dimension on the longest side (default 2048)+ * @returns A downscaled data URL (PNG), the original if already small enough,+ * or a 1×1 transparent PNG placeholder if downscaling fails.+ */++/** 1×1 transparent PNG — used when downscaling fails so the UI never receives a multi-MB data URL. */+const FALLBACK_PLACEHOLDER =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+GkZcAAAAASUVORK5CYII='++export async function downscaleDataUrlForPreview(+ dataUrl: string,+ maxLongEdge = 2048+): Promise<string> {+ // Guard: createImageBitmap and OffscreenCanvas are not available in jsdom+ // (test environment) or very old Chromium builds. Return the original if missing.+ if (typeof createImageBitmap !== 'function' || typeof OffscreenCanvas !== 'function') {+ return dataUrl+ }++ const commaIndex = dataUrl.indexOf(',')++ if (commaIndex === -1) {+ return dataUrl+ }++ try {+ // fetch(dataUrl) decodes base64 natively in C++ — avoids the O(n) atob()+ // + charCodeAt loop that creates main-thread jank for multi-MB images.+ const blob = await fetch(dataUrl).then(r => r.blob())++ // createImageBitmap decodes off the main thread in Chromium, but the+ // operation may still be costly for >5 MB retina screenshots; we then+ // resize quickly with OffscreenCanvas.+ const bitmap = await createImageBitmap(blob)++ try {+ const { width, height } = bitmap+ const longEdge = Math.max(width, height)++ if (longEdge <= maxLongEdge) {+ return dataUrl+ }++ const scale = maxLongEdge / longEdge+ const newWidth = Math.round(width * scale)+ const newHeight = Math.round(height * scale)++ const canvas = new OffscreenCanvas(newWidth, newHeight)+ const ctx = canvas.getContext('2d')++ if (!ctx) {+ return FALLBACK_PLACEHOLDER+ }++ ctx.drawImage(bitmap, 0, 0, newWidth, newHeight)++ const resultBlob = await canvas.convertToBlob({ type: 'image/png' })+ const reader = new FileReader()++ return new Promise<string>(resolve => {+ reader.onloadend = () => {+ if (typeof reader.result === 'string') {+ resolve(reader.result)+ } else {+ resolve(FALLBACK_PLACEHOLDER)+ }+ }+ reader.onerror = () => resolve(FALLBACK_PLACEHOLDER)+ reader.readAsDataURL(resultBlob)+ })+ } finally {+ bitmap.close()+ }+ } catch {+ // Downscaling failed (unsupported format, OOM, etc.) — return a tiny+ // placeholder rather than the original multi-MB data URL, which would+ // re-introduce the main-thread decode freeze this function exists to prevent.+ return FALLBACK_PLACEHOLDER+ }+}