diff --git a/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts b/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts index 9f65458688..10f2051134 100644 --- a/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts +++ b/apps/desktop/src/components/assistant-ui/inline-preview-directive.test.ts @@ -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 ', () => { + const doc = '

hi

' + const framed = withMeasurement(doc, 'tok') + + expect(framed.indexOf('')).toBeLessThan(framed.indexOf('')) + expect(framed).toContain('"tok"') + }) + + it('appends when there is no body close tag', () => { + const framed = withMeasurement('

fragment

', 'tok') + + expect(framed.startsWith('

fragment

')).toBe(true) + expect(framed).toContain('postMessage') + }) +}) + +describe('frameHeightFromMessage', () => { + const msg = (over: Record = {}) => ({ + 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() + }) +}) diff --git a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx index 804296029c..00f3fc09ac 100644 --- a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx +++ b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx @@ -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 ( + '' + ) +} + +/** Inject the measuring script into a document string — before `` + * 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 ? : null } - return + return } -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(null) const [failed, setFailed] = useState(false) + const [measured, setMeasured] = useState(null) + const heightRef = useRef(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 } + const height = fixedHeight ?? measured ?? DEFAULT_HEIGHT + return ( - {doc === null ? ( + {framedDoc === null ? ( ) : (