fix(desktop): inline preview frames size to their content instead of a fixed default

The frame was a hardcoded 280px unless the model guessed a height attribute
— tall pages clipped (the flip-clock demo cut its last digit), short ones
floated in dead space. The opaque-origin sandbox means the parent can't
measure the document, but we own the srcdoc string: a tiny injected script
observes the document with ResizeObserver and posts its scrollHeight up via
postMessage, and the frame tracks it live within the 120-1200 clamp.

Reports are validated before they can move layout — per-mount random token
(two previews in one transcript, or a hostile page inventing messages,
can't move each other's frames), finite-number check, clamp. A 4px
tolerance stops vh-sized pages (which measure exactly what they're given)
from oscillating; an explicit height attribute still opts out of
auto-sizing entirely.
This commit is contained in:
Brooklyn Nicholson
2026-08-17 12:34:22 -05:00
committed by brooklyn!
parent 8425f8286b
commit 5c4f1e744c
2 changed files with 164 additions and 16 deletions
@@ -1,18 +1,62 @@
import { describe, expect, it } from 'vitest'
import { directiveFrameHeight } from './inline-preview-directive'
import { directiveFrameHeight, frameHeightFromMessage, withMeasurement } from './inline-preview-directive'
describe('directiveFrameHeight', () => {
it('defaults when absent or garbage', () => {
expect(directiveFrameHeight(undefined)).toBe(280)
expect(directiveFrameHeight('')).toBe(280)
expect(directiveFrameHeight('tall')).toBe(280)
expect(directiveFrameHeight('12.5')).toBe(280)
it('returns null (auto-size) when absent or garbage', () => {
expect(directiveFrameHeight(undefined)).toBeNull()
expect(directiveFrameHeight('')).toBeNull()
expect(directiveFrameHeight('tall')).toBeNull()
expect(directiveFrameHeight('12.5')).toBeNull()
})
it('clamps to the sane band', () => {
it('clamps an explicit height to the sane band', () => {
expect(directiveFrameHeight('50')).toBe(120)
expect(directiveFrameHeight('480')).toBe(480)
expect(directiveFrameHeight('99999')).toBe(1200)
})
})
describe('withMeasurement', () => {
it('injects the measuring script before </body>', () => {
const doc = '<html><body><h1>hi</h1></body></html>'
const framed = withMeasurement(doc, 'tok')
expect(framed.indexOf('<script>')).toBeGreaterThan(framed.indexOf('<h1>'))
expect(framed.indexOf('</script>')).toBeLessThan(framed.indexOf('</body>'))
expect(framed).toContain('"tok"')
})
it('appends when there is no body close tag', () => {
const framed = withMeasurement('<h1>fragment</h1>', 'tok')
expect(framed.startsWith('<h1>fragment</h1>')).toBe(true)
expect(framed).toContain('postMessage')
})
})
describe('frameHeightFromMessage', () => {
const msg = (over: Record<string, unknown> = {}) => ({
type: 'hermes-inline-preview-size',
token: 'tok',
height: 500,
...over
})
it('accepts our message with our token, clamped', () => {
expect(frameHeightFromMessage(msg(), 'tok')).toBe(500)
expect(frameHeightFromMessage(msg({ height: 12 }), 'tok')).toBe(120)
expect(frameHeightFromMessage(msg({ height: 5000 }), 'tok')).toBe(1200)
expect(frameHeightFromMessage(msg({ height: 500.7 }), 'tok')).toBe(501)
})
it('rejects wrong type, wrong token, and hostile shapes', () => {
expect(frameHeightFromMessage(msg({ type: 'other' }), 'tok')).toBeNull()
expect(frameHeightFromMessage(msg({ token: 'stolen' }), 'tok')).toBeNull()
expect(frameHeightFromMessage(msg({ height: 'tall' }), 'tok')).toBeNull()
expect(frameHeightFromMessage(msg({ height: Infinity }), 'tok')).toBeNull()
expect(frameHeightFromMessage(msg({ height: -5 }), 'tok')).toBeNull()
expect(frameHeightFromMessage(null, 'tok')).toBeNull()
expect(frameHeightFromMessage('str', 'tok')).toBeNull()
})
})
@@ -1,5 +1,5 @@
import { useStore } from '@nanostores/react'
import { useEffect, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useSessionView } from '@/app/chat/session-view'
import { PreviewAttachment } from '@/components/chat/preview-attachment'
@@ -19,6 +19,14 @@ import { localPreviewTarget } from '@/lib/local-preview'
* assets don't resolve in an opaque origin — the header's rail affordance
* covers multi-file apps with the full webview preview.
*
* HEIGHT IS CONTENT-DRIVEN. The opaque origin means the parent can't measure
* the document, but we own the srcdoc string — so a measuring script is
* injected that posts the document's scrollHeight up via postMessage (tagged
* with a per-mount token) on load and on every resize, and the frame tracks
* it within the clamp band. Full-viewport pages (100vh) measure exactly the
* height they're given, so they settle at the default instead of looping. An
* explicit `height="480"` attribute opts out of auto-sizing entirely.
*
* Non-HTML targets and remote gateways (no local file access) fall back to
* the standard preview-attachment card rather than a broken frame.
*/
@@ -26,21 +34,78 @@ import { localPreviewTarget } from '@/lib/local-preview'
const MIN_HEIGHT = 120
const MAX_HEIGHT = 1200
const DEFAULT_HEIGHT = 280
/** Ignore sub-pixel/rounding churn so a vh-sized page can't oscillate. */
const RESIZE_TOLERANCE = 4
export function directiveFrameHeight(raw: string | undefined): number {
export function directiveFrameHeight(raw: string | undefined): number | null {
if (!raw) {
return DEFAULT_HEIGHT
return null
}
const parsed = Number(raw)
if (!Number.isInteger(parsed)) {
return DEFAULT_HEIGHT
return null
}
return Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, parsed))
}
const SIZE_MESSAGE_TYPE = 'hermes-inline-preview-size'
/** The script injected into the srcdoc that reports content height to the
* parent. Runs inside the opaque origin, so postMessage is its only door —
* it can say "I am N pixels tall" and nothing else. */
export function measurementScript(token: string): string {
return (
'<script>(function(){var t=' +
JSON.stringify(token) +
';var last=0;function post(){var d=document.documentElement;var b=document.body;' +
'var h=Math.max(d?d.scrollHeight:0,b?b.scrollHeight:0);' +
'if(Math.abs(h-last)>1){last=h;parent.postMessage({type:' +
JSON.stringify(SIZE_MESSAGE_TYPE) +
',token:t,height:h},"*")}}' +
'if(typeof ResizeObserver==="function"){var ro=new ResizeObserver(post);' +
'ro.observe(document.documentElement);if(document.body)ro.observe(document.body)}' +
'addEventListener("load",post);post()})()</script>'
)
}
/** Inject the measuring script into a document string — before `</body>`
* when present so it runs after the page's own markup, appended otherwise. */
export function withMeasurement(doc: string, token: string): string {
const script = measurementScript(token)
const bodyClose = /<\/body\s*>/i.exec(doc)
if (bodyClose) {
return doc.slice(0, bodyClose.index) + script + doc.slice(bodyClose.index)
}
return doc + script
}
/** Parse a size report from the frame. Null unless it is OUR message type,
* carries OUR token, and holds a sane finite height — anything inside the
* sandbox can postMessage, so everything is validated before it moves the
* layout. Clamped to the band. */
export function frameHeightFromMessage(data: unknown, token: string): number | null {
if (typeof data !== 'object' || data === null) {
return null
}
const message = data as { type?: unknown; token?: unknown; height?: unknown }
if (message.type !== SIZE_MESSAGE_TYPE || message.token !== token || typeof message.height !== 'number') {
return null
}
if (!Number.isFinite(message.height) || message.height <= 0) {
return null
}
return Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.round(message.height)))
}
const HTML_FILE_RE = /\.(?:html?|xhtml)$/i
export function InlinePreviewDirective({
@@ -58,15 +123,31 @@ export function InlinePreviewDirective({
return file ? <PreviewAttachment source="explicit-link" target={file} /> : null
}
return <InlineHtmlFrame file={file} height={directiveFrameHeight(attrs.height)} streaming={streaming} />
return <InlineHtmlFrame file={file} fixedHeight={directiveFrameHeight(attrs.height)} streaming={streaming} />
}
function InlineHtmlFrame({ file, height, streaming }: { file: string; height: number; streaming: boolean }) {
function InlineHtmlFrame({
file,
fixedHeight,
streaming
}: {
file: string
/** Explicit `height` attribute — opts out of content-driven sizing. */
fixedHeight: number | null
streaming: boolean
}) {
const { t } = useI18n()
const cwd = useStore(useSessionView().$cwd)
const isDark = useIsDark()
const [doc, setDoc] = useState<string | null>(null)
const [failed, setFailed] = useState(false)
const [measured, setMeasured] = useState<number | null>(null)
const heightRef = useRef<number>(fixedHeight ?? DEFAULT_HEIGHT)
// One token per mount: the message listener only trusts reports from the
// document THIS mount injected, so two previews in one transcript (or a
// hostile page inventing messages) can't move each other's frames.
const token = useMemo(() => Math.random().toString(36).slice(2), [])
// Resolve against THIS session's cwd (the file was written by its agent).
const resolved = localPreviewTarget(file, cwd || undefined)
@@ -100,13 +181,36 @@ function InlineHtmlFrame({ file, height, streaming }: { file: string; height: nu
}
}, [path, streaming])
useEffect(() => {
if (fixedHeight !== null) {
return
}
const onMessage = (event: MessageEvent) => {
const next = frameHeightFromMessage(event.data, token)
if (next !== null && Math.abs(next - heightRef.current) > RESIZE_TOLERANCE) {
heightRef.current = next
setMeasured(next)
}
}
window.addEventListener('message', onMessage)
return () => window.removeEventListener('message', onMessage)
}, [fixedHeight, token])
const framedDoc = useMemo(() => (doc === null ? null : withMeasurement(doc, token)), [doc, token])
if (!path || failed) {
return <PreviewAttachment source="explicit-link" target={file} />
}
const height = fixedHeight ?? measured ?? DEFAULT_HEIGHT
return (
<span className="my-2 grid w-full max-w-160 gap-2">
{doc === null ? (
{framedDoc === null ? (
<span
className="grid w-full animate-pulse place-items-center rounded-lg border border-(--ui-stroke-tertiary) text-[0.75rem] text-muted-foreground"
style={{ height }}
@@ -115,14 +219,14 @@ function InlineHtmlFrame({ file, height, streaming }: { file: string; height: nu
</span>
) : (
<span
className="relative block w-full overflow-hidden rounded-lg border border-(--ui-stroke-tertiary)"
className="relative block w-full overflow-hidden rounded-lg border border-(--ui-stroke-tertiary) transition-[height] duration-200"
style={{ height }}
>
<iframe
className="absolute inset-0 size-full border-0 bg-transparent"
loading="lazy"
sandbox="allow-scripts"
srcDoc={doc}
srcDoc={framedDoc}
style={{ colorScheme: isDark ? 'dark' : 'light' }}
title={file}
/>