A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.
TypeScript
Merge main and reconcile screenshots with preview hot updates
Esteban Suareza0eaec1a25cc
diff --cc app/api/artifact-frame/route.tsindex 3c59664,68a3cd7..da909a2--- a/app/api/artifact-frame/route.ts+++ b/app/api/artifact-frame/route.ts@@@ -1,6 -1,6 +1,7 @@@import { ARTIFACT_IMAGE_PATH, artifactImageSrc } from '../../../lib/artifact-image'- import { DESIGN_ARTIFACT_EMBEDDED_CSP, designFrameCsp, designFrameHtml, prepareDesignArtifactHtml, remoteImagesEnabled } from '../../../lib/design-artifact'+ import { DESIGN_ARTIFACT_EMBEDDED_CSP, designFrameCsp, designFrameHtml, normalizeDesignArtifactHtml, prepareDesignArtifactHtml, remoteImagesEnabled } from '../../../lib/design-artifact'+import { DESIGN_CAPTURE_RELAY, designCaptureScript } from '../../../lib/design-capture'+ import { PREVIEW_PROTOCOL, type PreviewPayload } from '../../../lib/preview-update'import { markRemoteImages } from '../../../lib/remote-image'import { readDesignArtifactAt } from '../../../lib/journal'import { readGeneration } from '../../../lib/history'@@@ -45,7 -57,7 +58,8 @@@ export const GET = withSessionRoute(asyartifact != null ? 'This design could not be prepared for preview.': past ? 'This version is not in the history.' : 'No design artifact has been published for this session.'}</p></body></html>`- const html = designFrameHtml(preparedArtifact, readyToken, images, DESIGN_CAPTURE_RELAY)- const html = designFrameHtml(preparedArtifact, readyToken, images, payload ?? undefined)++ // Every preview is photographed where it is (lib/design-capture.ts): the wrapper gives each child document its own capture runtime.++ const html = designFrameHtml(preparedArtifact, readyToken, images, payload ?? undefined, { relay: DESIGN_CAPTURE_RELAY, script: designCaptureScript })return new Response(html, {status: artifact == null ? 404 : 200,headers: {diff --cc components/chat-app.tsxindex f29e1a6,3e8823a..caee365--- a/components/chat-app.tsx+++ b/components/chat-app.tsx@@@ -2105,11 -2090,9 +2105,12 @@@ export default function ChatApp({ accousource={{ kind: 'design', sessionId: view.sessionId, revision: view.snapshot.transcript.view.artifactRevision }}viewing={viewing}draft={designDraft?.html ?? null}+ accessAllowed={!authBlocked && signOutStatus == null}intro={view.snapshot.transcript.entries.length === 0}onClose={closePreview}+ capture={captureRequest && !captureRequest.offscreen && captureRequest.sessionId === view.sessionId ? captureRequest : null}+ onCaptureDone={(cid, answered) => setCaptureRequest((current) =>+ current?.cid !== cid ? current : answered ? null : { ...current, offscreen: true })}/>))}</>diff --cc components/preview-pane.tsxindex a1fb539,fdee432..a4e270d--- a/components/preview-pane.tsx+++ b/components/preview-pane.tsx@@@ -3,8 -3,8 +3,10 @@@import { useCallback, useEffect, useRef, useState } from 'react'import { designLinkUrl } from '../lib/design-link'import { EMPTY_DRAFT_DOCUMENT, patchDraftDocument } from '../lib/draft-preview'- import { CAPTURE_PAINT_MS, CAPTURE_PREVIEW_START_MS } from '../lib/capture-protocol'++import { CAPTURE_PAINT_MS, CAPTURE_PREVIEW_START_MS, type CaptureFailure } from '../lib/capture-protocol'+import { captureFrame, reportCaptureFailure, sendCapture, type CaptureRequest } from './design-capture'+ import { PREVIEW_PREPARE_MS, PREVIEW_PROTOCOL, type PreviewPayload } from '../lib/preview-update'+ import { AuthRouteError, fetchUi } from './auth-ui'import DesignLinkDialog from './design-link-dialog'import { HowItWorksPanel } from './how-it-works'@@@ -18,10 -57,9 +59,11 @@@ export default function PreviewPane(source,viewing,draft = null,+ accessAllowed = true,intro,onClose,+ capture = null,+ onCaptureDone,}: {source: PreviewSource// A past revision opened from the transcript's "View" link, never the latest; null is the latest.@@@ -31,152 -71,343 +75,425 @@@// Only an empty chat explains fx0; a chat waiting on its first design stays blank.intro: booleanonClose: () => void+ // A screenshot_design request; the preview answers from the frame on screen.+ capture?: CaptureRequest | null+ // Whether this preview answered (a photo or a failure); when not, the hidden copy should.+ onCaptureDone?: (cid: string, answered: boolean) => void}) {- const session = encodeURIComponent(source.sessionId)- const previewUrl = source.revision > 0- ? viewing != null- ? `/api/artifact-frame?session=${session}&revision=${viewing}`- : `/api/artifact-frame?session=${session}&v=${source.revision}`- : null-- // A new revision, or another chat's design, loads in a slot underneath and comes to- // the front once it has loaded, so the screen never shows a frame mid-load. The- // slots never move in the DOM (moving an iframe reloads it); only which one is in- // front changes. The draft stays on top until the front slot shows the latest- // revision.- const [slots, setSlots] = useState<[string | null, string | null]>([previewUrl, null])- const [front, setFront] = useState<number | null>(previewUrl ? 0 : null)- const wanted = useRef(previewUrl)- wanted.current = previewUrl- const slotUrls = useRef(slots)- slotUrls.current = slots- const fallback = useRef<ReturnType<typeof setTimeout> | null>(null)- // Only a slot holding the revision asked for now may come to the front; a late- // paint or fallback from a revision already left behind is ignored.- const bringToFront = (index: number) => {- if (slotUrls.current[index] !== wanted.current) return- if (fallback.current) clearTimeout(fallback.current)- setFront(index)- }- useEffect(() => {- if (!previewUrl) {- setSlots([null, null])- setFront(null)- return- }- // Returning to a design still loaded in a slot (the chat just left, or the latest- // after viewing an older revision) shows it at once; it has already painted.- const loaded = slots.indexOf(previewUrl)- if (loaded >= 0) {- bringToFront(loaded)- return- }- const target = front == null ? 0 : 1 - front- setSlots((current) => (target === 0 ? [previewUrl, current[1]] : [current[0], previewUrl]))- }, [previewUrl]) // eslint-disable-line react-hooks/exhaustive-deps- // A slot comes to the front once its design reports it has painted. The design- // renders in a nested frame in another process, so the slot's own load event- // fires before that and swapping then showed the wrapper's white page. Documents- // that never report (a missing revision) swap a while after loading.+ const scope = JSON.stringify([source.sessionId, viewing, accessAllowed])+ const currentScope = useRef(scope)+ currentScope.current = scopeconst frames = useRef<(HTMLIFrameElement | null)[]>([null, null])- const frontIndex = useRef(front)- frontIndex.current = front- // A link the design on screen asked to open, waiting for the user's own click.- const [linkRequest, setLinkRequest] = useState<string | null>(null)+ const demand = useRef<(revision: number, retry?: boolean) => void>(() => {})+ const retry = useRef(() => {})++ // Capture and hot application share a document: never mutate it mid-photo.++ const capturingScope = useRef<string | null>(null)++ const canCapture = useRef<() => boolean>(() => false)++ const resumeUpdates = useRef(() => {})+ const [display, setDisplay] = useState<PreviewDisplay>(() => {+ const revision = accessAllowed && source.revision > 0 ? (viewing ?? source.revision) : 0+ const slot: PreviewSlot | null = revision > 0 ? {+ mountUrl: `/api/artifact-frame?session=${encodeURIComponent(source.sessionId)}&${viewing == null ? 'v' : 'revision'}=${revision}`,+ requestedRevision: revision, appliedRevision: null, documentId: null, updateReady: false,+ } : null+ return { scope, slots: [slot, null], front: slot ? 0 : null, error: null }+ })+ // Hydration adopts this exact HTML load. Keep it through Strict Mode's effect+ // replay, but never reuse it after navigation to a different document scope.+ const initialDisplay = useRef<PreviewDisplay | null>(display)+ const [linkRequest, setLinkRequest] = useState<{ scope: string; url: string } | null>(null)const linksPausedUntil = useRef(0)const closeLinkRequest = useCallback(() => {linksPausedUntil.current = Date.now() + LINK_PAUSE_MSsetLinkRequest(null)}, [])+useEffect(() => {+ if (!accessAllowed) {+ initialDisplay.current = null+ setDisplay({ scope, slots: [null, null], front: null, error: null })+ setLinkRequest(null)+ demand.current = () => {}+ retry.current = () => {}++ canCapture.current = () => false++ resumeUpdates.current = () => {}+ return+ }+ const sessionId = source.sessionId+ const session = encodeURIComponent(sessionId)+ const initial = initialDisplay.current?.scope === scope ? initialDisplay.current : null+ if (!initial) initialDisplay.current = null+ const slots: [PreviewSlot | null, PreviewSlot | null] = [initial?.slots[0] ? { ...initial.slots[0] } : null, null]+ let front = initial?.front ?? null+ let desired = slots[0]?.requestedRevision ?? 0+ let error: string | null = null+ let disposed = false+ let attempt: PreviewAttempt | null = null+ let loading: number | null = slots[0] ? 0 : null+ let loadTimer: ReturnType<typeof setTimeout> | null = null+ let loadClock: { remaining: number; checkedAt: number; visible: boolean } | null = null+ const active = () => !disposed && currentScope.current === scope+ const urlFor = (revision: number) => `/api/artifact-frame?session=${session}&${viewing == null ? 'v' : 'revision'}=${revision}`+ const publish = () => {+ if (active()) setDisplay({ scope, slots: [slots[0] && { ...slots[0] }, slots[1] && { ...slots[1] }], front, error })+ }+ const cancelPosted = () => {+ if (!attempt?.posted) return+ const { index, documentId } = attempt.posted+ frames.current[index]?.contentWindow?.postMessage({+ type: 'fx0-preview-cancel', protocol: PREVIEW_PROTOCOL, requestId: attempt.requestId, documentId,+ }, window.location.origin)+ }+ const clearAttempt = () => {+ if (attempt?.timer) clearTimeout(attempt.timer)+ attempt?.controller.abort()+ attempt = null+ }+ const clearLoading = () => {+ if (loadTimer) clearTimeout(loadTimer)+ loadTimer = null+ loadClock = null+ if (loading != null) {+ slots[loading] = null+ if (front === loading) front = null+ }+ loading = null+ }+ const fail = (message: string) => {+ error = message+ publish()+ }+ const watchLoad = (index: number) => {+ const clock = { remaining: PREVIEW_PREPARE_MS * 2, checkedAt: Date.now(), visible: document.visibilityState === 'visible' }+ loadClock = clock+ const check = () => {+ if (!active() || loading !== index || loadClock !== clock) return+ const now = Date.now(), elapsed = now - clock.checkedAt, visible = document.visibilityState === 'visible'+ // Painting waits on animation frames. Hidden or suspended time cannot prove+ // that a loaded document failed; acquisition/preparation keep their own bounds.+ if (clock.visible && visible && elapsed <= 3000) clock.remaining -= Math.max(0, elapsed)+ clock.checkedAt = now+ clock.visible = visible+ if (visible && elapsed > 3000) frames.current[index]?.contentWindow?.postMessage({ type: 'fx0-preview-status', protocol: PREVIEW_PROTOCOL }, window.location.origin)+ if (clock.remaining <= 0) {+ clearLoading()+ fail('The design preview did not finish loading. Try again.')+ return+ }+ loadTimer = setTimeout(check, 500)+ }+ loadTimer = setTimeout(check, 500)+ }+ const onVisibilityChange = () => {+ if (!active() || !loadClock) return+ loadClock.checkedAt = Date.now()+ loadClock.visible = document.visibilityState === 'visible'+ if (loadClock.visible && loading != null) frames.current[loading]?.contentWindow?.postMessage({ type: 'fx0-preview-status', protocol: PREVIEW_PROTOCOL }, window.location.origin)+ }+ if (loading != null) watchLoad(loading)+ const loadFull = (revision: number) => {+ const index = front == null ? 0 : 1 - front+ // Never reuse a URL as evidence of document identity, including after a hot+ // patch. A distinct mount URL also rejects queued messages from the old page+ // in this slot's (stable) WindowProxy.+ slots[index] = {+ mountUrl: `${urlFor(revision)}&mount=${crypto.randomUUID()}`,+ requestedRevision: revision, appliedRevision: null, documentId: null, updateReady: false,+ }+ loading = index+ watchLoad(index)+ publish()+ }++ const pump = async () => {- if (!active() || !desired || error || attempt || loading != null) return++ if (!active() || !desired || error || attempt || loading != null || capturingScope.current === scope) return+ const shown = front == null ? null : slots[front]+ // A legacy wrapper can confirm a full load, but cannot advertise hot updates.+ if (shown && (shown.appliedRevision ?? shown.requestedRevision) >= desired) return+ const next: PreviewAttempt = {+ revision: desired, controller: new AbortController(), timer: null,+ requestId: crypto.randomUUID(), posted: null,+ }+ attempt = next+ const deadline = Date.now() + PREVIEW_PREPARE_MS+ next.timer = setTimeout(() => next.controller.abort(), PREVIEW_PREPARE_MS)+ const isCurrent = () => active() && attempt === next+ try {+ // Updates read the entire body under the same deadline, not just headers.+ // The initial server-rendered artifact loads HTML directly instead.+ const response = await fetchUi(`${urlFor(next.revision)}&format=json`, {+ signal: next.controller.signal, cache: 'no-store',+ })+ if (!isCurrent()) return+ if (response.status === 404) throw new Error('This design is not available. Try again.')+ const unsupported = [400, 406, 415, 501].includes(response.status)+ if (!response.ok && !unsupported) throw new Error('The design could not be loaded. Try again.')+ const body = await response.text()+ if (!isCurrent()) return+ if (Date.now() >= deadline || next.controller.signal.aborted) throw new Error('Preview request timed out. Try again.')+ let payload: unknown = null+ if (!unsupported && response.headers.get('content-type')?.includes('application/json')) {+ try { payload = JSON.parse(body) } catch { /* An older or unknown representation uses HTML once. */ }+ }+ if (Date.now() >= deadline) throw new Error('Preview request timed out. Try again.')+ if (next.timer) clearTimeout(next.timer)+ next.timer = null+ if (!isPreviewPayload(payload)) {+ clearAttempt()+ loadFull(desired)+ return+ }+ if (payload.sessionId !== sessionId || (viewing == null ? payload.revision < desired : payload.revision !== viewing)) {+ throw new Error('The requested design version is not available yet. Try again.')+ }+ // A response may already be ahead of its journal event. Never send an+ // older revision back into the confirmed document.+ if (shown?.appliedRevision != null && payload.revision <= shown.appliedRevision) {+ clearAttempt()+ return+ }++ // Acquisition can finish after a photo started; leave desired queued until it ends.++ if (capturingScope.current === scope) {++ clearAttempt()++ return++ }+ if (viewing != null || !shown?.updateReady || !shown.documentId || front == null) {+ clearAttempt()+ loadFull(payload.revision)+ return+ }+ const targetWindow = frames.current[front]?.contentWindow+ if (!targetWindow) throw new Error('The design preview is unavailable. Try again.')+ next.posted = { index: front, documentId: shown.documentId, revision: payload.revision }+ targetWindow.postMessage({+ type: 'fx0-preview-update', protocol: PREVIEW_PROTOCOL, requestId: next.requestId,+ documentId: shown.documentId, baseRevision: shown.appliedRevision, payload,+ }, window.location.origin)+ // The wrapper owns image preparation and its visible-time ACK deadline.+ // Keep this attempt occupied until its result, even if desired moves on.+ } catch (cause) {+ if (!isCurrent()) return+ const timedOut = Date.now() >= deadline || next.controller.signal.aborted+ clearAttempt()+ fail(cause instanceof AuthRouteError ? cause.message+ : timedOut ? 'Preview request timed out. Try again.'+ : cause instanceof Error && cause.message ? cause.message : 'The design could not be loaded. Try again.')+ }+ }++ demand.current = (revision, again = false) => {+ const target = revision > 0 ? (viewing ?? revision) : 0+ // Zero also represents revoked access. It must clear the private document,+ // rather than be treated as an older journal event to ignore.+ if (!target) {+ cancelPosted()+ clearAttempt()+ clearLoading()+ slots[0] = slots[1] = null+ front = null+ desired = 0+ error = null+ initialDisplay.current = null+ publish()+ return+ }+ const newest = viewing == null ? Math.max(desired, target) : target+ if (newest === desired && !again) return+ desired = newest+ error = null+ if (attempt?.posted) {+ // Cancel delegated preparation, but do not assume cancellation undid a+ // mutation. Its result (or a new document) must release the apply lane.+ cancelPosted()+ } else {+ clearAttempt()+ }+ clearLoading()+ publish()+ void pump()+ }+ retry.current = () => demand.current(desired, true)++ canCapture.current = () => active() && !attempt?.posted && capturingScope.current !== scope++ resumeUpdates.current = () => { void pump() }setLinkRequest(null)- }, [source.sessionId])- useEffect(() => {+ publish()+const onMessage = (event: MessageEvent) => {- if (event.origin !== window.location.origin) return- if (event.data?.type === 'fx0-artifact-open') {- // Only the design on screen may ask, never one loading underneath; one ask- // at a time, and none just after the last one closed.- const shown = frontIndex.current == null ? null : frames.current[frontIndex.current]- const url = designLinkUrl(event.data.url)- if (!url || !shown || shown.contentWindow !== event.source || Date.now() < linksPausedUntil.current) return- setLinkRequest((current) => current ?? url)+ if (!active() || event.origin !== window.location.origin) return+ const index = frames.current.findIndex((frame) => frame?.contentWindow === event.source)+ const slot = slots[index]+ if (!slot || (index !== front && index !== loading)) return+ // Source equality alone survives iframe navigation. Check the actual wrapper+ // URL as well before accepting the first document ID for this mount.+ try {+ if (frames.current[index]?.contentDocument?.URL !== new URL(slot.mountUrl, window.location.origin).href) return+ } catch { return }+ const data = event.data+ if (!data || typeof data !== 'object') return+ if (data.type === 'fx0-artifact-open') {+ const url = designLinkUrl(data.url)+ if (index !== front || !url || Date.now() < linksPausedUntil.current) return+ setLinkRequest((current) => current ?? { scope, url })return}- if (event.data?.type !== 'fx0-artifact-painted') return- const index = frames.current.findIndex((frame) => frame?.contentWindow === event.source)- if (index >= 0) bringToFront(index)+ if (data.type === 'fx0-preview-result') {+ const posted = attempt?.posted+ if (!posted || index !== front || posted.index !== index || data.protocol !== PREVIEW_PROTOCOL+ || data.requestId !== attempt?.requestId || data.documentId !== posted.documentId+ || data.documentId !== slot.documentId || data.sessionId !== sessionId || data.revision !== posted.revision+ || !['applied', 'reload', 'error'].includes(data.status)) return+ const superseded = attempt!.revision < desired+ clearAttempt()+ if (data.status === 'applied') {+ slot.appliedRevision = Math.max(slot.appliedRevision ?? 0, data.revision)+ error = null+ publish()+ void pump()+ } else if (data.status === 'reload') {+ // Read latest again: a newer publish can have arrived during preparation.+ loadFull(Math.max(desired, data.revision))+ } else if (superseded) {+ void pump()+ } else {+ fail('The design update could not be applied. Your previous preview is still shown. Try again.')+ }+ return+ }+ if (data.type !== 'fx0-artifact-painted') return+ const legacy = data.protocol === undefined && data.sessionId === undefined && data.revision === undefined+ && data.documentId === undefined && data.updateReady === undefined+ if (!legacy && (data.protocol !== PREVIEW_PROTOCOL || data.sessionId !== sessionId+ || !Number.isSafeInteger(data.revision) || data.revision < slot.requestedRevision+ || typeof data.documentId !== 'string' || !data.documentId || typeof data.updateReady !== 'boolean')) return+ const revision = legacy ? slot.requestedRevision : data.revision as number+ const confirmed = front == null ? null : slots[front]?.appliedRevision+ if ((viewing != null && revision !== viewing) || (index !== front && revision < desired)+ || (viewing == null && confirmed != null && revision < confirmed)) return+ if (index === front && loading !== index && slot.documentId === (legacy ? null : data.documentId)+ && (slot.appliedRevision ?? slot.requestedRevision) === revision+ && slot.updateReady === (!legacy && data.updateReady)) return+ // Recovery keeps the wrapper WindowProxy but installs a new child document.+ // Invalidate work tied to the previous document before accepting that paint.+ if (slot.documentId !== (legacy ? null : data.documentId)) {+ cancelPosted()+ clearAttempt()+ setLinkRequest(null)+ }+ slot.appliedRevision = legacy ? null : revision+ slot.documentId = legacy ? null : data.documentId+ slot.updateReady = !legacy && data.updateReady+ if (loading === index) {+ if (loadTimer) clearTimeout(loadTimer)+ loadTimer = null+ loadClock = null+ loading = null+ // Old documents are deliberately not cached after cross-document navigation.+ slots[1 - index] = null+ front = index+ setLinkRequest(null)+ }+ error = null+ publish()+ void pump()}window.addEventListener('message', onMessage)+ document.addEventListener('visibilitychange', onVisibilityChange)+ // The SSR iframe can paint before hydration installs this listener.+ for (const frame of frames.current) frame?.contentWindow?.postMessage({ type: 'fx0-preview-status', protocol: PREVIEW_PROTOCOL }, window.location.origin)return () => {+ disposed = true+ cancelPosted()+ clearAttempt()+ clearLoading()window.removeEventListener('message', onMessage)- if (fallback.current) clearTimeout(fallback.current)+ document.removeEventListener('visibilitychange', onVisibilityChange)+ demand.current = () => {}+ retry.current = () => {}++ canCapture.current = () => false++ resumeUpdates.current = () => {}}- }, [])- // screenshot_design photographs the design on screen in place: no reload, and the photo is- // what the user sees. A past revision on screen or a frame with no size (behind the chat on- // a phone) hands the request to the hidden copy at once (onCaptureDone(cid, false)), and so- // does a revision that has not started loading here after CAPTURE_PREVIEW_START_MS. A slot- // loading the asked revision is waited for, up to CAPTURE_PAINT_MS: the hidden copy would- // load the same document from scratch. Once the frame is asked, its answer is final.+ }, [source.sessionId, viewing, scope, accessAllowed])++ useEffect(() => {+ demand.current(source.revision)+ }, [source.sessionId, source.revision, viewing])++ const current = display.scope === scope+ const slots: PreviewDisplay['slots'] = current ? display.slots : [null, null]+ const front = current ? display.front : null++ // Hot patches keep the mount URL: only the confirmed applied revision identifies++ // the design on screen. Never capture a frame retained from another scope.+ const captureDone = useRef(onCaptureDone)+ captureDone.current = onCaptureDone+ const waitingCapture = useRef<{ request: CaptureRequest; timer: ReturnType<typeof setTimeout>; loading: boolean } | null>(null)+ const settleCapture = (request: CaptureRequest): boolean => {+ if (waitingCapture.current?.request !== request) return false+ clearTimeout(waitingCapture.current.timer)+ waitingCapture.current = null+ return true+ }+ const handOffCapture = (request: CaptureRequest) => {+ if (settleCapture(request)) captureDone.current?.(request.cid, false)+ }- const failCapture = (request: CaptureRequest) => {- if (settleCapture(request)) void reportCaptureFailure(request, 'not-painted').finally(() => captureDone.current?.(request.cid, true))++ const failCapture = (request: CaptureRequest, reason: CaptureFailure = 'not-painted') => {++ if (settleCapture(request)) void reportCaptureFailure(request, reason).finally(() => captureDone.current?.(request.cid, true))+ }+ useEffect(() => {+ if (!capture) return+ const request = capture+ waitingCapture.current = { request, timer: setTimeout(() => handOffCapture(request), CAPTURE_PREVIEW_START_MS), loading: false }+ return () => handOffCapture(request)- }, [capture?.cid]) // eslint-disable-line react-hooks/exhaustive-deps++ }, [capture?.cid, scope]) // eslint-disable-line react-hooks/exhaustive-deps+ useEffect(() => {+ const waiting = waitingCapture.current+ if (!waiting) return+ const { request } = waiting- if (viewing != null) return handOffCapture(request)- if (!previewUrl?.endsWith(`&v=${request.revision}`)) return- const index = slots.indexOf(previewUrl)++ if (!accessAllowed || !current || request.sessionId !== source.sessionId || viewing != null) return handOffCapture(request)++ const index = slots.findIndex((slot) => slot?.appliedRevision === request.revision)+ const frame = index < 0 ? null : frames.current[index]- if (!frame) return- if (frame.getBoundingClientRect().width < 1) return handOffCapture(request)- if (front !== index || !frame.contentWindow) {++ if (!frame && source.revision !== request.revision) return++ if (frame && frame.getBoundingClientRect().width < 1) return handOffCapture(request)++ if (!frame || front !== index || !frame.contentWindow) {+ if (!waiting.loading) {+ clearTimeout(waiting.timer)+ waiting.loading = true+ waiting.timer = setTimeout(() => failCapture(request), CAPTURE_PAINT_MS)+ }+ return+ }++ if (!canCapture.current()) return failCapture(request, 'capture-failed')+ settleCapture(request)++ capturingScope.current = scope+ const askedAt = Date.now()++ let released = false++ const releaseCapture = () => {++ if (released) return++ released = true++ if (capturingScope.current === scope) capturingScope.current = null++ resumeUpdates.current()++ }+ void captureFrame(frame.contentWindow, request.cid, request.full)- .then((reply) => sendCapture(request, reply, { path: 'preview', askedAt }))- .finally(() => captureDone.current?.(request.cid, true))- }, [capture?.cid, front, slots, previewUrl, viewing]) // eslint-disable-line react-hooks/exhaustive-deps- const caughtUp = !previewUrl || (front != null && slots[front] === previewUrl)- const [heldDraft, setHeldDraft] = useState<string | null>(null)- const liveDraft = draft && renderable(draft) ? draft : null++ .then((reply) => {++ // Bytes are fixed now; a slow upload must not hold later preview updates.++ releaseCapture()++ if (currentScope.current !== scope) return reportCaptureFailure(request, 'capture-failed')++ return sendCapture(request, reply, { path: 'preview', askedAt })++ })++ .finally(() => {++ releaseCapture()++ captureDone.current?.(request.cid, true)++ })++ }, [capture?.cid, current, slots, front, source.sessionId, source.revision, viewing, accessAllowed]) // eslint-disable-line react-hooks/exhaustive-deps+ const published = front != null+ const [heldDraft, setHeldDraft] = useState<{ scope: string; html: string } | null>(null)+ const liveDraft = accessAllowed && draft && renderable(draft) ? draft : nulluseEffect(() => {- if (liveDraft) setHeldDraft(liveDraft)- else if (!draft && caughtUp) setHeldDraft(null)- }, [liveDraft, draft, caughtUp])- const draftLayer = liveDraft ?? heldDraft- const shownUrl = front != null ? slots[front] : null+ if (!accessAllowed || published) setHeldDraft(null)+ else if (liveDraft) setHeldDraft({ scope, html: liveDraft })+ else if (!draft && source.revision === 0) setHeldDraft(null)+ }, [liveDraft, draft, published, scope, source.revision, accessAllowed])+ // Once published, never cover the live program with a scriptless draft photo.+ const draftLayer = published ? null : liveDraft ?? (heldDraft?.scope === scope ? heldDraft.html : null)useEffect(() => {const onKeyDown = (event: KeyboardEvent) => {diff --cc lib/design-artifact.tsindex 2e4e1e0,c91a027..ff366c4--- a/lib/design-artifact.ts+++ b/lib/design-artifact.ts@@@ -70,13 -73,12 +73,21 @@@ export const DESIGN_FRAME_CSP = designF// Counted per place an image is written, so a repeated image cannot expand the design past it.export const MAX_EMBEDDED_IMAGE_BYTES = 4 * 1024 * 1024++// The screenshot hook. `relay` is wrapper script, run before the design loads; `script`++// returns the capture runtime for a child document carrying the given token.++export interface DesignFrameCapture {++ relay: string++ script?: (readyToken: string) => string++}++// The page artifact-frame serves under designFrameCsp(): it frames the prepared design// and relays its heartbeat, paint and link messages to the app. Each image marker in the// design becomes its image, loaded from `src` (cached by the browser across revisions),// within MAX_EMBEDDED_IMAGE_BYTES counted per occurrence; a missing image is blank. Only- // then does the design start, so it never needs the network. `relay` is more wrapper- // script (lib/design-capture.ts), run before the design loads.- export function designFrameHtml(preparedArtifact: string, readyToken: string, images: { marker: string; src: string }[] = [], relay = ''): string {-// then does the design start, so it never needs the network.-export function designFrameHtml(preparedArtifact: string, readyToken: string, images: { marker: string; src: string }[] = [], preview?: PreviewPayload): string {++// then does the design start, so it never needs the network. `capture` is the screenshot++// hook (lib/design-capture.ts): its relay runs in this wrapper, and every child document++// the wrapper builds from a preview gets the runtime bound to that child's own token.++export function designFrameHtml(preparedArtifact: string, readyToken: string, images: { marker: string; src: string }[] = [], preview?: PreviewPayload, capture?: DesignFrameCapture): string {// The design reaches its frame as a blob: URL the wrapper makes from this string,// not as a data: URL: browsers refuse data: URLs past 2 MiB, which embedded images// reach. A blob: document is local like data:, so it inherits this wrapper's CSP and@@@ -84,6 -86,11 +95,16 @@@const serializedArtifact = JSON.stringify(preparedArtifact).replace(/</g, '\\u003c')const serializedReadyToken = JSON.stringify(readyToken)const serializedImages = JSON.stringify(images).replace(/</g, '\\u003c')+ const scriptJson = (value: unknown) => JSON.stringify(value).replace(/</g, '\\u003c')+ const bootstrapToken = 'fx0-bootstrap-token'+ const childBootstrap = scriptJson(designArtifactBootstrap(bootstrapToken))+ const childCsp = scriptJson(`<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(DESIGN_ARTIFACT_EMBEDDED_CSP)}">`)+ const updater = scriptJson(previewUpdateRuntime.toString())++ // Built once with a placeholder token, then bound in the browser to each child's token: a++ // child rebuilt by a restore must not keep the token of the document it replaced.++ const runtimeToken = 'fx0-runtime-token'++ const runtimeJs = capture?.script ? scriptJson(capture.script(runtimeToken)) : 'null'++ const runtimeTarget = scriptJson(JSON.stringify(runtimeToken))// The wrapper paints nothing of its own, so a design that has not painted yet// shows the app's background. Sharing the app's color scheme keeps it// transparent; a design that sets no background still gets the browser's white.@@@ -110,47 -123,133 +137,139 @@@ frame.setAttribute('credentialless','')let readySignals=0;let consumedSignals=0;let lastHeartbeat=Date.now();- // A relay can hold off restores while the design is busy on its behalf (lib/design-capture.ts).++// A capture can hold off restores while the design is busy photographing itself (lib/design-capture.ts).+let holdUntil=0;- const restore=()=>{if(!artifact)return;lastHeartbeat=Date.now();frame.src=artifact;};++// The capture runtime, bound to each child's own token by the restore that builds that child.++const captureRuntimeJs=${runtimeJs};+ const safe=value=>JSON.stringify(value).replaceAll('<',String.fromCharCode(92)+'u003c');+ const painted=()=>parent.postMessage(preview?{type:'fx0-artifact-painted',protocol:1,sessionId:preview.sessionId,revision:current.revision,documentId,updateReady:hotReady}:{type:'fx0-artifact-painted'},location.origin);+ const reply=(task,status,reason)=>parent.postMessage({type:'fx0-preview-result',protocol:1,sessionId:preview.sessionId,requestId:task.requestId,documentId:task.documentId,revision:task.payload.revision,status,...(reason?{reason}:{})},location.origin);+ const finish=(task,status,reason)=>{if(pending!==task)return;pending=null;task.controller.abort();reply(task,status,reason);};+ const restore=()=>{+ if(!current)return;+ if(pending)finish(pending,'reload','document-restarted');+ hotReady=hasPainted=false;readySignals=consumedSignals=0;lastHeartbeat=Date.now();+ let html=current.renderHtml;+ if(preview){+ documentId=token=crypto.randomUUID();+ const seed={sessionId:preview.sessionId,revision:current.revision,sourceHtml:current.sourceHtml,renderHtml:html,documentId,parentOrigin:location.origin,token};+ const bootstrap=${childBootstrap}.replace(${scriptJson(JSON.stringify(bootstrapToken))},JSON.stringify(token));- html='<!doctype html>'+${childCsp}+bootstrap+'<script>('+${updater}+')('+safe(seed)+')</scr'+'ipt>'+html.slice('<!doctype html>'.length);++ const runtime=captureRuntimeJs?captureRuntimeJs.replaceAll(${runtimeTarget},JSON.stringify(token)):'';++ html='<!doctype html>'+${childCsp}+bootstrap+runtime+'<script>('+${updater}+')('+safe(seed)+')</scr'+'ipt>'+html.slice('<!doctype html>'.length);+ }+ const previous=artifact;+ artifact=URL.createObjectURL(new Blob([html],{type:'text/html;charset=utf-8'}));+ frame.src=artifact;+ if(previous)URL.revokeObjectURL(previous);+ };+ const validPayload=value=>value&&value.protocol===1&&value.sessionId===preview.sessionId&&Number.isSafeInteger(value.revision)&&value.revision>0&&typeof value.sourceHtml==='string'&&new TextEncoder().encode(value.sourceHtml).length<=${MAX_DESIGN_ARTIFACT_BYTES}&&typeof value.renderHtml==='string'&&value.renderHtml.length<=${MAX_DESIGN_ARTIFACT_BYTES * 2}&&Array.isArray(value.images)&&value.images.length<=12&&value.images.every(image=>{+ if(!image||typeof image.marker!=='string'||!image.marker||image.marker.length>256||typeof image.src!=='string')return false;+ try{const url=new URL(image.src,location.href);return url.origin===location.origin&&url.pathname==='/api/artifact-image'&&!url.username&&!url.password;}catch{return false;}+ });addEventListener('message',event=>{- if(event.source!==frame.contentWindow||event.data?.token!==token)return;+ const data=event.data;+ if(event.source===parent&&event.origin===location.origin&&preview){+ if(data?.type==='fx0-preview-status'&&data.protocol===1){if(hasPainted)painted();return;}+ if(!data||data.protocol!==1||data.documentId!==documentId||typeof data.requestId!=='string'||!data.requestId||data.requestId.length>128)return;+ if(data.type==='fx0-preview-cancel'){+ if(pending&&pending.requestId===data.requestId&&pending.phase==='prepare')finish(pending,'error','cancelled');+ return;+ }+ if(data.type!=='fx0-preview-update'||!validPayload(data.payload))return;+ const task={requestId:data.requestId,documentId,payload:data.payload,controller:new AbortController(),phase:'prepare',remaining:5000};+ if(pending){reply(task,'error','update-busy');return;}+ if(!hotReady||data.baseRevision!==current.revision||data.payload.revision<=current.revision){reply(task,'reload','stale-base-revision');return;}+ pending=task;+ prepare(task.payload,task.controller).then(renderHtml=>{+ if(pending!==task||documentId!==task.documentId)return;+ task.renderHtml=renderHtml;task.phase='apply';+ frame.contentWindow.postMessage({type:'fx0-preview-apply',protocol:1,token,documentId,requestId:task.requestId,baseRevision:current.revision,revision:task.payload.revision,sourceHtml:task.payload.sourceHtml,renderHtml},'*');+ }).catch(()=>finish(task,'error','preparation-failed'));+ return;+ }+ if(event.source!==frame.contentWindow||data?.token!==token)return;lastHeartbeat=Date.now();- if(event.data.type==='ready')readySignals++;- // The design paints in its own process, after this wrapper's load event; the app- // swaps a new revision on screen only once it has.- if(event.data.type==='painted')parent.postMessage({type:'fx0-artifact-painted'},location.origin);- // The design can only ask to open a link: its scripts can read the token and send- // this at any time. The app shows the address and opens it on the user's own click- // there. Recent user activation only filters out asks nobody prompted; it is not proof.- if(event.data.type==='open'&&typeof event.data.url==='string'&&navigator.userActivation?.isActive!==false){- parent.postMessage({type:'fx0-artifact-open',url:event.data.url},location.origin);+ if(data.type==='ready')readySignals++;+ if(data.type==='fx0-preview-ready'&&data.protocol===1&&data.documentId===documentId&&data.revision===current?.revision){hotReady=data.ready===true;return;}+ if(data.type==='fx0-preview-result'&&data.protocol===1&&data.documentId===documentId){+ const task=pending;+ if(!task||task.phase!=='apply'||data.requestId!==task.requestId)return;+ if(data.status==='applied'&&data.revision===task.payload.revision){+ current={sourceHtml:task.payload.sourceHtml,renderHtml:task.renderHtml,revision:task.payload.revision};+ finish(task,'applied');+ }else if(data.status==='reload'){+ hotReady=false;+ finish(task,'reload',typeof data.reason==='string'?data.reason.slice(0,120):'incompatible-update');+ }+ return;+ }+ // Paint and link messages are observations, never authority to fetch or mutate the host.+ if(data.type==='painted'){hasPainted=true;painted();}+ if(data.type==='open'&&typeof data.url==='string'&&navigator.userActivation?.isActive!==false){+ parent.postMessage({type:'fx0-artifact-open',url:data.url},location.origin);}});- frame.addEventListener('load',()=>setTimeout(()=>{- if(readySignals>consumedSignals){consumedSignals=readySignals;return;}- restore();- },100));+ frame.addEventListener('load',()=>{+ const loadedDocument=documentId;+ setTimeout(()=>{+ if(loadedDocument!==documentId)return;+ if(readySignals>consumedSignals){consumedSignals=readySignals;return;}+ restore();+ },100);+ });// Hidden time and suspended timers are browser pauses, not design failures.let lastCheck=Date.now();document.addEventListener('visibilitychange',()=>{lastHeartbeat=lastCheck=Date.now();});setInterval(()=>{- const now=Date.now(),paused=now-lastCheck>3000;+ const now=Date.now(),elapsed=now-lastCheck,paused=elapsed>3000;lastCheck=now;if(document.visibilityState!=='visible'||paused){lastHeartbeat=now;return;}+ if(pending?.phase==='apply'){+ pending.remaining-=Math.max(0,elapsed);+ if(pending.remaining<=0){finish(pending,'reload','application-timeout');restore();return;}+ }- if(now-lastHeartbeat>3000)restore();+ if(now-lastHeartbeat>3000&&now>holdUntil)restore();},500);- ${relay}const read=blob=>new Promise(done=>{const reader=new FileReader();reader.onload=()=>done(String(reader.result));reader.onerror=()=>done(null);reader.readAsDataURL(blob)});- const load=async src=>{try{const response=await fetch(src,{credentials:'same-origin'});if(!response.ok)return null;const blob=await response.blob();return /^image\\/(png|jpeg|gif|webp|avif)$/.test(blob.type)?await read(blob):null}catch{return null}};- Promise.all(images.map(image=>load(image.src))).then(loaded=>{- let html=design,total=0;- images.forEach((image,index)=>{- const data=loaded[index],size=data?(data.length-data.indexOf(',')-1)*3/4-(data.endsWith('==')?2:data.endsWith('=')?1:0):0;- html=html.split(image.marker).map((part,at)=>at===0?part:(data&&total+size<=${MAX_EMBEDDED_IMAGE_BYTES}?(total+=size,data):${JSON.stringify(BLANK_IMAGE)})+part).join('');- });- artifact=URL.createObjectURL(new Blob([html],{type:'text/html;charset=utf-8'}));- lastHeartbeat=Date.now();- frame.src=artifact;++${capture?.relay ?? ''}+ const read=(blob,signal)=>new Promise(done=>{+ const reader=new FileReader();+ const abort=()=>{reader.abort();complete(null);};+ const complete=value=>{signal.removeEventListener('abort',abort);reader.onload=reader.onerror=reader.onabort=null;done(value);};+ reader.onload=()=>complete(String(reader.result));reader.onerror=reader.onabort=()=>complete(null);+ if(signal.aborted){complete(null);return;}+ signal.addEventListener('abort',abort,{once:true});reader.readAsDataURL(blob);+ });+ const load=async(src,signal,deadline)=>{+ try{+ const response=await fetch(src,{credentials:'same-origin',signal});+ if(!response.ok)return null;+ const blob=await response.blob();+ if(signal.aborted||Date.now()>=deadline||!/^image\\/(png|jpeg|gif|webp|avif)$/.test(blob.type))return null;+ const data=await read(blob,signal);+ return !signal.aborted&&Date.now()<deadline?data:null;+ }catch{return null;}+ };+ const prepare=async(payload,controller)=>{+ const deadline=Date.now()+10000;+ const timer=setTimeout(()=>controller.abort(),10000);+ try{+ const loaded=await Promise.all(payload.images.map(image=>load(image.src,controller.signal,deadline)));+ let html=payload.renderHtml,total=0;+ payload.images.forEach((image,index)=>{+ const data=loaded[index],size=data?(data.length-data.indexOf(',')-1)*3/4-(data.endsWith('==')?2:data.endsWith('=')?1:0):0;+ html=html.split(image.marker).map((part,at)=>at===0?part:(data&&total+size<=${MAX_EMBEDDED_IMAGE_BYTES}?(total+=size,data):${JSON.stringify(BLANK_IMAGE)})+part).join('');+ });+ return html;+ }finally{clearTimeout(timer);}+ };+ const initialController=new AbortController();+ let disposed=false;+ addEventListener('pagehide',()=>{disposed=true;initialController.abort();if(pending)finish(pending,'error','unmounted');if(artifact)URL.revokeObjectURL(artifact);});+ const initial=preview??{renderHtml:design,sourceHtml:design,revision:0,images};+ prepare(initial,initialController).then(renderHtml=>{+ if(disposed)return;+ current={sourceHtml:initial.sourceHtml,renderHtml,revision:initial.revision};+ restore();document.querySelector('#frame-root').append(frame);});</script>diff --cc lib/design-capture.tsindex b32861d,0000000..2440c86mode 100644,000000..100644--- a/lib/design-capture.ts+++ b/lib/design-capture.ts@@@ -1,102 -1,0 +1,107 @@@+// @ts-expect-error Node strip-types tests require the source extension.+import { CAPTURE_LIBRARY_MS, CAPTURE_REPLY, CAPTURE_REQUEST, MAX_CAPTURE_BYTES, MAX_CAPTURE_TILES } from './capture-protocol.ts'+// @ts-expect-error Node strip-types tests require the source extension.+import { FAST_HTML_TO_IMAGE } from './vendor/fast-html-to-image.ts'++// The frame side of the screenshot protocol (lib/capture-protocol.ts). The capture library+// runs inside the design's own frame, under the CSP that gives the design no network, so+// it cannot fetch anything the design names either: the photo shows what the screen shows.+// The design's scripts share that realm and can tamper with their own photo; that only+// misleads the model about its own work, and /api/capture still checks the bytes.++/** The library and its message handler, injected into every prepared design. */+export function designCaptureScript(readyToken: string): string {+ // Encodes at once: canvas.toBlob waits for an idle moment a busy page never has. WebP is+ // about half the bytes of a JPEG at the same quality, which the upload feels most; a+ // browser that cannot write WebP (Safari) returns a PNG for it, and gets JPEG instead.+ // Nothing runs until the first capture, so a preview that is never photographed pays+ // only for parsing the library.+ const handler = `(() => {+ const token = ${JSON.stringify(readyToken)}, maxBytes = ${MAX_CAPTURE_BYTES}, maxTiles = ${MAX_CAPTURE_TILES};+ let type = null;+ const encode = (canvas, quality) => {+ if (!type) {+ const probe = document.createElement("canvas");+ probe.width = probe.height = 1;+ type = probe.toDataURL("image/webp").startsWith("data:image/webp") ? "image/webp" : "image/jpeg";+ }+ const url = canvas.toDataURL(type, quality), binary = atob(url.slice(url.indexOf(",") + 1));+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);+ return new Blob([bytes], { type });+ };+ const total = (blobs) => blobs.reduce((sum, blob) => sum + blob.size, 0);+ // A remainder under 15% of a viewport joins the last tile instead of becoming its own.+ const slack = () => Math.round(innerHeight * 0.15);+ // The page, cut into viewport-high tiles from the top.+ const tiles = (page) => {+ const height = innerHeight, count = Math.min(maxTiles, Math.max(1, Math.ceil((page.height - slack()) / height)));+ return Array.from({ length: count }, (_, i) => {+ const tile = document.createElement("canvas");+ tile.width = page.width;+ tile.height = i === count - 1 ? Math.min(page.height - i * height, height + slack()) : height;+ tile.getContext("2d").drawImage(page, 0, i * height, page.width, tile.height, 0, 0, page.width, tile.height);+ return tile;+ });+ };+ addEventListener("message", async (event) => {+ if (event.source !== parent || event.data?.type !== "capture" || typeof event.data.cid !== "string") return;+ const { cid, full } = event.data;+ const reply = (data) => parent.postMessage({ type: "captured", token, cid, ...data }, "*");+ try {+ const t0 = performance.now();+ await document.fonts.ready;+ const t1 = performance.now();+ const options = { pixelRatio: 1, backgroundColor: "#ffffff", timeoutMs: ${CAPTURE_LIBRARY_MS} };+ // A full page is the document from its top, as tall as its content (which can overflow+ // an html{height:100%} box) but no taller than the tiles can carry.+ const root = document.documentElement, pageHeight = Math.max(root.scrollHeight, document.body?.scrollHeight ?? 0);+ const region = full+ ? { x: 0, y: root.getBoundingClientRect().top, width: innerWidth, height: Math.min(pageHeight, maxTiles * innerHeight + slack()) }+ : { x: 0, y: 0, width: innerWidth, height: innerHeight };++ // Hot updates edit CSSOM declarations without changing the style element. An empty++ // stylesheet mutation invalidates the fork's style caches without replacing app sheets.++ const invalidation = document.createElement("style");++ document.head.append(invalidation);++ invalidation.remove();+ const page = await (await FastHtmlToImage.captureRegion(region, options)).toCanvas();+ const t2 = performance.now();+ const parts = full ? tiles(page) : [page];+ // One pass at a good quality; over the limit, one more at the quality the size suggests.+ let blobs = parts.map((part) => encode(part, 0.85));+ if (total(blobs) > maxBytes) {+ const quality = Math.min(0.75, Math.max(0.3, 0.85 * (maxBytes / total(blobs)) * 0.9));+ blobs = parts.map((part) => encode(part, quality));+ }+ const t3 = performance.now();+ if (total(blobs) > maxBytes) return reply({ error: "too-large" });+ const covered = parts.reduce((sum, part) => sum + part.height, 0);+ reply({+ blobs, width: page.width, height: page.height, truncated: full && covered < pageHeight,+ timing: { fontsMs: t1 - t0, libraryMs: t2 - t1, encodeMs: t3 - t2 },+ });+ } catch {+ reply({ error: "capture-failed" });+ }+ });+})()`+ return `<script>${FAST_HTML_TO_IMAGE}</script><script>${handler}</script>`+}++// Added to the wrapper's script (designFrameHtml), where `frame`, `token` and `holdUntil`+// are in scope. Only the app may ask for a photo, and only the design's reply is passed+// on. A large page can block its own heartbeat while it is photographed, so the wrapper+// holds off restoring it until the reply or the library's time limit.+export const DESIGN_CAPTURE_RELAY = `addEventListener('message',event=>{+ const data=event.data;+ if(event.source===parent&&event.origin===location.origin&&data?.type===${JSON.stringify(CAPTURE_REQUEST)}&&typeof data.cid==='string'){+ holdUntil=Date.now()+${CAPTURE_LIBRARY_MS};+ frame.contentWindow?.postMessage({type:'capture',cid:data.cid,full:data.full===true},'*');+ }else if(event.source===frame.contentWindow&&data?.token===token&&data.type==='captured'&&typeof data.cid==='string'){+ holdUntil=0;+ const blobs=Array.isArray(data.blobs)?data.blobs.filter(blob=>blob instanceof Blob):[];+ const error=typeof data.error==='string'?data.error:undefined;+ parent.postMessage({type:${JSON.stringify(CAPTURE_REPLY)},cid:data.cid,blobs,error,width:data.width,height:data.height,truncated:data.truncated===true,timing:data.timing},location.origin);+ }+});+`diff --cc tests/core.test.mjsindex b73653f,98afa8e..b27d478--- a/tests/core.test.mjs+++ b/tests/core.test.mjs@@@ -763,12 -744,14 +763,14 @@@ async function frameWatchdog(relay = ''querySelector: () => ({ append() {} }),addEventListener: (type, listener) => documentListeners.set(type, listener),}- const html = designFrameHtml(SAFE_DESIGN, 'watchdog-test', [], relay)- const html = designFrameHtml(SAFE_DESIGN, 'watchdog-test')++ const html = designFrameHtml(SAFE_DESIGN, 'watchdog-test', [], undefined, { relay })runInNewContext(html.match(/<script>([\s\S]*?)<\/script>/)[1], {document,+ parent: {},Date: { now: () => now },Blob,- URL: { createObjectURL: () => 'blob:design' },+ AbortController,+ URL: { createObjectURL: () => 'blob:design', revokeObjectURL() {} },addEventListener: (type, listener) => listeners.set(type, listener),setInterval: (callback) => { check = callback },setTimeout() {},diff --cc tests/design-artifact.browser.mjsindex 901d408,e603e93..da397a7--- a/tests/design-artifact.browser.mjs+++ b/tests/design-artifact.browser.mjs@@@ -191,86 -190,6 +191,229 @@@ for (const name of ['small', 'large', '}})+// screenshot_design: the app mounts a preview the way DesignCapture does+// (fixed, invisible, under the page, in a phone-sized window) and asks it for photos once+// it has painted: the viewport, then the whole page. The viewport must come back as one+// 1280x800 WebP of the design, the page as viewport-high tiles from the top (even when+// html and body are only viewport-high and the content overflows them), and the remote+// url() the design names must never reach the network, capture included.+test('in Chrome, a hidden preview photographs its viewport and its whole page without any network', async () => {+ assert.ok(existsSync(CHROME), `Chrome not found at ${CHROME}; set CHROME_PATH`)+ const requests = []+ const server = http.createServer((request, response) => {+ const url = new URL(request.url, 'http://test')+ requests.push(url.pathname)+ if (url.pathname === '/frame') {+ const stored = validateDesignArtifactHtml(`<!doctype html><html><head><style>html,body{margin:0;height:100%}+section{height:800px}.a{background:#ff0066}.b{background:#00cc66}.c{height:400px;background:#3366ff}+.leak{background:url(http://127.0.0.1:${server.address().port}/leak.png)}</style></head><body>+<section class="a"><h1 class="leak" style="color:#fff;margin:0;padding:40px">fx0</h1></section><section class="b"></section><section class="c"></section></body></html>`)+ assert.equal(stored.ok, true, stored.error)+ const token = 'browser-test'+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-security-policy': DESIGN_FRAME_CSP })- response.end(designFrameHtml(prepareDesignArtifactHtml(stored.html, DESIGN_ARTIFACT_EMBEDDED_CSP, token, designCaptureScript(token)), token, [], DESIGN_CAPTURE_RELAY))++ response.end(designFrameHtml(prepareDesignArtifactHtml(stored.html, DESIGN_ARTIFACT_EMBEDDED_CSP, token, designCaptureScript(token)), token, [], undefined, { relay: DESIGN_CAPTURE_RELAY }))+ } else if (url.pathname === '/hold') {+ setTimeout(() => response.writeHead(404).end(), 6000)+ } else if (url.pathname === '/') {+ response.writeHead(200, { 'content-type': 'text/html' }).end(`<!doctype html><html><head><title>app</title></head><body style="margin:0">+<main style="position:fixed;inset:0;background:#fff"><pre id="out">{}</pre></main>+<div style="position:fixed;inset:0;z-index:-10;overflow:hidden;opacity:0;pointer-events:none"><iframe id="capture" src="/frame" style="width:1280px;height:800px;border:0"></iframe></div>+<script>+const frame = document.getElementById('capture')+const out = {}+const show = () => { document.getElementById('out').textContent = JSON.stringify(out) }+const describe = async (blob) => {+ const bitmap = await createImageBitmap(blob)+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height)+ const context = canvas.getContext('2d')+ context.drawImage(bitmap, 0, 0)+ return { type: blob.type, width: bitmap.width, height: bitmap.height, color: [...context.getImageData(1200, bitmap.height - 20, 1, 1).data.slice(0, 3)] }+}+addEventListener('message', async ({ data, source }) => {+ if (source !== frame.contentWindow) return+ if (data?.type === 'fx0-artifact-painted' && !out.asked) {+ out.asked = true+ frame.contentWindow.postMessage({ type: 'fx0-capture', cid: 'viewport' }, location.origin)+ }+ if (data?.type !== 'fx0-artifact-captured') return+ out[data.cid] = { height: data.height, truncated: data.truncated, timing: data.timing, images: await Promise.all(data.blobs.map(describe)) }+ if (data.cid === 'viewport') frame.contentWindow.postMessage({ type: 'fx0-capture', cid: 'page', full: true }, location.origin)+ show()+})+</script><img alt="" src="/hold"></body></html>`)+ } else {+ response.writeHead(404).end()+ }+ })+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))+ const dir = await mkdtemp(join(tmpdir(), 'fx0-design-capture-'))+ try {+ const { stdout } = await promisify(execFile)(CHROME, [+ '--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check', '--window-size=390,844',+ `--user-data-dir=${join(dir, 'profile')}`, '--dump-dom', `http://127.0.0.1:${server.address().port}/`,+ ], { timeout: 60_000, maxBuffer: 16 * 1024 * 1024 })+ const out = JSON.parse(stdout.match(/<pre id="out">([^<]*)<\/pre>/)[1])+ const near = (rgb, target) => rgb.every((value, i) => Math.abs(value - target[i]) < 24)+ assert.equal(out.viewport.images.length, 1)+ assert.deepEqual(out.viewport.images.map(({ type, width, height }) => [type, width, height]), [['image/webp', 1280, 800]], 'Chrome sends WebP')+ assert.ok(near(out.viewport.images[0].color, [255, 0, 102]), `the viewport is the design's first section, got ${out.viewport.images[0].color}`)+ for (const part of ['fontsMs', 'libraryMs', 'encodeMs']) assert.ok(out.viewport.timing?.[part] >= 0, `the frame reports ${part}`)+ assert.equal(out.page.height, 2000)+ assert.equal(out.page.truncated, false)+ assert.deepEqual(out.page.images.map(({ width, height }) => [width, height]), [[1280, 800], [1280, 800], [1280, 400]])+ const colors = [[255, 0, 102], [0, 204, 102], [51, 102, 255]]+ out.page.images.forEach((image, i) => assert.ok(near(image.color, colors[i]), `tile ${i + 1} shows section ${i + 1}, got ${image.color}`))+ assert.ok(!requests.includes('/leak.png'), 'the url() the design names never reached the network')+ } finally {+ server.closeAllConnections()+ server.close()+ await rm(dir, { recursive: true, force: true })+ }+})+++// screenshot_design on a live preview, driven as the app drives it: a compatible hot update is++// photographed in place; the design is then frozen so the frame restores it under a fresh token++// and it is photographed again; an update the frame refuses makes the app reload the frame, with++// a fresh token, and it is photographed once more. Each photo must show the design it came from,++// under the wrapper's production policy and the design's embedded CSP, with no network request.++test('in Chrome, a live preview photographs its design after a hot update, a restore and a reload', async () => {++ assert.ok(existsSync(CHROME), `Chrome not found at ${CHROME}; set CHROME_PATH`)++ const session = 'capture-session'++ const requests = []++ let origin = ''++ // Freezes the design's own thread on request, as a stalled design would be.++ const FREEZE = `<script>addEventListener('message',event=>{if(event.data==='fx0-test-freeze'){const end=Date.now()+4500;while(Date.now()<end);}});</script>`++ const page = (color, tag = 'section') => `<!doctype html><html><head><title>capture</title><style>html,body{margin:0;height:100%}++${tag}{height:800px}.a{background:${color};background-image:url(${origin}/leak.png)}</style></head><body><${tag} class="a"></${tag}>${FREEZE}</body></html>`++ const source = (revision) => revision === 1 ? page('#ff0066') : revision === 2 ? page('#0066ff') : page('#00cc66', 'main')++ // The same shape the route returns as JSON, and what it hands the wrapper.++ const payload = (revision) => {++ const validation = validateDesignArtifactHtml(source(revision))++ assert.equal(validation.ok, true, validation.error)++ return { protocol: 1, sessionId: session, revision, sourceHtml: validation.html, renderHtml: validation.html, images: [] }++ }++ // The app: a fixed, invisible preview in a phone-sized window. It waits for each paint, asks for++ // photos, and sends the updates the way PreviewPane does. The hold keeps the load (and the dump)++ // open until the flow is done.++ const harness = `<!doctype html><html><head><title>app</title></head><body><pre id="out">{}</pre>++<div style="position:fixed;inset:0;z-index:-10;overflow:hidden;opacity:0;pointer-events:none"><iframe id="capture" style="width:1280px;height:800px;border:0"></iframe></div>++<script>++const out = { shots: {} }++const frame = document.getElementById('capture')++const show = () => { document.getElementById('out').textContent = JSON.stringify(out) }++const waiting = []++const next = (test) => new Promise((resolve) => waiting.push({ test, resolve }))++addEventListener('message', ({ data, source }) => {++ if (source !== frame.contentWindow || !data) return++ const at = waiting.findIndex((waiter) => waiter.test(data))++ if (at >= 0) waiting.splice(at, 1)[0].resolve(data)++})++const describe = async (blob) => {++ const bitmap = await createImageBitmap(blob)++ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height)++ const context = canvas.getContext('2d')++ context.drawImage(bitmap, 0, 0)++ return { type: blob.type, width: bitmap.width, height: bitmap.height, color: [...context.getImageData(1200, bitmap.height - 20, 1, 1).data.slice(0, 3)] }++}++const bounded = (promise, what) => Promise.race([promise, new Promise((resolve, reject) => setTimeout(() => reject(new Error(what + ' did not answer in time')), 8000))])++const painted = () => next((data) => data.type === 'fx0-artifact-painted' && data.updateReady === true)++const open = (revision) => {++ const arrived = painted()++ frame.src = '/frame?rev=' + revision + '&n=' + crypto.randomUUID()++ return bounded(arrived, 'the preview painting')++}++const shot = async (name) => {++ const reply = next((data) => data.type === 'fx0-artifact-captured' && data.cid === name)++ frame.contentWindow.postMessage({ type: 'fx0-capture', cid: name, full: false }, location.origin)++ const data = await bounded(reply, 'the capture')++ out.shots[name] = { error: data.error ?? null, images: await Promise.all(data.blobs.map(describe)) }++ show()++}++const update = async (documentId, baseRevision, revision) => {++ const body = await (await fetch('/payload?rev=' + revision)).json()++ const requestId = crypto.randomUUID()++ const result = next((data) => data.type === 'fx0-preview-result' && data.requestId === requestId)++ frame.contentWindow.postMessage({ type: 'fx0-preview-update', protocol: 1, requestId, documentId, baseRevision, payload: body }, location.origin)++ const data = await bounded(result, 'the update')++ return { status: data.status, reason: data.reason ?? null }++}++const run = async () => {++ const first = await open(1)++ await shot('pink')++ out.compatible = await update(first.documentId, 1, 2)++ await shot('blue')++ const restored = Promise.race([painted(), new Promise((_, reject) => setTimeout(() => reject(new Error('the frame did not restore a stalled design')), 9000))])++ frame.contentDocument.querySelector('#frame-root iframe').contentWindow.postMessage('fx0-test-freeze', '*')++ const again = await restored++ out.restored = again.documentId !== first.documentId++ await shot('restored')++ out.refused = await update(again.documentId, 2, 3)++ const reopened = await open(3)++ out.reopened = reopened.documentId !== again.documentId++ await shot('reloaded')++}++run().then(() => { out.done = true }, (error) => { out.error = String(error && error.message || error) }).then(() => {++ show()++ return fetch('/done')++})++</script><img alt="" src="/hold"></body></html>`++ const holds = []++ const server = http.createServer((request, response) => {++ const url = new URL(request.url, 'http://test')++ requests.push(url.pathname)++ if (url.pathname === '/frame') {++ const preview = payload(Number(url.searchParams.get('rev')))++ // Each response is a new wrapper with its own token, as the route issues.++ const token = crypto.randomUUID()++ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-security-policy': designFrameCsp(`${origin}/api/artifact-image`) })++ return response.end(designFrameHtml(prepareDesignArtifactHtml(preview.renderHtml, DESIGN_ARTIFACT_EMBEDDED_CSP, token), token, [], preview, { relay: DESIGN_CAPTURE_RELAY, script: designCaptureScript }))++ }++ if (url.pathname === '/payload') {++ return response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'private, no-store' }).end(JSON.stringify(payload(Number(url.searchParams.get('rev')))))++ }++ if (url.pathname === '/hold') {++ holds.push(response)++ setTimeout(() => { if (!response.writableEnded) response.writeHead(404).end() }, 60_000).unref()++ return++ }++ if (url.pathname === '/done') {++ for (const held of holds.splice(0)) if (!held.writableEnded) held.writeHead(404).end()++ return response.writeHead(204).end()++ }++ if (url.pathname === '/') return response.writeHead(200, { 'content-type': 'text/html' }).end(harness)++ response.writeHead(404).end()++ })++ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))++ origin = `http://127.0.0.1:${server.address().port}`++ const dir = await mkdtemp(join(tmpdir(), 'fx0-design-live-'))++ try {++ const { stdout } = await promisify(execFile)(CHROME, [++ '--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check', '--window-size=390,844',++ `--user-data-dir=${join(dir, 'profile')}`, '--dump-dom', `${origin}/`,++ ], { timeout: 90_000, killSignal: 'SIGKILL', maxBuffer: 16 * 1024 * 1024 })++ const out = JSON.parse(stdout.match(/<pre id="out">([^<]*)<\/pre>/)[1])++ assert.equal(out.error, undefined, out.error)++ assert.equal(out.done, true, 'the flow finished')++ assert.equal(out.compatible.status, 'applied', 'a compatible update applies in place')++ assert.equal(out.restored, true, 'a stalled design is restored under a new document token')++ assert.equal(out.refused.status, 'reload', 'an incompatible update is refused, not applied')++ assert.equal(out.reopened, true, 'the reloaded frame has a new document token')++ const near = (rgb, target) => rgb.every((value, i) => Math.abs(value - target[i]) < 24)++ const expected = { pink: [255, 0, 102], blue: [0, 102, 255], restored: [0, 102, 255], reloaded: [0, 204, 102] }++ for (const [name, color] of Object.entries(expected)) {++ const shot = out.shots[name]++ assert.equal(shot.error, null, `${name}: no capture failure`)++ assert.deepEqual(shot.images.map(({ type, width, height }) => [type, width, height]), [['image/webp', 1280, 800]], `${name}: one WebP viewport`)++ assert.ok(near(shot.images[0].color, color), `${name} shows ${color}, got ${shot.images[0].color}`)++ }++ assert.ok(!requests.includes('/leak.png'), 'the url() the design names never reached the network')++ } finally {++ server.closeAllConnections()++ server.close()++ await rm(dir, { recursive: true, force: true })++ }++})++// The draft has no network, so a remote image must show the soft placeholder, never// the browser's broken-image icon. The draft cleaner runs in Chrome, types stripped.test('in Chrome, a draft shows a placeholder for remote images instead of a broken icon', async () => {diff --cc tests/preview-update.browser.mjsindex 0000000,1a89f2a..7ed93c9mode 000000,100644..100644--- a/tests/preview-update.browser.mjs+++ b/tests/preview-update.browser.mjs@@@ -1,0 -1,1026 +1,1076 @@@+ import assert from 'node:assert/strict'+ import test from 'node:test'+ import { execFile, spawn } from 'node:child_process'+ import { existsSync } from 'node:fs'+ import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'+ import { registerHooks } from 'node:module'+ import { fileURLToPath, pathToFileURL } from 'node:url'+ import { promisify } from 'node:util'+ import http from 'node:http'+ import { tmpdir } from 'node:os'+ import { join } from 'node:path'+ import { createHash, randomBytes } from 'node:crypto'+ import { setTimeout as sleep } from 'node:timers/promises'+ import { markRemoteImages } from '../lib/remote-image.ts'++import { CAPTURE_TIMING_HEADER } from '../lib/capture-protocol.ts'++import { DESIGN_CAPTURE_RELAY, designCaptureScript } from '../lib/design-capture.ts'+ import { BLANK_IMAGE, DESIGN_ARTIFACT_EMBEDDED_CSP, MAX_EMBEDDED_IMAGE_BYTES, designFrameCsp, designFrameHtml, prepareDesignArtifactHtml, validateDesignArtifactHtml } from '../lib/design-artifact.ts'++ // Opt-in, like design-artifact.browser.mjs. Node 24 supplies WebSocket and TS stripping.+ // One Chrome and sequential cases keep this suite from spawning a browser per assertion.+ const CHROME = process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'+ const PIXEL = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')+ const SESSION = 'preview-browser-session'+ const TOKEN = 'preview-browser-ready'++ function design({ color = 'rgb(10, 20, 30)', title = 'Original title', padding = 4, image = '', photo = false, program = 'original', structure = '', beforeLoad = '', sheetId = true } = {}) {+ return `<!doctype html><html><head><title>Interactive presentation</title>+ <style${sheetId ? ' id="theme"' : ''}>body{margin:0;min-height:2600px}#title{color:${color}}#swatch{width:80px;height:80px;background-image:${image ? `url(https://fixture.invalid/${image})` : 'none'}}</style>+ </head><body class="slide-1"><h1 id="title">${title}</h1>+ <p id="inline" style="padding:${padding}px">Inline target</p><p id="runtime-label">Authored label</p>+ <input id="input" value="authored"><button id="next">Next slide</button><div id="swatch"></div>+ ${photo ? '<img id="photo" alt="Local fixture" src="https://fixture.invalid/pixel.png">' : ''}${structure}+ <script>+ const instance = crypto.randomUUID(), program = ${JSON.stringify(program)}+ const find = id => id === 'theme' ? document.querySelector('style') : document.getElementById(id)+ const refs = Object.fromEntries(['title', 'inline', 'input', 'next', 'theme'].map(id => [id, find(id)]))+ let clicks = 0+ refs.next.addEventListener('click', () => { clicks++; document.body.className = 'slide-' + (4 + clicks) })+ document.body.className = 'slide-4'+ refs.input.value = 'typed at runtime'+ document.getElementById('runtime-label').textContent = 'Runtime label'+ const generated = document.createElement('p'); generated.id = 'generated'; generated.textContent = 'Generated at runtime'; document.body.append(generated)+ ${beforeLoad}+ const send = data => top.postMessage({ fixture: 'preview-update', instance, program, ...data }, '*')+ send({ kind: 'boot' })+ addEventListener('error', event => send({ kind: 'error', error: event.message }))+ addEventListener('unhandledrejection', event => send({ kind: 'error', error: String(event.reason) }))+ const report = () => {+ const title = document.getElementById('title'), input = document.getElementById('input'), sheet = find('theme').sheet+ send({ kind: 'state', title: title.textContent, color: getComputedStyle(title).color,+ padding: getComputedStyle(document.getElementById('inline')).paddingTop, background: getComputedStyle(document.getElementById('swatch')).backgroundImage,+ className: document.body.className, input: input.value, focused: document.activeElement === input,+ selection: [input.selectionStart, input.selectionEnd], scroll: Math.round(scrollY), clicks,+ sameNodes: Object.entries(refs).every(([id, node]) => find(id) === node),+ runtimeLabel: document.getElementById('runtime-label').textContent, generated: !!document.getElementById('generated'),+ cssText: find('theme').textContent, rules: sheet.cssRules.length, disabled: sheet.disabled,+ photo: document.getElementById('photo')?.getAttribute('src') ?? null,+ photoDecoded: !!document.getElementById('photo')?.naturalWidth, added: !!document.getElementById('added'),+ csp: document.querySelector('meta[http-equiv="Content-Security-Policy"]')?.content })+ }+ addEventListener('load', report, { once: true })+ setInterval(report, 60)+ </script></body></html>`+ }++ function payload(revision, html, imageName) {+ const validated = validateDesignArtifactHtml(` \n${html}\n `, { remoteImages: true })+ assert.equal(validated.ok, true, validated.error)+ const marked = markRemoteImages(validated.html, randomBytes(16).toString('hex'), { remote: true })+ return {+ protocol: 1, sessionId: SESSION, revision, sourceHtml: validated.html, renderHtml: marked.html,+ images: marked.images.map(({ marker, url }) => ({ marker, src: `/api/artifact-image?name=${encodeURIComponent(imageName ?? new URL(url).pathname.slice(1))}&nonce=${randomBytes(8).toString('hex')}` })),+ }+ }++ // Observe real window messages without intercepting any production listener or send.+ const OBSERVER = `+ window.observed = { paints: [], results: [], boots: [], reports: [], errors: [] }+ addEventListener('message', event => {+ const frames = [...document.querySelectorAll('#active, #preview-pane iframe')], data = event.data+ if (!data || typeof data !== 'object') return+ const wrapper = frames.find(frame => event.source === frame.contentWindow)+ if (wrapper && event.origin === location.origin) {+ const entry = { ...data, mountUrl: wrapper.getAttribute('src') }+ if (data.type === 'fx0-artifact-painted') observed.paints.push(entry)+ if (data.type === 'fx0-preview-result') observed.results.push(entry)+ }+ const frame = frames.find(frame => event.source === frame.contentWindow.frames[0])+ if (frame && data.fixture === 'preview-update') {+ const entry = { ...data, mountUrl: frame.getAttribute('src') }+ if (data.kind === 'boot') observed.boots.push(entry)+ if (data.kind === 'state') { observed.reports.push(entry); if (observed.reports.length > 30) observed.reports.shift() }+ if (data.kind === 'error') observed.errors.push(data.error)+ }+ })`++ const PARENT = `<!doctype html><html><head><title>Preview update browser test</title>+ <style>html,body{margin:0}iframe{width:1000px;height:720px;border:0}</style></head><body><script>${OBSERVER}+ window.mount = url => {+ document.getElementById('active')?.remove()+ observed.reports = []+ const frame = document.createElement('iframe'); frame.id = 'active'; frame.src = url; document.body.append(frame)+ }+ </script></body></html>`++ async function buildPaneFixture(directory) {+ const output = await realpath(directory), root = fileURLToPath(new URL('../', import.meta.url))+ // Same narrow compile as html-ui.test.mjs, using this test's Node 24 executable.+ await promisify(execFile)(process.execPath, [join(root, 'node_modules/typescript/bin/tsc'),+ '--ignoreConfig', '--outDir', join(output, 'compiled'), '--strict', '--types', 'node',+ '--jsx', 'react-jsx', '--target', 'esnext', '--module', 'esnext',+ '--moduleResolution', 'bundler', '--skipLibCheck', '--esModuleInterop', 'components/preview-pane.tsx',+ ], { cwd: root, maxBuffer: 4 * 1024 * 1024 })+ await writeFile(join(output, 'package.json'), '{"type":"module"}')+ // These controls change only the real component's props. No replacement hooks,+ // updater, transport or slot coordinator is bundled into the fixture.+ await writeFile(join(output, 'pane-fixture.js'), `+ import { createElement, useEffect, useState } from 'react'+ import PreviewPane from './compiled/components/preview-pane.js'+ export function Fixture() {+ const [revision, setRevision] = useState(101), [viewing, setViewing] = useState(null)+ const [sessionId, setSession] = useState(${JSON.stringify(SESSION)}), [draft, setDraft] = useState(null)- const [accessAllowed, setAccessAllowed] = useState(true)++ const [accessAllowed, setAccessAllowed] = useState(true), [capture, setCapture] = useState(null)+ useEffect(() => {- Object.assign(window, { setRevision, setViewing, setSession, setDraft, setAccessAllowed, fixtureReady: true })++ window.captureResults = []++ Object.assign(window, { setRevision, setViewing, setSession, setDraft, setAccessAllowed, setCapture, fixtureReady: true })+ const revoke = () => { setAccessAllowed(false); setRevision(0) }+ window.addEventListener('fx0:auth-required', revoke)+ return () => window.removeEventListener('fx0:auth-required', revoke)+ }, [])- return createElement(PreviewPane, { source: { kind: 'design', sessionId, revision }, viewing, draft, accessAllowed, intro: false, onClose: () => setRevision(0) })++ return createElement(PreviewPane, { source: { kind: 'design', sessionId, revision }, viewing, draft, accessAllowed, intro: false, onClose: () => setRevision(0),++ capture, onCaptureDone: (cid, answered) => { window.captureResults.push({ cid, answered }); setCapture(current => current?.cid === cid ? null : current) },++ })+ }`)+ await writeFile(join(output, 'pane-entry.js'), `+ import { createElement } from 'react'+ import { hydrateRoot } from 'react-dom/client'+ import { Fixture } from './pane-fixture.js'+ hydrateRoot(document.getElementById('app'), createElement(Fixture), { onRecoverableError: error => observed.errors.push(error.message) })+ `)+ const { default: bundledWebpack } = await import('../node_modules/next/dist/compiled/webpack/webpack.js')+ const compiler = bundledWebpack.webpack({+ // Next's packaged webpack references a terser entry absent in this install.+ // Production React is still selected; minification is not under test here.+ mode: 'production', optimization: { minimize: false }, target: 'web', entry: join(output, 'pane-entry.js'),+ output: { path: join(output, 'browser'), filename: 'bundle.js' },+ module: { rules: [{ test: /\.js$/, resolve: { fullySpecified: false } }] },+ resolve: { modules: [join(root, 'node_modules')], extensions: ['.js'], extensionAlias: { '.ts': ['.js'] } },+ })+ try {+ const stats = await promisify(compiler.run.bind(compiler))()+ assert.equal(stats.hasErrors(), false, stats.toString({ all: false, errors: true }))+ } finally { await promisify(compiler.close.bind(compiler))() }++ const outputUrl = pathToFileURL(`${output}/`).href, projectUrl = new URL('../package.json', import.meta.url).href+ const hooks = registerHooks({ resolve(specifier, context, nextResolve) {+ if (!context.parentURL?.startsWith(outputUrl)) return nextResolve(specifier, context)+ if (specifier.startsWith('.')) return nextResolve(/\.js$/.test(specifier) ? specifier : `${specifier.replace(/\.ts$/, '')}.js`, context)+ return nextResolve(specifier, { ...context, parentURL: projectUrl })+ } })+ let markup+ try {+ const [{ Fixture }, { createElement }, { renderToString }] = await Promise.all([+ import(pathToFileURL(join(output, 'pane-fixture.js')).href), import('react'), import('react-dom/server'),+ ])+ markup = renderToString(createElement(Fixture))+ } finally { hooks.deregister() }+ return {+ bundle: await readFile(join(output, 'browser/bundle.js')),+ html: `<!doctype html><html><head><meta charset="utf-8"><title>Real PreviewPane</title><style>+ html,body,#app{margin:0;height:100%}#preview-pane{height:100%;display:flex;flex-direction:column}+ #preview-pane>div:last-of-type{position:relative;flex:1;min-height:720px}+ #preview-pane iframe{position:absolute;inset:0;width:1000px;height:720px;border:0}+ #preview-pane iframe[aria-hidden=true]{z-index:0;pointer-events:none}#preview-pane iframe:not([aria-hidden=true]){z-index:1}+ </style></head><body><script>${OBSERVER}</script><div id="app">${markup}</div><script defer src="/bundle.js"></script></body></html>`,+ }+ }++ async function until(read, label, milliseconds = 8000) {+ const deadline = Date.now() + milliseconds+ let last+ do {+ last = await read()+ if (last) return last+ await sleep(40)+ } while (Date.now() < deadline)+ throw new Error(`Timed out: ${label}; last observation: ${JSON.stringify(last)}`)+ }++ // Only the CDP primitives this file needs; no automation package or copied updater.+ async function connectCdp(url, errors) {+ const socket = new WebSocket(url), pending = new Map(), contexts = new Map()+ let sequence = 0, iframeSession+ const closed = new Promise(resolve => socket.addEventListener('close', resolve, { once: true }))+ socket.addEventListener('message', ({ data }) => {+ const message = JSON.parse(data)+ if (message.id) {+ const request = pending.get(message.id)+ if (!request) return+ pending.delete(message.id); clearTimeout(request.timer)+ if (message.error) request.reject(new Error(JSON.stringify(message.error)))+ else request.resolve(message.result)+ }+ if (message.method === 'Target.attachedToTarget' && message.params.targetInfo.type === 'iframe') {+ iframeSession = message.params.sessionId+ call('Runtime.enable', {}, iframeSession).catch(error => errors.push(error.message))+ }+ if (message.method === 'Target.detachedFromTarget' && iframeSession === message.params.sessionId) iframeSession = undefined+ if (message.method === 'Runtime.executionContextCreated') {+ const context = message.params.context+ if (context.auxData?.isDefault) contexts.set(context.auxData.frameId, { id: context.id, sessionId: message.sessionId })+ }+ if (message.method === 'Runtime.executionContextDestroyed' || message.method === 'Runtime.executionContextsCleared' || message.method === 'Target.detachedFromTarget') {+ for (const [frame, context] of contexts) {+ if (context.sessionId === (message.params?.sessionId ?? message.sessionId) &&+ (message.method !== 'Runtime.executionContextDestroyed' || context.id === message.params.executionContextId)) contexts.delete(frame)+ }+ }+ if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails)+ if (message.method === 'Runtime.consoleAPICalled' && message.params.type === 'error') errors.push(message.params.args)+ })+ socket.addEventListener('close', () => {+ for (const request of pending.values()) { clearTimeout(request.timer); request.reject(new Error('Chrome CDP closed')) }+ pending.clear()+ })+ await new Promise((resolve, reject) => {+ const timer = setTimeout(() => { socket.close(); reject(new Error('Chrome CDP connection timeout')) }, 8000)+ socket.addEventListener('open', () => { clearTimeout(timer); resolve() }, { once: true })+ socket.addEventListener('error', () => { clearTimeout(timer); socket.close(); reject(new Error('Chrome CDP connection failed')) }, { once: true })+ })+ const call = (method, params = {}, sessionId) => new Promise((resolve, reject) => {+ const id = ++sequence+ const timer = setTimeout(() => { pending.delete(id); reject(new Error(`CDP timeout: ${method}`)) }, 12_000)+ pending.set(id, { resolve, reject, timer }); socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }))+ })+ const evaluate = async (expression, depth = 0) => {+ let context+ if (depth === 2 && iframeSession) {+ context = await until(() => [...contexts.values()].find(c => c.sessionId === iframeSession), 'opaque iframe execution context')+ } else if (depth) {+ let { frameTree } = await call('Page.getFrameTree')+ for (let index = 0; index < depth; index++) frameTree = frameTree?.childFrames?.[0]+ assert.ok(frameTree, `Missing frame at depth ${depth}`)+ context = contexts.get(frameTree.frame.id)+ assert.ok(context, `Missing default execution context at depth ${depth}`)+ }+ const result = await call('Runtime.evaluate', { expression, ...(context ? { contextId: context.id } : {}), returnByValue: true, awaitPromise: true }, context?.sessionId)+ if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails))+ return result.result.value+ }+ await call('Runtime.enable'); await call('Page.enable')+ await call('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: false, flatten: true })+ return { call, evaluate, close: async () => { socket.close(); await Promise.race([closed, sleep(1000, undefined, { ref: false })]) } }+ }++ test('in Chrome, the production preview wrapper and React PreviewPane preserve state, reload safely and recover', { timeout: 180_000 }, async t => {+ assert.ok(existsSync(CHROME), `Chrome not found at ${CHROME}; set CHROME_PATH`)+ const dir = await mkdtemp(join(tmpdir(), 'fx0-preview-update-'))+ const frames = new Map(), hits = new Map(), held = [], errors = []+ // Chrome decodes the valid PNG prefix; trailing bytes exercise embedding size,+ // not expensive pixel allocation. Three occurrences stay below the real budget.+ const largeImage = Buffer.alloc(Math.floor(1.1 * 1024 * 1024), 0x41)+ PIXEL.copy(largeImage)- const paneArtifacts = new Map(), paneLatest = new Map(), paneModes = new Map(), paneRequests = [], paneHeld = [], paneHtmlHeld = [], bundleHeld = []++ const paneArtifacts = new Map(), paneLatest = new Map(), paneModes = new Map(), paneRequests = [], paneHeld = [], paneHtmlHeld = [], bundleHeld = [], paneCaptures = []+ let paneFixture, holdBundle = true+ let origin, chrome, cdp, chromeError = '', frameNumber = 0, requestNumber = 0, offRouteHits = 0+ const sendFrame = (response, preview) => {+ const prepared = prepareDesignArtifactHtml(preview.renderHtml, DESIGN_ARTIFACT_EMBEDDED_CSP, TOKEN)+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-security-policy': designFrameCsp(`${origin}/api/artifact-image`) })- response.end(designFrameHtml(prepared, TOKEN, preview.images, preview))++ response.end(designFrameHtml(prepared, TOKEN, preview.images, preview, { relay: DESIGN_CAPTURE_RELAY, script: designCaptureScript }))+ }+ const server = http.createServer((request, response) => {+ const url = new URL(request.url, 'http://fixture')+ if (url.pathname === '/pane' && paneFixture) return response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(paneFixture.html)+ if (url.pathname === '/bundle.js' && paneFixture) {+ if (holdBundle) return void bundleHeld.push(response)+ return response.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }).end(paneFixture.bundle)+ }++ if (url.pathname === '/api/capture') {++ const chunks = []++ request.on('data', chunk => chunks.push(chunk))++ request.on('end', async () => {++ const form = request.headers['content-type']?.startsWith('multipart/form-data')++ ? await new Response(Buffer.concat(chunks), { headers: { 'content-type': request.headers['content-type'] } }).formData() : null++ paneCaptures.push({ cid: url.searchParams.get('cid'), failed: url.searchParams.get('failed'),++ images: form?.getAll('image').map(image => ({ type: image.type, size: image.size })) ?? [],++ timing: JSON.parse(request.headers[CAPTURE_TIMING_HEADER] ?? '{}') })++ response.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}')++ })++ return++ }+ if (url.pathname === '/api/artifact-frame') {+ const session = url.searchParams.get('session'), wanted = Number(url.searchParams.get('revision') ?? url.searchParams.get('v'))+ const revision = url.searchParams.has('revision') ? wanted : paneLatest.get(session)+ const preview = paneArtifacts.get(`${session}:${revision}`), json = url.searchParams.get('format') === 'json'+ paneRequests.push({ session, wanted, revision, json })+ if (!preview) return response.writeHead(404, { 'content-type': 'application/json' }).end('{"error":"No local design"}')+ const mode = paneModes.get(`${session}:${wanted}`)+ if (!json) {+ if (mode === 'hold-html') return void paneHtmlHeld.push({ response, preview })+ return sendFrame(response, preview)+ }+ if (mode === 'error') return response.writeHead(503, { 'content-type': 'application/json' }).end('{"error":"Local failure"}')+ // Only the external snapshot/data source is simulated. JSON never mounts or+ // executes a candidate; the real React effect decides what to do with it.+ const text = JSON.stringify(preview)+ response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'private, no-store' })+ if (mode === 'hang') {+ response.flushHeaders(); response.write(text.slice(0, 32))+ const entry = { response, rest: text.slice(32), closed: false }; paneHeld.push(entry)+ response.on('close', () => { entry.closed = !response.writableEnded })+ return+ }+ return response.end(text)+ }+ if (url.pathname === '/api/artifact-image') {+ const name = url.searchParams.get('name')+ hits.set(name, (hits.get(name) ?? 0) + 1)+ if (name === 'missing.png') return response.writeHead(404).end()+ response.writeHead(200, { 'content-type': 'image/png', 'cache-control': 'no-store' })+ if (name?.startsWith('large-')) return response.end(largeImage)+ if (name === 'hang.png') {+ response.flushHeaders(); response.write(PIXEL.subarray(0, 8))+ const entry = { response, closed: false }; held.push(entry)+ response.on('close', () => { entry.closed = true })+ return+ }+ return response.end(PIXEL)+ }+ if (frames.has(url.pathname)) return sendFrame(response, frames.get(url.pathname))+ if (url.pathname === '/') return response.writeHead(200, { 'content-type': 'text/html' }).end(PARENT)+ if (url.pathname === '/not-an-image') { offRouteHits++; return response.end('must not be fetched') }+ response.writeHead(204).end()+ })+ try {+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })+ origin = `http://127.0.0.1:${server.address().port}`+ chrome = spawn(CHROME, [+ '--headless=new', '--disable-gpu', '--no-first-run', '--no-default-browser-check', '--no-proxy-server',+ '--disable-background-networking', '--disable-component-update', '--disable-sync', '--disable-default-apps',+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows',+ '--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1',+ '--remote-debugging-address=127.0.0.1', '--remote-debugging-port=0', `--user-data-dir=${join(dir, 'profile')}`, 'about:blank',+ ], { stdio: ['ignore', 'ignore', 'pipe'] })+ let spawnError+ chrome.on('error', error => { spawnError = error })+ chrome.stderr.on('data', data => { chromeError = (chromeError + data).slice(-16_384) })+ const port = await until(async () => {+ if (spawnError) throw spawnError+ assert.equal(chrome.exitCode, null, chromeError)+ try { return (await readFile(join(dir, 'profile', 'DevToolsActivePort'), 'utf8')).split('\n')[0] }+ catch (error) { if (error.code !== 'ENOENT') throw error }+ }, 'Chrome debugging port')+ const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(8000) })).json()+ cdp = await connectCdp(targets.find(target => target.type === 'page').webSocketDebuggerUrl, errors)+ await cdp.call('Page.bringToFront')+ await cdp.call('Emulation.setFocusEmulationEnabled', { enabled: true })+ await cdp.call('Page.navigate', { url: origin })+ await until(() => cdp.evaluate('typeof mount === "function"'), 'fixture parent')+ const evaluate = cdp.evaluate+ const observed = () => evaluate('observed')+ const state = () => evaluate('observed.reports.at(-1) ?? null')+ const waitState = predicate => until(async () => { const current = await state(); return current && predicate(current) && current }, 'design state report')+ const post = message => evaluate(`document.getElementById('active').contentWindow.postMessage(${JSON.stringify(message)}, location.origin)`)+ const interact = () => evaluate("{ const input = document.getElementById('input'); input.focus({ preventScroll: true }); input.setSelectionRange(2, 7); scrollTo(0, 900) }", 2)+ const mounted = async preview => {+ const path = `/frame-${++frameNumber}`; frames.set(path, preview)+ const count = (await observed()).paints.length+ await evaluate(`mount(${JSON.stringify(path)})`)+ await waitState(s => s.sameNodes && s.input === 'typed at runtime')+ await interact()+ await waitState(s => s.scroll === 900 && s.focused)+ assert.equal(await evaluate("document.querySelector('iframe').contentDocument.querySelector('iframe').contentDocument === null"), true, 'design keeps its opaque sandbox')+ return until(async () => (await observed()).paints.slice(count).find(p => p.protocol === 1 && p.sessionId === SESSION && p.revision === preview.revision && typeof p.documentId === 'string' && p.updateReady === true), `production paint + updater ready for revision ${preview.revision}`)+ }+ const start = async (paint, baseRevision, candidate) => {+ const requestId = `browser-request-${++requestNumber}`+ await post({ type: 'fx0-preview-update', protocol: 1, requestId, documentId: paint.documentId, baseRevision, payload: candidate })+ return requestId+ }+ const terminal = (requestId, milliseconds = 8000) => until(async () => (await observed()).results.find(result => result.requestId === requestId), `terminal result for ${requestId}`, milliseconds)+ const update = async (paint, baseRevision, candidate, expected = 'applied') => {+ const requestId = await start(paint, baseRevision, candidate), result = await terminal(requestId)+ assert.deepEqual({ type: result.type, protocol: result.protocol, requestId: result.requestId, documentId: result.documentId, sessionId: result.sessionId, revision: result.revision, status: result.status }, {+ type: 'fx0-preview-result', protocol: 1, requestId, documentId: paint.documentId, sessionId: SESSION, revision: candidate.revision, status: expected,+ }, JSON.stringify(result))+ if (expected !== 'applied') assert.equal(typeof result.reason, 'string')+ return result+ }+ const preserved = (before, after) => {+ for (const key of ['instance', 'program', 'input', 'focused', 'selection', 'scroll', 'className', 'clicks', 'runtimeLabel', 'generated', 'sameNodes']) assert.deepEqual(after[key], before[key], key)+ assert.equal(after.sameNodes, true)+ }+ const noErrors = async () => { assert.deepEqual(errors, []); assert.deepEqual((await observed()).errors, []) }++ // Fail once, rather than running every case against a legacy three-argument wrapper.+ let paint = await mounted(payload(1, design({ photo: true })))++ await t.test('first patch uses the real initial baseline; CSS, inline style and text preserve interactive state', async () => {+ const before = await state(), boots = (await observed()).boots.length+ assert.equal(before.photo, `data:image/png;base64,${PIXEL.toString('base64')}`)+ assert.equal(before.photoDecoded, true)+ await update(paint, 1, payload(2, design({ photo: true, color: 'rgb(90, 80, 70)' })))+ preserved(before, await waitState(s => s.color === 'rgb(90, 80, 70)'))+ await update(paint, 2, payload(3, design({ photo: true, color: 'rgb(90, 80, 70)', title: 'Edited title', padding: 12 })))+ preserved(before, await waitState(s => s.title === 'Edited title' && s.padding === '12px'))+ // Fresh marker/descriptor nonces must not turn unchanged embedded images into a conflict.+ await update(paint, 3, payload(4, design({ photo: true, color: 'rgb(90, 80, 70)', title: 'Edited title', padding: 12 })))+ preserved(before, await state())+ await evaluate("document.getElementById('next').click()", 2)+ assert.equal((await waitState(s => s.clicks === 1)).className, 'slide-5', 'the original listener still fires exactly once')+ assert.equal((await observed()).boots.length, boots, 'no speculative candidate or script restart')+ await noErrors()+ })++ await t.test('script and structure edits request reload without executing a candidate; a real remount accepts its first patch', async () => {+ const boots = (await observed()).boots.length+ const candidate = payload(5, design({ photo: true, color: 'rgb(90, 80, 70)', title: 'Edited title', padding: 12, program: 'replacement' }))+ await update(paint, 4, candidate, 'reload')+ await sleep(150)+ assert.equal((await observed()).boots.length, boots)+ assert.equal((await state()).program, 'original')+ paint = await mounted(candidate)+ assert.equal((await state()).program, 'replacement')+ assert.equal((await observed()).boots.length, boots + 1)+ await update(paint, 5, payload(6, design({ photo: true, color: 'rgb(1, 2, 3)', title: 'After real reload', padding: 12, program: 'replacement' })))+ await waitState(s => s.title === 'After real reload' && s.color === 'rgb(1, 2, 3)')+ await update(paint, 6, payload(7, design({ photo: true, color: 'rgb(1, 2, 3)', title: 'After real reload', padding: 12, program: 'replacement', structure: '<aside id="added">New structure</aside>' })), 'reload')+ assert.equal((await state()).added, false)+ assert.equal((await observed()).boots.length, boots + 1)+ await noErrors()+ })++ await t.test('CSS updates preserve cached stylesheet references and unchanged neighboring rules, including id-less styles', async () => {+ for (const sheetId of [true, false]) {+ const options = { sheetId, beforeLoad: 'window.cachedSheet = refs.theme.sheet; window.cachedFirstRule = cachedSheet.cssRules[0]' }+ const current = await mounted(payload(200, design(options))), before = await state(), boots = (await observed()).boots.length+ await update(current, 200, payload(201, design({ ...options, color: 'rgb(90, 80, 70)' })))+ preserved(before, await waitState(s => s.color === 'rgb(90, 80, 70)'))+ assert.equal(await evaluate('cachedSheet === refs.theme.sheet', 2), true, 'authored code keeps its CSSStyleSheet reference')+ assert.equal(await evaluate('cachedFirstRule === cachedSheet.cssRules[0]', 2), true, 'an unchanged neighboring rule is not replaced')+ await update(current, 201, payload(202, design({ ...options, color: 'rgb(21, 32, 43)' })))+ preserved(before, await waitState(s => s.color === 'rgb(21, 32, 43)'))+ assert.equal(await evaluate('cachedSheet === refs.theme.sheet', 2), true, 'a second update keeps the same stylesheet')+ await evaluate('window.currentRules = [...cachedSheet.cssRules]', 2)+ const formatted = design({ ...options, color: 'rgb(21, 32, 43)' }).replace('body{margin:0;', '/* formatting only */body{margin:0;')+ await update(current, 202, payload(203, formatted))+ assert.equal(await evaluate('currentRules.every((rule, index) => cachedSheet.cssRules[index] === rule)', 2), true, 'canonical no-ops do not replace rule objects')+ await evaluate("cachedSheet.insertRule('#title { color: rgb(4, 5, 6) }', cachedSheet.cssRules.length)", 2)+ preserved(before, await waitState(s => s.color === 'rgb(4, 5, 6)'))+ const result = await update(current, 203, payload(204, design({ ...options, color: 'rgb(99, 88, 77)', title: 'Must not overwrite runtime CSS' })), 'reload')+ assert.match(result.reason, /stylesheet.*conflict/)+ assert.equal((await state()).title, before.title, 'a CSSOM conflict prevents unrelated text writes')+ assert.equal((await observed()).boots.length, boots)+ }+ await noErrors()+ })++ await t.test('disjoint CSS edits, insertions and deletions retain the untouched rule and its live declaration', async () => {+ for (const sheetId of [true, false]) {+ const options = { sheetId, beforeLoad: 'window.cachedSheet = refs.theme.sheet; window.cachedRule = [...cachedSheet.cssRules].find(rule => rule.selectorText === "#title"); refs.next.addEventListener("click", () => { cachedRule.style.opacity = "0.4" })' }+ const original = design(options)+ const changed = value => original.replace('min-height:2600px}', `min-height:2600px;background:rgb(${value},2,3)}`).replace('width:80px;', `width:${80 + value}px;`)+ const current = await mounted(payload(250, original)), before = await state(), boots = (await observed()).boots.length+ await update(current, 250, payload(251, changed(1)))+ assert.equal(await evaluate('[...cachedSheet.cssRules].includes(cachedRule)', 2), true, 'an untouched rule between two edited rules keeps its identity')+ await update(current, 251, payload(252, changed(2)))+ const inserted = changed(2).replace('#title{', '.unused-before{color:red}#title{').replace('#swatch{', '.unused-after{color:blue}#swatch{')+ await update(current, 252, payload(253, inserted))+ await update(current, 253, payload(254, changed(2)))+ assert.equal(await evaluate('cachedSheet === refs.theme.sheet && [...cachedSheet.cssRules].includes(cachedRule)', 2), true, 'separate insertions and deletions retain the cached sheet and rule')+ preserved(before, await state())+ await evaluate("document.getElementById('next').click()", 2)+ await waitState(s => s.clicks === 1)+ assert.equal(await evaluate('getComputedStyle(refs.title).opacity', 2), '0.4', 'the original handler still changes displayed CSS through its cached declaration')+ assert.equal((await observed()).boots.length, boots)+ }+ await noErrors()+ })++ await t.test('reordered or ambiguous shared rules reload before unrelated CSS, inline style or text is written', async () => {+ const original = design(), css = original.match(/<style[^>]*>([\s\S]*?)<\/style>/)[1], rules = css.match(/[^}]+}/g)+ for (const [previous, next] of [+ [rules, [rules[1], rules[0], rules[2]]],+ [[rules[0], rules[1], rules[1], rules[2]], [rules[0].replace('margin:0', 'margin:1px'), rules[1], rules[1], rules[2].replace('width:80px', 'width:81px')]],+ ]) {+ const current = await mounted(payload(260, original.replace(css, previous.join('')))), before = await state()+ const candidate = original.replace(css, next.join('')).replace('>Original title</h1>', '>Must not write</h1>').replace('padding:4px', 'padding:12px')+ await update(current, 260, payload(261, candidate), 'reload')+ const after = await state()+ assert.equal(after.cssText, before.cssText)+ assert.equal(after.title, before.title)+ assert.equal(after.padding, before.padding)+ preserved(before, after)+ }+ await noErrors()+ })++ await t.test('changed grouping rules reload without detaching cached unchanged descendants', async () => {+ const options = { beforeLoad: 'window.cachedGroup = refs.theme.sheet.cssRules[0]; window.cachedRule = cachedGroup.cssRules[1]; refs.next.addEventListener("click", () => { cachedRule.style.opacity = "0.4" })' }+ const original = design(options).replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/, '$1@media (min-width:0px){$2}$3')+ const current = await mounted(payload(270, original)), before = await state(), boots = (await observed()).boots.length+ const formatted = original.replace('body{margin:0;', '/* formatting only */body{margin:0;')+ await update(current, 270, payload(271, formatted))+ assert.equal(await evaluate('cachedGroup === refs.theme.sheet.cssRules[0] && cachedRule === cachedGroup.cssRules[1]', 2), true, 'grouped canonical no-ops keep the entire rule tree')+ const candidate = formatted.replace('min-height:2600px}', 'min-height:2600px;background:red}').replace('width:80px;', 'width:81px;').replace('>Original title</h1>', '>Must not write</h1>').replace('padding:4px', 'padding:12px')+ await update(current, 271, payload(272, candidate), 'reload')+ const after = await state()+ assert.equal(after.cssText, before.cssText)+ assert.equal(after.title, before.title)+ assert.equal(after.padding, before.padding)+ preserved(before, after)+ await evaluate("document.getElementById('next').click()", 2)+ await waitState(s => s.clicks === 1)+ assert.equal(await evaluate('getComputedStyle(refs.title).opacity', 2), '0.4', 'a rejected group replacement leaves the original cached declaration live')+ assert.equal((await observed()).boots.length, boots)+ await noErrors()+ })++ await t.test('id-less stylesheet lookup distinguishes logical duplicates from stale physical text after an update', async () => {+ for (const duplicate of ['logical', 'physical']) {+ const options = { sheetId: false }, original = design(options), changed = design({ ...options, color: 'rgb(90, 80, 70)' })+ const current = await mounted(payload(210, original)), before = await state()+ await update(current, 210, payload(211, changed))+ await waitState(s => s.color === 'rgb(90, 80, 70)')+ const css = (duplicate === 'logical' ? changed : original).match(/<style>([\s\S]*?)<\/style>/)[1]+ await evaluate(`{ const extra = document.createElement('style'); extra.textContent = ${JSON.stringify(css)}; document.head.append(extra) }`, 2)+ const result = await update(current, 211, payload(212, design({ ...options, color: 'rgb(21, 32, 43)', title: 'Unambiguous update' })), duplicate === 'logical' ? 'reload' : 'applied')+ if (duplicate === 'logical') {+ assert.match(result.reason, /target/)+ assert.equal((await state()).title, before.title)+ } else {+ preserved(before, await waitState(s => s.title === 'Unambiguous update'))+ assert.equal(await evaluate("[...refs.theme.sheet.cssRules].some(rule => rule.cssText.includes('rgb(21, 32, 43)'))", 2), true)+ }+ }+ await noErrors()+ })++ await t.test('CSS preflight rejects imports and invalid namespace splices before any stylesheet or text write', async () => {+ const cases = [+ { before: '#other { color: red }', after: '@import "data:text/css,body{}"; #other { color: red }' },+ { before: '@namespace test "urn:old"; test|p { color: red }', after: '@namespace test "urn:new"; test|p { color: red }' },+ ]+ for (const { before: first, after: next } of cases) {+ const original = design({ structure: `<style id="secondary">${first}</style>` })+ const current = await mounted(payload(220, original)), before = await state()+ const candidate = design({ color: 'rgb(99, 88, 77)', title: 'Must not write', structure: `<style id="secondary">${next}</style>` })+ await update(current, 220, payload(221, candidate), 'reload')+ const after = await state()+ assert.equal(after.title, before.title)+ assert.equal(after.color, before.color)+ assert.equal(after.cssText, before.cssText)+ preserved(before, after)+ }+ await noErrors()+ })++ await t.test('runtime stylesheet changes before load and after a hot update remain conflicts', async () => {+ for (const mutation of ["refs.theme.sheet.insertRule('body { outline: 3px solid red }', refs.theme.sheet.cssRules.length)", "refs.theme.textContent += '\\n'"]) {+ const options = { beforeLoad: mutation }, current = await mounted(payload(230, design(options))), before = await state()+ await update(current, 230, payload(231, design({ ...options, color: 'rgb(99, 88, 77)', title: 'Must not write' })), 'reload')+ assert.equal((await state()).title, before.title)+ assert.equal((await state()).cssText, before.cssText)+ }+ const current = await mounted(payload(240, design()))+ await update(current, 240, payload(241, design({ color: 'rgb(90, 80, 70)' })))+ const before = await waitState(s => s.color === 'rgb(90, 80, 70)')+ await evaluate("refs.theme.textContent += '\\n'", 2)+ await update(current, 241, payload(242, design({ color: 'rgb(99, 88, 77)', title: 'Must not write' })), 'reload')+ assert.equal((await state()).title, before.title)+ await noErrors()+ })++ await t.test('a real hot update retains a fully embedded render past 2 MiB within the image budget', async largeTest => {+ const names = ['large-a.png', 'large-b.png', 'large-c.png']+ const options = {+ structure: names.map((name, index) => `<img id="large-${index}" alt="Large local image ${index}" src="https://fixture.invalid/${name}">`).join(''),+ beforeLoad: 'for (const image of document.images) refs[image.id] = image',+ }+ const initial = payload(8, design(options))+ assert.equal(initial.images.length, 3)+ assert.ok(Buffer.byteLength(initial.sourceHtml) < 16 * 1024, 'canonical HTML stays small; the wrapper must embed the large render')+ assert.ok(Buffer.byteLength(initial.renderHtml) < 16 * 1024)+ const expectedBytes = names.length * largeImage.length+ assert.ok(expectedBytes > 3 * 1024 * 1024 && expectedBytes <= MAX_EMBEDDED_IMAGE_BYTES)+ const expectedHash = createHash('sha256').update(`data:image/png;base64,${largeImage.toString('base64')}`).digest('hex')+ // Return only lengths, digests and decode state. Even failures must never dump+ // the multi-megabyte data URLs into TAP or the continuously polled reports.+ const resources = () => evaluate(`(async () => ({+ documentUrl: document.URL,+ bodyBytes: new TextEncoder().encode(document.body.outerHTML).length,+ images: await Promise.all([...document.images].map(async image => {+ const source = image.getAttribute('src'), data = source.slice(source.indexOf(',') + 1)+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(source)))+ return { id: image.id, png: source.startsWith('data:image/png;base64,'),+ bytes: data.length * 3 / 4 - (data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0),+ hash: [...digest].map(byte => byte.toString(16).padStart(2, '0')).join(''),+ decoded: image.complete && image.naturalWidth === 1 && image.naturalHeight === 1 }+ }))+ }))()`, 2)+ const boots = (await observed()).boots.length+ const current = await mounted(initial)+ const before = await state(), embedded = await resources()+ assert.match(embedded.documentUrl, /^blob:/)+ assert.ok(embedded.bodyBytes > 2 * 1024 * 1024, 'the live embedded body, not just its bootstrap or raw source, exceeds 2 MiB')+ assert.deepEqual(embedded.images, names.map((_, index) => ({ id: `large-${index}`, png: true, bytes: largeImage.length, hash: expectedHash, decoded: true })))+ const embeddedBytes = embedded.images.reduce((total, image) => total + image.bytes, 0)+ assert.equal(embeddedBytes, expectedBytes)+ assert.ok(embeddedBytes <= MAX_EMBEDDED_IMAGE_BYTES)+ assert.equal((await observed()).boots.length, boots + 1)+ const mountUrl = await evaluate("document.getElementById('active').src")+ const candidate = payload(9, design({ ...options, color: 'rgb(71, 82, 93)', title: 'Large render hot update' }))+ assert.equal(candidate.images.length, 3)+ await update(current, 8, candidate)+ preserved(before, await waitState(s => s.title === 'Large render hot update' && s.color === 'rgb(71, 82, 93)'))+ const after = await resources()+ assert.equal(after.documentUrl, embedded.documentUrl)+ assert.ok(after.bodyBytes > 2 * 1024 * 1024)+ assert.deepEqual(after.images, embedded.images, 'all three decoded images and their complete embedded bytes are retained')+ assert.equal((await observed()).boots.length, boots + 1, 'the large candidate does not execute another iframe program')+ assert.equal(await evaluate("document.getElementById('active').src"), mountUrl)+ assert.equal(await evaluate("document.querySelectorAll('iframe').length"), 1)+ for (const name of names) assert.equal(hits.get(name), 2, `${name}: initial preparation and hot preparation both use the real image route`)+ largeTest.diagnostic(`embedded image bytes=${embeddedBytes}/${MAX_EMBEDDED_IMAGE_BYTES}; live body bytes=${after.bodyBytes}`)+ await noErrors()+ })++ await t.test('CSSOM rules and disabled sheets conflict before any patch writes', async () => {+ for (const mutation of ["sheet.insertRule('body { outline: 3px solid red }', sheet.cssRules.length)", 'sheet.disabled = true']) {+ const current = await mounted(payload(10, design()))+ await evaluate(`{ const sheet = document.getElementById('theme').sheet; ${mutation} }`, 2)+ const before = await waitState(s => mutation.includes('disabled') ? s.disabled : s.rules === 4)+ const result = await update(current, 10, payload(11, design({ color: 'rgb(99, 88, 77)', title: 'Must not write' })), 'reload')+ assert.match(result.reason, /stylesheet.*conflict/)+ await sleep(100)+ const after = await state()+ assert.equal(after.title, before.title, 'all operations are preflighted before writing')+ assert.equal(after.cssText, before.cssText)+ assert.equal(after.rules, before.rules)+ assert.equal(after.disabled, before.disabled, 'hot update must not re-enable a disabled sheet')+ preserved(before, after)+ }+ await noErrors()+ })++ await t.test('a target changed before load is not adopted as the authored baseline', async () => {+ const options = { beforeLoad: "refs.title.textContent = 'Changed before load'" }+ const current = await mounted(payload(20, design(options))), before = await state()+ assert.equal(before.title, 'Changed before load')+ const result = await update(current, 20, payload(21, design({ ...options, title: 'Candidate title', color: 'rgb(99, 88, 77)' })), 'reload')+ assert.match(result.reason, /text.*conflict/)+ await sleep(100)+ const after = await state()+ assert.equal(after.title, before.title)+ assert.equal(after.cssText, before.cssText, 'a later text conflict prevents even an earlier CSS operation')+ preserved(before, after)+ await noErrors()+ })++ await t.test('incidental embedded image differences require reload even when authored images are unchanged', async () => {+ const current = await mounted(payload(30, design({ photo: true }))), before = await state()+ await update(current, 30, payload(31, design({ photo: true, color: 'rgb(99, 88, 77)' }), 'missing.png'), 'reload')+ await sleep(100)+ const after = await state()+ assert.equal(after.photo, before.photo)+ assert.equal(after.cssText, before.cssText)+ preserved(before, after)+ await noErrors()+ })++ await t.test('an initially image-free wrapper embeds a later CSS image using only its permitted endpoint', async () => {+ const current = await mounted(payload(40, design())), before = await state(), requests = hits.get('pixel.png') ?? 0+ await update(current, 40, payload(41, design({ image: 'pixel.png' })))+ const after = await waitState(s => s.background.includes('data:image/png;base64,'))+ preserved(before, after)+ assert.equal(hits.get('pixel.png'), requests + 1)+ assert.match(after.csp, /connect-src 'none'/)+ assert.match(after.csp, /img-src data:/)+ assert.equal(await evaluate("fetch('/not-an-image').then(() => false, () => true)", 1), true, 'wrapper connect-src is path-only, not the whole origin')+ assert.equal(offRouteHits, 0)+ assert.equal(await evaluate(`fetch(${JSON.stringify(`${origin}/api/artifact-image?name=forbidden.png`)}).then(() => false, () => true)`, 2), true, 'opaque child cannot fetch even the allowed wrapper endpoint')+ assert.equal(hits.get('forbidden.png') ?? 0, 0)+ await noErrors()+ })++ await t.test('wrong source, protocol, session and document messages are ignored, not used to fetch or mutate', async () => {+ const current = await mounted(payload(50, design())), before = await state(), results = (await observed()).results.length+ const candidate = payload(51, design({ image: 'forbidden.png' }))+ const message = { type: 'fx0-preview-update', protocol: 1, requestId: 'untrusted-source', documentId: current.documentId, baseRevision: 50, payload: candidate }+ await evaluate(`postMessage(${JSON.stringify(message)}, location.origin)`, 1)+ await evaluate(`parent.postMessage(${JSON.stringify(message)}, '*')`, 2)+ await post({ ...message, requestId: 'wrong-protocol', protocol: 2 })+ await post({ ...message, requestId: 'wrong-document', documentId: 'not-the-live-document' })+ await post({ ...message, requestId: 'wrong-session', payload: { ...candidate, sessionId: 'other-session' } })+ await post({ type: 'fx0-preview-result', protocol: 1, requestId: 'forged-ack', documentId: current.documentId, sessionId: SESSION, revision: 51, status: 'applied' })+ await sleep(350)+ assert.equal((await observed()).results.length, results)+ assert.equal(hits.get('forbidden.png') ?? 0, 0)+ preserved(before, await state())+ await update(current, 50, payload(52, design({ title: 'Authenticated patch' })))+ await waitState(s => s.title === 'Authenticated patch')+ await noErrors()+ })++ await t.test('a hung image body hits the ten-second preparation deadline; late completion cannot replace the newest patch', async () => {+ const current = await mounted(payload(60, design())), before = await state(), count = held.length+ const began = Date.now(), requestId = await start(current, 60, payload(61, design({ image: 'hang.png' })))+ await until(() => held.length === count + 1, 'hung body request received')+ const result = await terminal(requestId, 15_000)+ assert.equal(result.status, 'applied', JSON.stringify(result))+ assert.equal(result.revision, 61); assert.equal(result.protocol, 1)+ assert.equal(result.documentId, current.documentId); assert.equal(result.sessionId, SESSION)+ assert.ok(Date.now() - began >= 9000, 'deadline includes reading the response body, not just headers')+ const placeholder = await waitState(s => s.background.includes(BLANK_IMAGE))+ preserved(before, placeholder)+ await until(() => held[count].closed, 'timed-out image reader/request aborted')+ await update(current, 61, payload(62, design({ image: 'pixel.png', title: 'Newest after timeout' })))+ const newest = await waitState(s => s.title === 'Newest after timeout' && s.background.includes('data:image/png;base64,'))+ held[count].response.end(PIXEL.subarray(8))+ await sleep(250)+ const after = await state()+ assert.equal(after.title, newest.title); assert.equal(after.background, newest.background)+ preserved(before, after)+ assert.equal((await observed()).results.filter(r => r.requestId === requestId).length, 1)+ await noErrors()+ })++ await t.test('canceling preparation returns one terminal error; a newer revision wins over late image data', async () => {+ const current = await mounted(payload(70, design())), before = await state(), count = held.length+ const requestId = await start(current, 70, payload(71, design({ image: 'hang.png', title: 'Canceled candidate' })))+ await until(() => held.length === count + 1, 'cancelable hung image request')+ await post({ type: 'fx0-preview-cancel', protocol: 1, requestId, documentId: current.documentId })+ const result = await terminal(requestId)+ assert.equal(result.status, 'error', JSON.stringify(result)); assert.equal(result.revision, 71)+ assert.equal(result.protocol, 1); assert.equal(result.documentId, current.documentId); assert.equal(result.sessionId, SESSION)+ assert.match(result.reason, /cancel/i)+ await until(() => held[count].closed, 'canceled image reader/request aborted')+ await update(current, 70, payload(72, design({ title: 'Newest after cancel', color: 'rgb(3, 4, 5)' })))+ await waitState(s => s.title === 'Newest after cancel')+ held[count].response.end(PIXEL.subarray(8))+ await sleep(250)+ const after = await state()+ assert.equal(after.title, 'Newest after cancel'); assert.equal(after.background, 'none')+ preserved(before, after)+ assert.equal((await observed()).results.filter(r => r.requestId === requestId).length, 1)+ await noErrors()+ })++ await t.test('watchdog recovery uses the last confirmed snapshot and new document identity, then accepts its first patch', async () => {+ const current = await mounted(payload(80, design()))+ await update(current, 80, payload(81, design({ title: 'Confirmed recovery snapshot', color: 'rgb(8, 9, 10)' })))+ await waitState(s => s.title === 'Confirmed recovery snapshot')+ const before = await observed(), oldInstance = (await state()).instance+ // Real self-navigation loses the bootstrap/heartbeat. The wrapper, not the test,+ // must recreate the confirmed document and install its fresh seed internally.+ await evaluate("location.replace('about:blank')", 2)+ const recovered = await until(async () => (await observed()).paints.slice(before.paints.length).find(p => p.protocol === 1 && p.sessionId === SESSION && p.revision === 81 && p.documentId !== current.documentId && p.updateReady), 'watchdog recovery paint')+ await interact()+ const restored = await waitState(s => s.instance !== oldInstance && s.title === 'Confirmed recovery snapshot' && s.scroll === 900)+ assert.equal(restored.color, 'rgb(8, 9, 10)')+ assert.equal((await observed()).boots.length, before.boots.length + 1)+ const results = (await observed()).results.length+ await start(current, 81, payload(82, design({ image: 'forbidden.png' })))+ await post({ type: 'fx0-preview-cancel', protocol: 1, requestId: 'stale-cancel', documentId: current.documentId })+ await sleep(250)+ assert.equal((await observed()).results.length, results, 'the same WindowProxy cannot revive old document IDs')+ assert.equal(hits.get('forbidden.png') ?? 0, 0)+ await update(recovered, 81, payload(83, design({ title: 'First patch after recovery', color: 'rgb(11, 12, 13)' })))+ const after = await waitState(s => s.title === 'First patch after recovery' && s.color === 'rgb(11, 12, 13)')+ preserved(restored, after)+ assert.equal((await observed()).boots.length, before.boots.length + 1)+ await noErrors()+ })+ await noErrors()++ await t.test('the real React PreviewPane hydrates, hot-updates, reloads, times out, retries and clears private scopes', async () => {+ paneFixture = await buildPaneFixture(dir)+ const publish = (revision, options = {}, sessionId = SESSION) => {+ const candidate = { ...payload(revision, design(options)), sessionId }+ paneArtifacts.set(`${sessionId}:${revision}`, candidate); paneLatest.set(sessionId, revision)+ }+ const frontSelector = '#preview-pane iframe[title="Design artifact preview"]:not([aria-hidden="true"])'+ const paneState = () => evaluate(`(() => { const frame = document.querySelector(${JSON.stringify(frontSelector)}); return frame ? observed.reports.filter(s => s.mountUrl === frame.getAttribute('src')).at(-1) ?? null : null })()`)+ const waitPane = predicate => until(async () => { const current = await paneState(); return current && predicate(current) && current }, 'visible React PreviewPane state')+ const applied = revision => until(async () => (await observed()).results.find(r => r.status === 'applied' && r.protocol === 1 && r.revision === revision), `React-coordinated applied revision ${revision}`)+ const painted = revision => until(async () => (await observed()).paints.find(p => p.protocol === 1 && p.revision === revision && p.updateReady), `React-coordinated painted revision ${revision}`)+ const iframeCount = () => evaluate("document.querySelectorAll('#preview-pane iframe').length")+ const status = () => evaluate("document.querySelector('#preview-pane [role=status]')?.textContent ?? ''")+ const htmlCount = () => paneRequests.filter(r => !r.json).length++ const askCapture = (cid, revision, sessionId = SESSION) => evaluate(`setCapture({ cid: ${JSON.stringify(cid)}, revision: ${revision}, sessionId: ${JSON.stringify(sessionId)}, receivedAt: Date.now() })`)++ const captureResult = cid => until(() => evaluate(`captureResults.find(result => result.cid === ${JSON.stringify(cid)})`), `capture result ${cid}`)+ try {+ publish(101)+ await cdp.call('Page.navigate', { url: `${origin}/pane` })+ await painted(101)+ await waitPane(s => s.title === 'Original title')+ const ssr = await observed(), initialHtmlCount = htmlCount()+ assert.equal(ssr.boots.length, 1)+ assert.equal(initialHtmlCount, 1)+ assert.equal(await evaluate('typeof setRevision'), 'undefined', 'SSR iframe paints before the hydration bundle is released')+ await evaluate(`void (window.initialPaneFrame = document.querySelector(${JSON.stringify(frontSelector)}))`)+ holdBundle = false+ for (const response of bundleHeld.splice(0)) response.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }).end(paneFixture.bundle)+ await until(() => evaluate('window.fixtureReady === true'), 'real React hydration effects')+ await until(async () => (await observed()).paints.length > ssr.paints.length, 'status handshake replays an already-painted SSR document')+ assert.equal(htmlCount(), initialHtmlCount, 'hydration adopts the SSR load instead of starting another document')+ assert.equal((await observed()).boots.length, 1)+ await interact()+ const before = await waitPane(s => s.scroll === 900 && s.focused)+ const initialSrc = await evaluate('initialPaneFrame.getAttribute("src")')+ const initialPaint = (await painted(101)).documentId++ // The server can already be ahead of the journal event. The next patch must+ // use that actual applied revision, not the event's requested revision.+ publish(103, { color: 'rgb(30, 40, 50)', title: 'Server already at 103' })+ await evaluate("setDraft('<!doctype html><html><head></head><body><p>Unpublished draft</p></body></html>'); setRevision(102)")+ assert.equal((await applied(103)).documentId, initialPaint)+ preserved(before, await waitPane(s => s.title === 'Server already at 103' && s.color === 'rgb(30, 40, 50)'))++ // Delay the real renderer, not its pixels: a publish in this window must wait++ // until the screenshot is fixed, rather than relabeling revision 104 as 103.++ await evaluate(`{++ const library = FastHtmlToImage++ FastHtmlToImage = { ...library, captureRegion: async (...args) => {++ window.capturePaused = true++ await new Promise(resolve => { window.releasePhoto = resolve })++ FastHtmlToImage = library++ return library.captureRegion(...args)++ } }++ }`, 2)++ await askCapture('applied-103', 103)++ await until(() => evaluate('window.capturePaused === true', 2), 'real screenshot paused before rendering')+ publish(104, { color: 'rgb(60, 70, 80)', title: 'Next patch after actual revision', padding: 12 })+ await evaluate('setRevision(104)')++ await sleep(150)++ assert.equal((await paneState()).title, 'Server already at 103', 'hot application waits for the in-flight photo')++ assert.equal(paneRequests.some(request => request.wanted === 104), false, 'the new revision remains queued during capture')++ await evaluate('releasePhoto()', 2)++ assert.equal((await captureResult('applied-103')).answered, true)++ const photo = paneCaptures.find(capture => capture.cid === 'applied-103')++ assert.equal(photo?.failed, null, 'the applied revision is capturable even while its mount URL and requested revision are older')++ assert.equal(photo?.timing.path, 'preview')++ assert.equal(photo?.images.length, 1)++ assert.ok(photo.images[0].type.startsWith('image/') && photo.images[0].size > 0, 'the real capture handler uploads image bytes')++ preserved(before, await paneState())+ assert.equal((await applied(104)).documentId, initialPaint)+ preserved(before, await waitPane(s => s.title === 'Next patch after actual revision' && s.padding === '12px' && s.color === 'rgb(60, 70, 80)'))+ assert.equal(await evaluate('initialPaneFrame === document.querySelector(' + JSON.stringify(frontSelector) + ')'), true)+ assert.equal(await evaluate('initialPaneFrame.getAttribute("src")'), initialSrc)+ assert.equal(htmlCount(), initialHtmlCount, 'compatible effects never navigate src or execute a candidate frame')+ assert.equal((await observed()).boots.length, 1)+ assert.equal(await iframeCount(), 1, 'a draft cannot cover the published interactive design')++ await askCapture('stale-mount-101', 101)++ assert.equal((await captureResult('stale-mount-101')).answered, false, 'the original mount URL cannot label the patched document as the old revision')++ assert.equal(paneCaptures.some(capture => capture.cid === 'stale-mount-101'), false)+ const requestsBeforeOldEvent = paneRequests.length+ await evaluate('setDraft(null); setRevision(103)')+ await sleep(150)+ assert.equal(paneRequests.length, requestsBeforeOldEvent, 'an old journal event does not roll the preview back')+ await evaluate("document.getElementById('next').click()", 2)+ assert.equal((await waitPane(s => s.clicks === 1)).className, 'slide-5')++ // An incompatible program is executed only by the real second-slot HTML+ // load, once. Then a compatible patch must use that new document's baseline.+ publish(105, { program: 'react replacement', title: 'Reloaded through React' })+ await evaluate('setRevision(105)')+ const reloadedPaint = await painted(105)+ await waitPane(s => s.program === 'react replacement' && s.title === 'Reloaded through React')+ await until(async () => await iframeCount() === 1, 'old double-buffer slot removed')+ assert.notEqual(reloadedPaint.documentId, initialPaint)+ assert.equal((await observed()).results.filter(r => r.revision === 105 && r.status === 'reload').length, 1)+ assert.equal(htmlCount(), initialHtmlCount + 1)+ assert.equal((await observed()).boots.length, 2, 'no speculative candidate execution or duplicate reload')+ assert.equal(await evaluate('initialPaneFrame.isConnected'), false)+ await evaluate(`void (window.reloadedPaneFrame = document.querySelector(${JSON.stringify(frontSelector)}))`)+ await interact()+ const reloaded = await waitPane(s => s.scroll === 900 && s.focused)+ publish(106, { program: 'react replacement', title: 'First patch after React reload', padding: 8 })+ await evaluate('setRevision(106)')+ assert.equal((await applied(106)).documentId, reloadedPaint.documentId)+ preserved(reloaded, await waitPane(s => s.title === 'First patch after React reload' && s.padding === '8px'))+ assert.equal((await observed()).boots.length, 2)++ const confirmed = await paneState(), htmlBeforeStall = htmlCount(), heldCount = paneHeld.length+ publish(107, { program: 'react replacement', title: 'Must not apply a partial JSON body' })+ paneModes.set(`${SESSION}:107`, 'hang')+ const began = Date.now()+ await evaluate('setRevision(107)')+ await until(() => paneHeld.length === heldCount + 1, 'React JSON acquisition reaches the stalled body')+ await until(async () => (await status()).includes('timed out'), 'React ten-second body deadline', 15_000)+ assert.ok(Date.now() - began >= 9000, 'acquisition deadline covers the body, not just response headers')+ await until(() => paneHeld[heldCount].closed, 'React aborts the stalled response reader')+ preserved(confirmed, await paneState())+ assert.equal((await paneState()).title, confirmed.title)+ assert.equal(htmlCount(), htmlBeforeStall, 'acquisition timeout retains the confirmed document without an automatic reload')+ assert.equal((await observed()).boots.length, 2)+ assert.equal(paneRequests.filter(r => r.wanted === 107).length, 1, 'no automatic request loop')+ publish(108, { program: 'react replacement', title: 'Retry gets the actual latest revision', padding: 10 })+ paneModes.delete(`${SESSION}:107`)+ await evaluate("[...document.querySelectorAll('#preview-pane button')].find(button => button.textContent === 'Retry preview').click()")+ assert.equal((await applied(108)).documentId, reloadedPaint.documentId)+ const newest = await waitPane(s => s.title === 'Retry gets the actual latest revision' && s.padding === '10px')+ assert.equal(await status(), '')+ assert.equal(await evaluate('reloadedPaneFrame === document.querySelector(' + JSON.stringify(frontSelector) + ')'), true)+ paneHeld[heldCount].response.end(paneHeld[heldCount].rest)+ await sleep(200)+ assert.equal((await paneState()).title, newest.title, 'late partial-body completion cannot roll back the retry')+ assert.equal((await observed()).results.some(r => r.revision === 107), false)++ // A real history/scope change must cancel acquisition. Returning to latest+ // is an explicit document load, not an attempt to patch the historical one.+ publish(110, { program: 'never execute canceled JSON', title: 'Canceled navigation candidate' })+ paneModes.set(`${SESSION}:110`, 'hang')+ const navigationHeld = paneHeld.length+ await evaluate('setRevision(110)')+ await until(() => paneHeld.length === navigationHeld + 1, 'navigation races a JSON acquisition')+ await evaluate('setViewing(101)')+ await painted(101)+ await waitPane(s => s.program === 'original' && s.title === 'Original title' && s.instance !== before.instance)+ await until(() => paneHeld[navigationHeld].closed, 'history navigation aborts the old acquisition')+ paneModes.delete(`${SESSION}:110`)+ await until(async () => await iframeCount() === 1, 'history owns one confirmed slot')+ assert.equal(await evaluate(`new URL(document.querySelector(${JSON.stringify(frontSelector)}).src).searchParams.get('revision')`), '101')+ assert.ok(paneRequests.some(r => !r.json && r.wanted === 101 && r.revision === 101))+ publish(111, { program: 'latest after history', title: 'Returned to latest' })+ await evaluate('setViewing(null)')+ await painted(111)+ await waitPane(s => s.program === 'latest after history' && s.title === 'Returned to latest')+ paneHeld[navigationHeld].response.end(paneHeld[navigationHeld].rest)+ await sleep(200)+ assert.equal((await observed()).boots.some(b => b.program === 'never execute canceled JSON'), false)+ assert.equal((await paneState()).title, 'Returned to latest')++ const otherSession = 'other-preview-browser-session'+ publish(1, { program: 'other private session', title: 'Other private design' }, otherSession)+ await evaluate(`setSession(${JSON.stringify(otherSession)}); setRevision(1)`)+ await waitPane(s => s.program === 'other private session' && s.title === 'Other private design')+ await until(async () => await iframeCount() === 1, 'new session replaces the old scope')+ assert.equal(await evaluate(`new URL(document.querySelector(${JSON.stringify(frontSelector)}).src).searchParams.get('session')`), otherSession)+ // Revocation must remove *all* private layers, not reveal a draft that had+ // been correctly hidden behind the published design or retain its link dialog.+ await evaluate("setDraft('<!doctype html><html><head></head><body><p>Private retained draft</p></body></html>')")+ assert.equal(await iframeCount(), 1)+ await evaluate("parent.postMessage({type:'fx0-artifact-open',url:'https://example.com/private-design-link'},location.origin)", 1)+ await until(() => evaluate("!!document.querySelector('[role=dialog]')"), 'private design link confirmation')+ const requestsBeforeZero = paneRequests.length+ await evaluate("window.dispatchEvent(new CustomEvent('fx0:auth-required',{detail:401}))")+ await until(async () => await iframeCount() === 0, 'revocation removes both published and draft iframes')+ await until(() => evaluate("!document.querySelector('[role=dialog]')"), 'revocation closes the private design link')+ await sleep(200)+ assert.equal(paneRequests.length, requestsBeforeZero)+ assert.equal(await status(), '')+ assert.equal(await iframeCount(), 0, 'a retained draft or late result cannot revive the private scope')++ await askCapture('revoked-scope', 1, otherSession)++ assert.equal((await captureResult('revoked-scope')).answered, false, 'revoked access never photographs a retained private frame')++ assert.equal(paneCaptures.some(capture => capture.cid === 'revoked-scope'), false)+ // Revision zero still supports a legitimate authorized first-generation draft.+ await evaluate("setAccessAllowed(true);setDraft('<!doctype html><html><head></head><body><p>Authorized first draft</p></body></html>')")+ await until(() => evaluate("!!document.querySelector('iframe[title=\"Design preview while generating\"]')"), 'authorized first-generation draft remains supported')+ await evaluate('setDraft(null)')++ // With no confirmed document, an initial JSON failure is recoverable via+ // the component's own Retry button, not a test-driven iframe mount.+ publish(2, { program: 'initial retry', title: 'Initial failure recovered' }, otherSession)+ paneModes.set(`${otherSession}:2`, 'error')+ const htmlBeforeInitialError = htmlCount(), bootsBeforeInitialError = (await observed()).boots.length+ await evaluate('setRevision(2)')+ await until(async () => (await status()).includes('could not be loaded'), 'initial acquisition error')+ assert.equal(await iframeCount(), 0)+ assert.equal(htmlCount(), htmlBeforeInitialError)+ paneModes.delete(`${otherSession}:2`)+ await evaluate("[...document.querySelectorAll('#preview-pane button')].find(button => button.textContent === 'Retry preview').click()")+ await waitPane(s => s.program === 'initial retry' && s.title === 'Initial failure recovered')+ assert.equal(htmlCount(), htmlBeforeInitialError + 1)+ assert.equal((await observed()).boots.length, bootsBeforeInitialError + 1)+ assert.equal(paneRequests.filter(r => r.session === otherSession && r.wanted === 2 && r.json).length, 2)+ assert.equal(await status(), '')+ await noErrors()+ } catch (error) {+ t.diagnostic(`React fixture failure: ${error.stack}; browser errors: ${JSON.stringify(errors)}`)+ t.diagnostic(`React fixture requests: ${JSON.stringify(paneRequests)}`)+ t.diagnostic(`React fixture observation: ${JSON.stringify(await evaluate('({ ...observed, reports: observed.reports.slice(-1) })'))}`)+ throw error+ } finally {+ holdBundle = false+ for (const response of bundleHeld.splice(0)) response.destroy()+ for (const { response } of paneHeld) response.destroy()+ }+ })++ await t.test('a loaded replacement survives background time while a genuinely visible load still has a deadline', async () => {+ paneFixture ??= await buildPaneFixture(dir)+ holdBundle = false+ const publish = (revision, program) => {+ paneArtifacts.set(`${SESSION}:${revision}`, payload(revision, design({ program })))+ paneLatest.set(SESSION, revision)+ }+ const painted = revision => until(async () => (await observed()).paints.find(p => p.revision === revision && p.updateReady), `background-safe paint ${revision}`)+ const status = () => evaluate("document.querySelector('#preview-pane [role=status]')?.textContent ?? ''")+ const frameCount = () => evaluate("document.querySelectorAll('#preview-pane iframe').length")+ let alternate+ try {+ publish(101, 'background initial')+ await cdp.call('Page.navigate', { url: `${origin}/pane` })+ await until(() => evaluate('window.fixtureReady === true'), 'background fixture hydration')+ await painted(101)+ publish(301, 'background replacement')+ paneModes.set(`${SESSION}:301`, 'hold-html')+ const heldCount = paneHtmlHeld.length+ await evaluate('setRevision(301)')+ await until(() => paneHtmlHeld.length === heldCount + 1, 'replacement HTML held before the tab becomes hidden')+ await cdp.call('Emulation.setFocusEmulationEnabled', { enabled: false })+ const other = await cdp.call('Target.createTarget', { url: 'about:blank' })+ alternate = other.targetId+ await cdp.call('Target.activateTarget', { targetId: alternate })+ await until(() => evaluate('document.visibilityState === "hidden"'), 'the real parent tab is hidden')+ const pending = paneHtmlHeld[heldCount]+ sendFrame(pending.response, pending.preview)+ await until(async () => (await observed()).boots.some(boot => boot.program === 'background replacement'), 'the replacement program boots while hidden')+ // Hidden tabs pause the two animation frames used to confirm the first paint.+ // Exceed the old twenty-second wall-clock deadline without mocking this state.+ await sleep(21_000)+ assert.equal(await status(), '', 'hidden time is not a failed paint')+ assert.equal(await frameCount(), 2, 'the loaded replacement stays mounted until it can paint')+ await cdp.call('Page.bringToFront')+ await until(() => evaluate('document.visibilityState === "visible"'), 'parent tab resumes')+ await painted(301)+ await until(async () => await frameCount() === 1, 'replacement is revealed and the old front is removed')+ assert.equal(await status(), '')+ assert.equal((await observed()).boots.filter(boot => boot.program === 'background replacement').length, 1, 'resuming neither reloads nor restarts the replacement')++ publish(302, 'never-loaded replacement')+ paneModes.set(`${SESSION}:302`, 'hold-html')+ const stalledCount = paneHtmlHeld.length+ await evaluate('setRevision(302)')+ await until(() => paneHtmlHeld.length === stalledCount + 1, 'a genuinely stalled visible HTML load')+ // Advance native Chrome timers instead of adding a second wall-clock wait.+ await cdp.call('Emulation.setVirtualTimePolicy', { policy: 'advance', budget: 21_000 })+ await until(async () => (await status()).includes('did not finish loading'), 'the visible paint deadline still expires')+ assert.equal(await frameCount(), 1, 'a genuine visible failure retains the confirmed document')+ await noErrors()+ } finally {+ await cdp.call('Page.bringToFront')+ await cdp.call('Emulation.setFocusEmulationEnabled', { enabled: true })+ if (alternate) await cdp.call('Target.closeTarget', { targetId: alternate })+ paneModes.delete(`${SESSION}:301`)+ paneModes.delete(`${SESSION}:302`)+ for (const { response } of paneHtmlHeld) response.destroy()+ }+ })+ await noErrors()+ } catch (error) {+ t.diagnostic(`Browser failure: ${error.stack}; runtime errors: ${JSON.stringify(errors)}`)+ t.diagnostic(`Chrome stderr (tail): ${chromeError}`)+ if (cdp) {+ try { t.diagnostic(`Last browser observations: ${JSON.stringify(await cdp.evaluate('({ ...observed, reports: observed.reports.slice(-1) })'))}`) } catch {}+ }+ throw error+ } finally {+ // Owned resources only. Bound graceful shutdown, then force cleanup even after a+ // failed assertion/CDP connection so a hung image cannot strand Chrome or a port.+ if (cdp) await cdp.close()+ if (chrome && chrome.exitCode === null && chrome.signalCode === null) {+ const exited = new Promise(resolve => chrome.once('exit', resolve))+ chrome.kill('SIGTERM')+ await Promise.race([exited, sleep(2000, undefined, { ref: false })])+ if (chrome.exitCode === null && chrome.signalCode === null) { chrome.kill('SIGKILL'); await exited }+ }+ chrome?.stderr.destroy()+ for (const { response } of [...held, ...paneHeld, ...paneHtmlHeld]) response.destroy()+ for (const response of bundleHeld) response.destroy()+ server.closeAllConnections()+ await new Promise(resolve => server.close(resolve))+ await rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })+ }+ })