Skip to content

The agent that grows with you

fix(desktop): keep image frames stable through delayed loads

BearHuddlestona69f86042c67
diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.tsx
index 73d8eb47dba..c7c955d1676 100644
--- a/apps/desktop/src/components/assistant-ui/markdown-text.tsx
+++ b/apps/desktop/src/components/assistant-ui/markdown-text.tsx
@@ -16,6 +16,7 @@ import { chunkByLines, SyntaxHighlighter } from '@/components/chat/shiki-highlig
import { TranscriptVideo } from '@/components/chat/transcript-video'
import { ZoomableImage } from '@/components/chat/zoomable-image'
import { ErrorBoundary } from '@/components/error-boundary'
+import { useMediaImage } from '@/hooks/use-media-image'
import { detectArtifact } from '@/lib/artifact-detect'
import { renderMediaTags } from '@/lib/chat-messages/parts'
import { normalizeExternalUrl, openExternalLink, PrettyLink } from '@/lib/external-link'
@@ -25,15 +26,14 @@ import { preprocessMarkdown } from '@/lib/markdown-preprocess'
import {
downloadGatewayMediaFile,
isFileMediaPath,
- isInlineMediaSrc,
isMarkdownDocumentPath,
isRemoteGateway,
mediaExternalUrl,
mediaKind,
mediaName,
mediaPathFromMarkdownHref,
- resolveMediaDisplaySrc,
- resolveMediaPlaybackSrc
+ resolveMediaPlaybackSrc,
+ validImageDimensions
} from '@/lib/media'
import { isOnboardingEnabled } from '@/lib/onboarding-enabled'
import { previewTargetFromMarkdownHref } from '@/lib/preview-targets'
@@ -151,6 +151,14 @@ function OpenMediaButton({ kind, path }: { kind: 'audio' | 'video'; path: string
}
function MediaAttachment({ path }: { path: string }) {
+ return mediaKind(path) === 'image' ? (
+ <MarkdownImage alt={mediaName(path)} src={path} />
+ ) : (
+ <MediaPlaybackAttachment path={path} />
+ )
+}
+
+function MediaPlaybackAttachment({ path }: { path: string }) {
const [src, setSrc] = useState('')
const [failed, setFailed] = useState(false)
const { open, openFailed } = useOpenMediaFile(path)
@@ -199,14 +207,6 @@ function MediaAttachment({ path }: { path: string }) {
}
}, [kind, path])
- if (kind === 'image' && src) {
- return (
- <span className="block">
- <MarkdownImage alt={name} src={src} />
- </span>
- )
- }
-
if (kind === 'audio' && src) {
return (
<span className="my-3 block max-w-md rounded-xl border border-(--ui-stroke-tertiary) bg-muted/35 p-3">
@@ -374,78 +374,60 @@ export function MarkdownImage(props: ComponentProps<'img'>) {
return <MarkdownImageContent {...props} />
}
-function MarkdownImageContent({ className, src, alt, ...props }: ComponentProps<'img'>) {
+function MarkdownImageContent({
+ className,
+ src,
+ alt,
+ width,
+ height,
+ onLoad,
+ onError,
+ style,
+ ...props
+}: ComponentProps<'img'>) {
const rawSrc = typeof src === 'string' ? src : ''
- const [resolvedSrc, setResolvedSrc] = useState(() => (rawSrc && isInlineMediaSrc(rawSrc) ? rawSrc : ''))
- const [failed, setFailed] = useState(false)
+ const image = useMediaImage(rawSrc, 16 / 9, validImageDimensions(width, height))
const { open, openFailed } = useOpenMediaFile(rawSrc)
const name = mediaName(rawSrc || String(alt || 'image'))
- useEffect(() => {
- let cancelled = false
-
- setFailed(false)
- setResolvedSrc(rawSrc && isInlineMediaSrc(rawSrc) ? rawSrc : '')
-
- if (!rawSrc || isInlineMediaSrc(rawSrc)) {
- return () => {
- cancelled = true
- }
- }
-
- void resolveMediaDisplaySrc(rawSrc)
- .then(value => {
- if (!cancelled) {
- setResolvedSrc(value)
- }
- })
- .catch(() => {
- if (!cancelled) {
- setFailed(true)
- }
- })
-
- return () => {
- cancelled = true
- }
- }, [rawSrc])
-
if (!rawSrc) {
return null
}
- if (failed) {
- return (
- <span className="my-2 block text-sm text-muted-foreground">
- Couldn&apos;t load {name}.{' '}
- <button className="ref font-medium text-foreground" onClick={open} type="button">
- Open image
- </button>
- {openFailed && <OpenMediaFailedNote name={name} />}
- </span>
- )
- }
-
- if (!resolvedSrc) {
- return <span className="my-2 block text-sm text-muted-foreground">Loading {name}...</span>
- }
-
- // The width cap belongs on the container, not the <img>: a percentage
- // max-width resolves to none while the container measures its fit-content
- // width, so the box overshoots the rendered image and strands the download
- // button — which anchors to the container — out in the margin.
return (
- <ZoomableImage
- alt={alt}
- className={cn(
- 'm-0 block h-auto w-auto max-h-(--image-preview-height) max-w-full rounded-lg object-contain shadow-[0_0.0625rem_0.125rem_color-mix(in_srgb,#000_4%,transparent),0_0.625rem_1.5rem_color-mix(in_srgb,#000_5%,transparent)]',
- className
+ <span className="relative my-2 block max-w-full" data-slot="aui_markdown-image" style={image.frameStyle}>
+ {image.failed ? (
+ <span className="absolute inset-0 block overflow-auto text-sm text-muted-foreground">
+ Couldn&apos;t load {name}.{' '}
+ <button className="ref font-medium text-foreground" onClick={open} type="button">
+ Open image
+ </button>
+ {openFailed && <OpenMediaFailedNote name={name} />}
+ </span>
+ ) : image.src ? (
+ <ZoomableImage
+ {...props}
+ alt={alt}
+ className={cn(
+ 'm-0 block size-full rounded-lg object-contain shadow-[0_0.0625rem_0.125rem_color-mix(in_srgb,#000_4%,transparent),0_0.625rem_1.5rem_color-mix(in_srgb,#000_5%,transparent)]',
+ className
+ )}
+ containerClassName="absolute inset-0 block size-full"
+ onError={event => {
+ image.onError()
+ onError?.(event)
+ }}
+ onLoad={event => {
+ image.onLoad(event.currentTarget)
+ onLoad?.(event)
+ }}
+ src={image.src}
+ style={style}
+ />
+ ) : (
+ <span className="absolute inset-0 block overflow-hidden text-sm text-muted-foreground">Loading {name}...</span>
)}
- containerClassName="my-2 block w-fit max-w-[min(100%,var(--image-preview-max-width))]"
- slot="aui_markdown-image"
- src={resolvedSrc}
- {...props}
- />
+ </span>
)
}
diff --git a/apps/desktop/src/components/chat/generated-image-result.tsx b/apps/desktop/src/components/chat/generated-image-result.tsx
index 89d35e5470a..f03ac7878d7 100644
--- a/apps/desktop/src/components/chat/generated-image-result.tsx
+++ b/apps/desktop/src/components/chat/generated-image-result.tsx
@@ -1,17 +1,17 @@
'use client'
-import { type FC, useEffect, useState } from 'react'
+import { type FC, useState } from 'react'
import { DiffusionCanvas } from '@/components/chat/image-generation-placeholder'
import { ImageActionButton, ImageLightbox } from '@/components/chat/zoomable-image'
import { useImageDownload } from '@/hooks/use-image-download'
+import { useMediaImage } from '@/hooks/use-media-image'
import { useI18n } from '@/i18n'
-import { generatedImageFromResult } from '@/lib/generated-images'
-import { filePathFromMediaPath, gatewayMediaDataUrl, isRemoteGateway, mediaExternalUrl, mediaName } from '@/lib/media'
+import { generatedImageDimensionsFromResult, generatedImageFromResult } from '@/lib/generated-images'
+import { mediaExternalUrl, mediaName } from '@/lib/media'
import { cn } from '@/lib/utils'
-// Aspect hint from the tool args sizes the frame *before* the image loads, so
-// the placeholder and the resolved image occupy the same box — no layout shift.
+// A hint is only a placeholder shape, not a promise about the delivered image.
const ASPECT_HINTS: Record<string, number> = {
landscape: 16 / 9,
square: 1,
@@ -28,115 +28,60 @@ function hintedRatio(aspectRatio?: string): number {
)
}
-function isInlineSrc(path: string): boolean {
- return /^(?:https?|data):/i.test(path)
-}
-
-async function resolveImageSrc(path: string): Promise<string> {
- if (isInlineSrc(path)) {
- return path
- }
-
- if (window.hermesDesktop && isRemoteGateway()) {
- return gatewayMediaDataUrl(path)
- }
-
- if (!window.hermesDesktop?.readFileDataUrl) {
- return mediaExternalUrl(path)
- }
-
- return window.hermesDesktop.readFileDataUrl(filePathFromMediaPath(path))
-}
-
export const GeneratedImage: FC<{ aspectRatio?: string; result?: unknown }> = ({ aspectRatio, result }) => {
const { t } = useI18n()
const copy = t.desktop
const image = result === undefined ? null : generatedImageFromResult(result)
const pending = result === undefined
- const [ratio, setRatio] = useState(() => hintedRatio(aspectRatio))
- const [src, setSrc] = useState(() => (image && isInlineSrc(image) ? image : ''))
- const [loaded, setLoaded] = useState(false)
- const [canvasGone, setCanvasGone] = useState(false)
- const [failed, setFailed] = useState(false)
- const [lightboxOpen, setLightboxOpen] = useState(false)
+ const media = useMediaImage(image ?? '', hintedRatio(aspectRatio), generatedImageDimensionsFromResult(result))
+ const { src, loaded, failed } = media
+ const [canvasGone, setCanvasGone] = useState<string | null>(null)
+ const [lightboxOpen, setLightboxOpen] = useState<string | null>(null)
const { download, saving } = useImageDownload(src)
- useEffect(() => setRatio(hintedRatio(aspectRatio)), [aspectRatio])
-
- // Resolve the deliverable path (local read / gateway proxy / remote URL). The
- // <img> stays mounted under the placeholder and only fades in once it decodes,
- // so the frame keeps its hinted size and never jumps.
- useEffect(() => {
- let cancelled = false
- setFailed(false)
- setLoaded(false)
- setCanvasGone(false)
- setSrc(image && isInlineSrc(image) ? image : '')
-
- if (!image || isInlineSrc(image)) {
- return
- }
-
- void resolveImageSrc(image)
- .then(resolved => !cancelled && setSrc(resolved))
- .catch(() => !cancelled && setFailed(true))
-
- return () => {
- cancelled = true
- }
- }, [image])
-
// Completed but no usable image (generation failed): the agent's prose carries
// the explanation, so render nothing here.
if (!pending && !image) {
return null
}
- if (failed && image) {
- return (
- <a
- className="mt-2 ref inline-block wrap-anywhere"
- href="#"
- onClick={event => {
- event.preventDefault()
- void window.hermesDesktop?.openExternal(mediaExternalUrl(image))
- }}
- >
- {copy.openImage}: {mediaName(image)}
- </a>
- )
- }
-
return (
<>
<span
aria-label={pending ? t.assistant.tool.renderingImage : undefined}
aria-live={pending ? 'polite' : undefined}
- className="group/image relative block max-w-full overflow-hidden rounded-2xl transition-[width,height] duration-300 ease-out"
+ className="group/image relative block max-w-full overflow-hidden rounded-2xl"
data-slot="aui_generated-image"
role={pending ? 'status' : undefined}
- style={{
- aspectRatio: ratio,
- // Width is capped so the derived height (width / ratio) never exceeds
- // --image-preview-height; the box then matches the image exactly with
- // no letterboxing.
- width: `min(calc(var(--image-preview-height) * ${ratio}), var(--image-preview-max-width), 100%)`
- }}
+ style={media.frameStyle}
>
- {!canvasGone && (
- <div
- className={cn('absolute inset-0 transition-opacity duration-500 ease-out', loaded && 'opacity-0')}
- onTransitionEnd={() => loaded && setCanvasGone(true)}
+ {failed && image ? (
+ <a
+ className="absolute inset-0 ref block overflow-auto wrap-anywhere"
+ href="#"
+ onClick={event => {
+ event.preventDefault()
+ void window.hermesDesktop?.openExternal(mediaExternalUrl(image))
+ }}
>
- <DiffusionCanvas />
- </div>
+ {copy.openImage}: {mediaName(image)}
+ </a>
+ ) : (
+ canvasGone !== media.key && (
+ <div
+ className={cn('absolute inset-0 transition-opacity duration-500 ease-out', loaded && 'opacity-0')}
+ onTransitionEnd={() => loaded && setCanvasGone(media.key)}
+ >
+ <DiffusionCanvas />
+ </div>
+ )
)}
- {src && (
+ {src && !failed && (
<button
aria-label={copy.openImage}
className="absolute inset-0 block size-full cursor-zoom-in"
- onClick={() => setLightboxOpen(true)}
+ onClick={() => setLightboxOpen(media.key)}
type="button"
>
<img
@@ -146,16 +91,8 @@ export const GeneratedImage: FC<{ aspectRatio?: string; result?: unknown }> = ({
loaded && 'opacity-100'
)}
draggable={false}
- onError={() => setFailed(true)}
- onLoad={event => {
- const { naturalHeight, naturalWidth } = event.currentTarget
-
- if (naturalWidth && naturalHeight) {
- setRatio(naturalWidth / naturalHeight)
- }
-
- setLoaded(true)
- }}
+ onError={media.onError}
+ onLoad={event => media.onLoad(event.currentTarget)}
src={src}
/>
</button>
@@ -169,8 +106,8 @@ export const GeneratedImage: FC<{ aspectRatio?: string; result?: unknown }> = ({
alt="Generated image"
copy={copy}
onClick={download}
- onOpenChange={setLightboxOpen}
- open={lightboxOpen}
+ onOpenChange={open => setLightboxOpen(open ? media.key : null)}
+ open={lightboxOpen === media.key}
saving={saving}
src={src}
/>
diff --git a/apps/desktop/src/components/chat/image-geometry.test.tsx b/apps/desktop/src/components/chat/image-geometry.test.tsx
new file mode 100644
index 00000000000..d2dfdc6aad4
--- /dev/null
+++ b/apps/desktop/src/components/chat/image-geometry.test.tsx
@@ -0,0 +1,142 @@
+import { act, cleanup, fireEvent, render } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import { ComposerScopeProvider, MAIN_COMPOSER_SCOPE } from '@/app/chat/composer/scope'
+import { MarkdownImage, MessageTextContent } from '@/components/assistant-ui/markdown-text'
+import { $connection } from '@/store/session'
+
+import { GeneratedImage } from './generated-image-result'
+
+vi.mock('./image-generation-placeholder', () => ({ DiffusionCanvas: () => null }))
+
+const paths = { first: '/geometry/first.svg', second: '/geometry/second.svg' }
+const data = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="800" height="800"/>'
+let reads: Array<{ resolve: (value: string) => void; reject: (error: Error) => void }>
+const read = vi.fn(() => new Promise<string>((resolve, reject) => reads.push({ resolve, reject })))
+
+beforeEach(() => {
+ reads = []
+ read.mockClear()
+ vi.stubGlobal('hermesDesktop', { readFileDataUrl: read, api: vi.fn(() => read().then(dataUrl => ({ dataUrl }))) })
+ $connection.set({ connectionId: 'geometry-local', mode: 'local', profile: 'a' } as never)
+})
+afterEach(() => {
+ cleanup()
+ $connection.set(null)
+ vi.unstubAllGlobals()
+})
+
+const cases = [
+ { kind: 'markdown', hint: undefined },
+ { kind: 'media', hint: undefined },
+ ...[undefined, 'landscape', 'square'].map(hint => ({ kind: 'generated', hint })),
+ { kind: 'markdown', hint: 'intrinsic' },
+ { kind: 'generated', hint: 'intrinsic' }
+]
+
+function content(kind: string, path: string, hint?: string) {
+ if (kind === 'generated') {
+ return (
+ <GeneratedImage
+ aspectRatio={hint}
+ result={{ success: true, image: path, pixel_size: hint === 'intrinsic' ? '800x800' : undefined }}
+ />
+ )
+ }
+
+ if (kind === 'media') {
+ return <MessageTextContent text={`MEDIA:${path}`} />
+ }
+
+ return (
+ <MarkdownImage
+ alt="geometry"
+ height={hint === 'intrinsic' ? 800 : undefined}
+ src={path}
+ width={hint === 'intrinsic' ? 800 : undefined}
+ />
+ )
+}
+
+function frame(container: HTMLElement) {
+ return container.querySelector<HTMLElement>('[data-slot="aui_generated-image"], [data-slot="aui_markdown-image"]')!
+}
+
+async function decode(container: HTMLElement, width = 800, height = 800) {
+ await act(async () => reads.shift()!.resolve(data))
+ const img = container.querySelector('img')!
+ Object.defineProperties(img, { naturalWidth: { value: width }, naturalHeight: { value: height } })
+ fireEvent.load(img)
+}
+
+it.each(cases)('reserves $kind frames through cold decode, warm return and failure ($hint)', async ({ kind, hint }) => {
+ // Unique paths keep parameter rows independent without a production cache-reset API.
+ const path = `${paths.first}?${kind}-${hint}`
+ const first = render(content(kind, path, hint))
+ const cold = frame(first.container)
+ expect(cold).not.toBeNull()
+ const coldSize = cold.style.cssText
+
+ if (hint === 'intrinsic') {
+ expect(parseFloat(cold.style.aspectRatio)).toBe(1)
+ }
+
+ await decode(first.container)
+ expect(frame(first.container).style.cssText).toBe(coldSize)
+ first.unmount()
+
+ const warm = render(content(kind, path, hint))
+ const reserved = frame(warm.container)
+ expect(parseFloat(reserved.style.aspectRatio)).toBe(1)
+ const warmSize = reserved.style.cssText
+ await decode(warm.container)
+ expect(frame(warm.container).style.cssText).toBe(warmSize)
+ fireEvent.error(warm.container.querySelector('img')!)
+ expect(frame(warm.container).style.cssText).toBe(warmSize)
+ expect(warm.container.textContent).toMatch(/Open image/i)
+})
+
+it.each(['markdown', 'generated'])('%s dimensions follow owner and source, not stale reads or hints', async kind => {
+ const path = `${paths.second}?${kind}`
+
+ const view = (connectionId: string, profile: string, src = path) => (
+ <ComposerScopeProvider value={{ ...MAIN_COMPOSER_SCOPE, connectionId, profile }}>
+ {content(kind, src, 'portrait')}
+ </ComposerScopeProvider>
+ )
+
+ const first = render(view('owner-a', 'a'))
+ await decode(first.container, 900, 600)
+ first.unmount()
+
+ const mounted = render(view('owner-b', 'a'))
+ expect(parseFloat(frame(mounted.container).style.aspectRatio)).not.toBe(1.5)
+ mounted.rerender(view('owner-a', 'b'))
+ expect(parseFloat(frame(mounted.container).style.aspectRatio)).not.toBe(1.5)
+ mounted.rerender(view('owner-a', 'a'))
+ expect(parseFloat(frame(mounted.container).style.aspectRatio)).toBe(1.5)
+ const reserved = frame(mounted.container).style.cssText
+ // Settle the two superseded owners after A has become visible again.
+ await act(async () => {
+ reads.shift()!.resolve(data)
+ reads.shift()!.reject(new Error('retired'))
+ })
+ expect(frame(mounted.container).style.cssText).toBe(reserved)
+ expect(mounted.container.querySelector('img')).toBeNull()
+ // Same path, changed bytes: update the next mount's intrinsic dimensions,
+ // but never reshape the frame currently being read.
+ await decode(mounted.container, 600, 900)
+ expect(frame(mounted.container).style.cssText).toBe(reserved)
+ mounted.rerender(view('owner-a', 'a', `${path}-revision`))
+ expect(parseFloat(frame(mounted.container).style.aspectRatio)).not.toBe(1.5)
+ expect(mounted.container.querySelector('img')).toBeNull()
+ await act(async () => reads.shift()!.reject(new Error('missing')))
+ expect(mounted.container.textContent).toMatch(/Open image/i)
+ mounted.rerender(view('owner-a', 'a'))
+ expect(parseFloat(frame(mounted.container).style.aspectRatio)).toBeCloseTo(600 / 900)
+ expect(window.hermesDesktop.api).toHaveBeenLastCalledWith({
+ connectionId: 'owner-a',
+ profile: 'a',
+ path: `/api/fs/read-data-url?path=${encodeURIComponent(path)}`
+ })
+})
diff --git a/apps/desktop/src/hooks/use-media-image.ts b/apps/desktop/src/hooks/use-media-image.ts
new file mode 100644
index 00000000000..feefe79af93
--- /dev/null
+++ b/apps/desktop/src/hooks/use-media-image.ts
@@ -0,0 +1,95 @@
+import { useStore } from '@nanostores/react'
+import { type CSSProperties, useEffect, useMemo, useState } from 'react'
+
+import { useComposerScope } from '@/app/chat/composer/scope'
+import {
+ forgetMediaImageDimensions,
+ getMediaImageDimensions,
+ isInlineMediaSrc,
+ type MediaImageDimensions,
+ mediaImageKey,
+ rememberMediaImageDimensions,
+ resolveMediaDisplaySrc
+} from '@/lib/media'
+import { $connection } from '@/store/session'
+
+/** Keep a frame for one source/owner for its mounted lifetime. Hints are not
+ * intrinsic dimensions: a cold image is contained in that frame, not allowed
+ * to resize it at decode. The next mount can use the measured dimensions. */
+export function useMediaImage(path: string, fallbackRatio: number, intrinsic?: MediaImageDimensions) {
+ const connection = useStore($connection)
+ const scope = useComposerScope()
+ const connectionId = scope.connectionId || connection?.connectionId
+ const profile = scope.profile ?? connection?.profile
+
+ const owner = useMemo(
+ () => (scope.connectionId || scope.profile ? { connectionId, profile } : undefined),
+ [scope.connectionId, scope.profile, connectionId, profile]
+ )
+
+ const key = mediaImageKey(path, connection, owner)
+
+ const initialState = () => {
+ const dimensions = intrinsic ?? getMediaImageDimensions(key)
+ const ratio = dimensions ? dimensions.width / dimensions.height : fallbackRatio
+
+ return {
+ key,
+ frameStyle: {
+ aspectRatio: ratio,
+ width: `min(calc(var(--image-preview-height) * ${ratio}), var(--image-preview-max-width), 100%${dimensions ? `, ${dimensions.width}px` : ''})`
+ } satisfies CSSProperties,
+ src: path && isInlineMediaSrc(path) ? path : '',
+ loaded: false,
+ failed: false
+ }
+ }
+
+ const [state, setState] = useState(initialState)
+
+ // Source changes must not paint the previous image/geometry even for one
+ // commit. React retries this component before committing its children.
+ if (state.key !== key) {
+ setState(initialState())
+ }
+
+ useEffect(() => {
+ let cancelled = false
+
+ if (path && !isInlineMediaSrc(path)) {
+ void resolveMediaDisplaySrc(path, owner).then(
+ src => {
+ if (!cancelled) {
+ if (!src) {
+ forgetMediaImageDimensions(key)
+ }
+
+ setState(current => ({ ...current, src, failed: !src }))
+ }
+ },
+ () => {
+ if (!cancelled) {
+ forgetMediaImageDimensions(key)
+ setState(current => ({ ...current, failed: true }))
+ }
+ }
+ )
+ }
+
+ return () => {
+ cancelled = true
+ }
+ }, [key, path, owner])
+
+ return {
+ ...state,
+ onLoad: (image: HTMLImageElement) => {
+ rememberMediaImageDimensions(key, image.naturalWidth, image.naturalHeight)
+ setState(current => ({ ...current, loaded: true }))
+ },
+ onError: () => {
+ forgetMediaImageDimensions(key)
+ setState(current => ({ ...current, failed: true, loaded: false }))
+ }
+ }
+}
diff --git a/apps/desktop/src/lib/generated-images.test.ts b/apps/desktop/src/lib/generated-images.test.ts
index 7fb32105104..7eb1e85cbf5 100644
--- a/apps/desktop/src/lib/generated-images.test.ts
+++ b/apps/desktop/src/lib/generated-images.test.ts
@@ -2,12 +2,30 @@ import { describe, expect, it } from 'vitest'
import {
dedupeGeneratedImageEchoesInParts,
+ generatedImageDimensionsFromResult,
generatedImageEchoSources,
generatedImageFromResult,
stripGeneratedImageEchoes
} from './generated-images'
describe('generatedImageFromResult', () => {
+ it('uses decoded pixel_size, never requested sizing, for intrinsic geometry', () => {
+ const dimensions = { width: 900, height: 600 }
+
+ const result = {
+ success: true,
+ image: '/image.png',
+ pixel_size: `${dimensions.width}x${dimensions.height}`,
+ size: '1024x1024'
+ }
+
+ expect(generatedImageDimensionsFromResult(JSON.stringify(result))).toEqual(dimensions)
+
+ for (const pixel_size of [undefined, 'auto', '0x600', '9'.repeat(400) + 'x600']) {
+ expect(generatedImageDimensionsFromResult({ ...result, pixel_size })).toBeUndefined()
+ }
+ })
+
it('prefers the host-visible image path', () => {
expect(
generatedImageFromResult({
diff --git a/apps/desktop/src/lib/generated-images.ts b/apps/desktop/src/lib/generated-images.ts
index 4ee990bd6d9..233e44ce836 100644
--- a/apps/desktop/src/lib/generated-images.ts
+++ b/apps/desktop/src/lib/generated-images.ts
@@ -1,3 +1,5 @@
+import type { MediaImageDimensions } from '@/lib/media'
+
type ToolLike = {
result?: unknown
toolName?: unknown
@@ -66,6 +68,21 @@ export function generatedImageFromResult(result: unknown): string | null {
return stringFields(record, DISPLAY_KEYS)[0] ?? null
}
+/** Codex reports decoded PNG geometry separately from its requested `size`.
+ * Never use requested_size/size or aspect_ratio as intrinsic metadata. */
+export function generatedImageDimensionsFromResult(result: unknown): MediaImageDimensions | undefined {
+ const record = recordFromUnknown(result)
+ const match = typeof record?.pixel_size === 'string' ? /^(\d+)x(\d+)$/.exec(record.pixel_size) : null
+
+ return match &&
+ Number.isSafeInteger(Number(match[1])) &&
+ Number.isSafeInteger(Number(match[2])) &&
+ Number(match[1]) > 0 &&
+ Number(match[2]) > 0
+ ? { width: Number(match[1]), height: Number(match[2]) }
+ : undefined
+}
+
/** Every path/URL a generated image might appear as in prose, for de-duping. */
export function generatedImageEchoSources(parts: readonly ToolLike[]): string[] {
// Runs on every streamed tool event over the whole timeline; skip the
diff --git a/apps/desktop/src/lib/media-dimensions.test.ts b/apps/desktop/src/lib/media-dimensions.test.ts
new file mode 100644
index 00000000000..bc0c4c9a997
--- /dev/null
+++ b/apps/desktop/src/lib/media-dimensions.test.ts
@@ -0,0 +1,45 @@
+import { expect, it } from 'vitest'
+
+import type { HermesConnection } from '@/global'
+
+import {
+ forgetMediaImageDimensions,
+ getMediaImageDimensions,
+ mediaImageKey,
+ rememberMediaImageDimensions,
+ validImageDimensions
+} from './media'
+
+it('shares proven path aliases only within an owner and bounds regenerated metadata by LRU', () => {
+ const a = { connectionId: 'a', profile: 'work', mode: 'remote' } as HermesConnection
+ const b = { ...a, connectionId: 'b' }
+ const key = mediaImageKey('/images/a b.png', a)
+ const dimensions = { width: 900, height: 600 }
+
+ rememberMediaImageDimensions(key, dimensions.width, dimensions.height)
+ expect(getMediaImageDimensions(mediaImageKey('file:///images/a%20b.png', a))).toEqual(dimensions)
+ expect(getMediaImageDimensions(mediaImageKey('/images/a b.png', b))).toBeUndefined()
+ expect(getMediaImageDimensions(mediaImageKey('/images/a b.png', { ...a, profile: 'personal' }))).toBeUndefined()
+ expect(getMediaImageDimensions(mediaImageKey('/images/a b.png?revision=2', a))).toBeUndefined()
+ expect(getMediaImageDimensions(mediaImageKey('file:///images/a%20b.png?revision=2', a))).toBeUndefined()
+ expect(getMediaImageDimensions(mediaImageKey('/images/a b.png', b, a))).toEqual(dimensions)
+
+ // Discover the finite capacity behaviorally, not by pinning its current value.
+ const cold = mediaImageKey('/images/old.png', a)
+ rememberMediaImageDimensions(cold, 100, 100)
+
+ for (let i = 0; i < 10000; i++) {
+ rememberMediaImageDimensions(`bounded-${i}`, 100, 100)
+ expect(getMediaImageDimensions(key)).toEqual(dimensions)
+ }
+
+ expect(getMediaImageDimensions(cold)).toBeUndefined()
+ expect(validImageDimensions(0, 100)).toBeUndefined()
+ expect(validImageDimensions(Infinity, 100)).toBeUndefined()
+ rememberMediaImageDimensions(key, 0, 100)
+ expect(getMediaImageDimensions(key)).toEqual(dimensions)
+ rememberMediaImageDimensions('x'.repeat(100000), 100, 100)
+ expect(getMediaImageDimensions('x'.repeat(100000))).toBeUndefined()
+ forgetMediaImageDimensions(key)
+ expect(getMediaImageDimensions(key)).toBeUndefined()
+})
diff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.ts
index 7847bc0e28e..830603e53ab 100644
--- a/apps/desktop/src/lib/media.ts
+++ b/apps/desktop/src/lib/media.ts
@@ -1,4 +1,7 @@
-import { readDesktopFileDataUrl } from '@/lib/desktop-fs'
+import { hermesApi, type OwnerScope } from '@/api/client'
+import type { HermesConnection } from '@/global'
+import { desktopFsCacheKey, readDesktopFileDataUrl } from '@/lib/desktop-fs'
+import { LruCache } from '@/lib/lru-cache'
import { capitalize } from '@/lib/text'
import { $connection } from '@/store/session'
@@ -84,11 +87,23 @@ export function isFileMediaPath(path: string): boolean {
return /^(?:file:|\/|~\/|[a-z]:[\\/]|\\\\)/i.test(path)
}
-export async function resolveMediaDisplaySrc(path: string): Promise<string> {
+export async function resolveMediaDisplaySrc(path: string, owner?: OwnerScope): Promise<string> {
if (isInlineMediaSrc(path) || !isFileMediaPath(path)) {
return path
}
+ // A tile can belong to a different gateway than the foreground. Pin both
+ // halves at read admission rather than resolving them when the read settles.
+ if (window.hermesDesktop && (owner?.connectionId || owner?.profile)) {
+ const result = await hermesApi<string | { dataUrl?: string }>({
+ path: `/api/fs/read-data-url?path=${encodeURIComponent(filePathFromMediaPath(path))}`,
+ ...(owner.connectionId ? { connectionId: owner.connectionId } : {}),
+ ...(owner.profile ? { profile: owner.profile } : {})
+ })
+
+ return typeof result === 'string' ? result : result.dataUrl || ''
+ }
+
if (window.hermesDesktop && isRemoteGateway()) {
return gatewayMediaDataUrl(path)
}
@@ -100,6 +115,55 @@ export async function resolveMediaDisplaySrc(path: string): Promise<string> {
return window.hermesDesktop.readFileDataUrl(filePathFromMediaPath(path))
}
+export interface MediaImageDimensions {
+ width: number
+ height: number
+}
+
+// Decoded geometry only: never retain image bytes/data URLs for every visited
+// transcript. A miss costs a letterboxed first display, not a collapsed row.
+const imageDimensions = new LruCache<string, MediaImageDimensions>(512)
+
+export function mediaImageKey(path: string, connection: HermesConnection | null, owner?: OwnerScope): string {
+ // File reads ignore URL query/fragment, but callers can use them to identify
+ // a new revision. Keep them in the geometry key while joining proven aliases.
+ const revision = /^file:/i.test(path) ? (path.match(/[?#].*$/)?.[0] ?? '') : ''
+
+ return JSON.stringify([
+ owner?.connectionId ||
+ connection?.connectionId ||
+ desktopFsCacheKey(connection && { ...connection, profile: owner?.profile ?? connection.profile }),
+ owner?.profile ?? connection?.profile ?? '',
+ filePathFromMediaPath(path),
+ revision
+ ])
+}
+
+export function validImageDimensions(width: unknown, height: unknown): MediaImageDimensions | undefined {
+ const w = Number(width)
+ const h = Number(height)
+
+ return Number.isFinite(w) && w > 0 && Number.isFinite(h) && h > 0 ? { width: w, height: h } : undefined
+}
+
+export function getMediaImageDimensions(key: string): MediaImageDimensions | undefined {
+ return imageDimensions.get(key)
+}
+
+export function rememberMediaImageDimensions(key: string, width: number, height: number): void {
+ const dimensions = validImageDimensions(width, height)
+
+ // Embedded images can have multi-megabyte source keys. Their bytes stay with
+ // the message; do not turn this small metadata cache into a second copy.
+ if (dimensions && key.length <= 4096) {
+ imageDimensions.set(key, dimensions)
+ }
+}
+
+export function forgetMediaImageDimensions(key: string): void {
+ imageDimensions.delete(key)
+}
+
// Audio/video need a seekable source instead of a whole-file data URL. Keep
// remote URLs untouched and route filesystem paths through the Electron media
// protocol. Its main-process handler reads local files directly or proxies a