A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.
TypeScript
Preserve preview state across compatible design updates
Esteban Suarezae9888ebbb1f
diff --git a/README.md b/README.mdindex 96273e6..9242e7a 100644--- a/README.md+++ b/README.md@@ -111,6 +111,7 @@ You can watch this happen. Open session diagnostics from the header to see the c- A text message sent while a tool runs, such as while a design is being written, waits for that tool before the model sees it. A message with images runs as its own turn, after any running turn finishes.- Every turn bills the login and team that sent the message that started it; a later message cannot change an earlier turn's funding. A text message that joins a running turn is billed to that turn. Token renewal from the same login keeps the turn's billing team.- Free prompts start in a new design on Opus 5.5 Fast with low effort. Existing paid-only chats keep their own billing. The allowance is five per IP across chats and browsers, with no periodic refill; clearing cookies does not reset it. After it is used, sign in to continue with your own team.+- Published previews update compatible stylesheets, inline styles on uniquely identified elements, and identified leaf text without restarting their scripts. Unedited inputs, listeners, and runtime state stay in place. Changes to scripts, structure, unsupported fields, or conflicting runtime values reload the preview instead. A published design stays visible while its next revision is prepared.- A design being written streams through a bounded, expiring Redis channel, so viewers on other instances can see it too. Reconnecting resumes from the full prefix; generation IDs and offsets prevent duplicated bytes. The provisional preview strips active markup and runs without scripts. Publishing or ending a turn closes its draft before it can replace the finished preview.- Deleting a chat removes fx0's records and credential. libfx's session data expires with the World's retention.- When no route follows a chat, its transcript catches up the next time someone opens it.diff --git a/app/api/artifact-frame/route.ts b/app/api/artifact-frame/route.tsindex e30a921..68a3cd7 100644--- a/app/api/artifact-frame/route.ts+++ b/app/api/artifact-frame/route.ts@@ -1,5 +1,6 @@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 { PREVIEW_PROTOCOL, type PreviewPayload } from '../../../lib/preview-update'import { markRemoteImages } from '../../../lib/remote-image'import { readDesignArtifactAt } from '../../../lib/journal'import { readGeneration } from '../../../lib/history'@@ -11,17 +12,22 @@ export const maxDuration = 30export const GET = withSessionRoute(async (request, { id: sessionId, user }) => {// Without a revision this is the live design in Redis; with one, a past version from Neon.const params = new URL(request.url).searchParams+ const format = params.get('format')+ if (format != null && format !== 'json') return Response.json({ error: 'Unknown preview format.' }, { status: 400 })+ const json = format === 'json'const revision = Number(params.get('revision'))const past = Number.isSafeInteger(revision) && revision > 0const live = past ? null : await readDesignArtifactAt(sessionId)- const artifact = past ? await readGeneration(user.id, sessionId, revision) : live!.html+ const stored = past ? await readGeneration(user.id, sessionId, revision) : live!.html+ const artifact = stored == null ? null : normalizeDesignArtifactHtml(stored)+ const actualRevision = past ? revision : live!.revision// ?v= names the revision the page expects. When it is the one live, the browser may// keep this response but must revalidate it: this route checks the session first,// so a reload costs a 304 and a signed-out browser gets nothing from its cache.const version = Number(params.get('v'))const cacheable = live?.html != null && Number.isSafeInteger(version) && version > 0 && version === live.revisionconst etag = cacheable ? `"${sessionId}:${live.revision}"` : null- if (etag && request.headers.get('if-none-match') === etag) {+ if (!json && etag && request.headers.get('if-none-match') === etag) {return new Response(null, { status: 304, headers: { 'cache-control': 'private, no-cache', etag } })}const readyToken = crypto.randomUUID()@@ -36,18 +42,28 @@ export const GET = withSessionRoute(async (request, { id: sessionId, user }) =>// Every stored design passed validation, so this only guards against one that// somehow lacks a doctype: it is never shown without its CSP.if (artifact != null && prepared == null) log(sessionId, 'artifact:unrenderable', { revision: past ? revision : live!.revision })+ const payload: PreviewPayload | null = artifact != null && prepared != null ? {+ protocol: PREVIEW_PROTOCOL, sessionId, revision: actualRevision,+ sourceHtml: artifact, renderHtml: marked.html!, images,+ } : null+ if (json) {+ return Response.json(payload ?? { error: artifact == null ? 'No design artifact.' : 'The design could not be prepared.' }, {+ status: payload ? 200 : artifact == null ? 404 : 422,+ headers: { 'cache-control': 'private, no-store', 'x-content-type-options': 'nosniff' },+ })+ }const preparedArtifact = prepared ??`<!doctype html><html><head><meta charset="utf-8"><title>No design artifact</title></head><body><p>${artifact != 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)+ const html = designFrameHtml(preparedArtifact, readyToken, images, payload ?? undefined)return new Response(html, {status: artifact == null ? 404 : 200,headers: {'cache-control': etag ? 'private, no-cache' : 'private, no-store',...(etag ? { etag } : {}),- 'content-security-policy': designFrameCsp(images.length ? `${new URL(request.url).origin}${ARTIFACT_IMAGE_PATH}` : undefined),+ 'content-security-policy': designFrameCsp(`${new URL(request.url).origin}${ARTIFACT_IMAGE_PATH}`),'content-type': 'text/html; charset=utf-8','permissions-policy':'accelerometer=(), camera=(), clipboard-read=(), clipboard-write=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), usb=()',diff --git a/components/chat-app.tsx b/components/chat-app.tsxindex 513b9a7..3e8823a 100644--- a/components/chat-app.tsx+++ b/components/chat-app.tsx@@ -2090,6 +2090,7 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultModsource={{ 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}/>diff --git a/components/preview-pane.tsx b/components/preview-pane.tsxindex ec1c6e0..fca649e 100644--- a/components/preview-pane.tsx+++ b/components/preview-pane.tsx@@ -3,6 +3,8 @@import { useCallback, useEffect, useRef, useState } from 'react'import { designLinkUrl } from '../lib/design-link'import { EMPTY_DRAFT_DOCUMENT, patchDraftDocument } from '../lib/draft-preview'+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'@@ -12,112 +14,375 @@ const LINK_PAUSE_MS = 2000export type PreviewSource = { kind: 'design'; sessionId: string; revision: number }+type PreviewSlot = {+ mountUrl: string+ requestedRevision: number+ appliedRevision: number | null+ documentId: string | null+ updateReady: boolean+}++type PreviewDisplay = {+ scope: string+ slots: [PreviewSlot | null, PreviewSlot | null]+ front: number | null+ error: string | null+}++type PreviewAttempt = {+ revision: number+ controller: AbortController+ timer: ReturnType<typeof setTimeout> | null+ requestId: string+ posted: { index: number; documentId: string; revision: number } | null+}++function isPreviewPayload(value: unknown): value is PreviewPayload {+ if (!value || typeof value !== 'object') return false+ const payload = value as Partial<PreviewPayload>+ return payload.protocol === PREVIEW_PROTOCOL && typeof payload.sessionId === 'string'+ && Number.isSafeInteger(payload.revision) && payload.revision! > 0+ && typeof payload.sourceHtml === 'string' && new TextEncoder().encode(payload.sourceHtml).length <= 512 * 1024+ && typeof payload.renderHtml === 'string' && payload.renderHtml.length <= 1024 * 1024+ && Array.isArray(payload.images) && payload.images.length <= 12 && payload.images.every((image) => {+ if (image == null || typeof image.marker !== 'string' || !image.marker || image.marker.length > 256 || typeof image.src !== 'string') return false+ try {+ const url = new URL(image.src, window.location.href)+ return url.origin === window.location.origin && url.pathname === '/api/artifact-image' && !url.username && !url.password+ } catch { return false }+ })+}+export default function PreviewPane({source,viewing,draft = null,+ accessAllowed = true,intro,onClose,}: {source: PreviewSource// A past revision opened from the transcript's "View" link, never the latest; null is the latest.viewing: number | null- // The design as the model writes it; shown until the real publish arrives.+ // The design as the model writes it; shown until the first real publish paints.draft?: string | null+ // Explicit revocation hides every private layer, including retained drafts and links.+ accessAllowed?: boolean// Only an empty chat explains fx0; a chat waiting on its first design stays blank.intro: booleanonClose: () => 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(() => {})+ 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 = () => {}+ 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+ 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+ if (loading != null) {+ slots[loading] = null+ if (front === loading) front = null+ }+ loading = null+ }+ const fail = (message: string) => {+ error = message+ publish()+ }+ const watchLoad = (index: number) => {+ loadTimer = setTimeout(() => {+ if (!active() || loading !== index) return+ clearLoading()+ fail('The design preview did not finish loading. Try again.')+ }, PREVIEW_PREPARE_MS * 2)+ }+ 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+ 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+ }+ 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)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+ 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)+ // 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)+ demand.current = () => {}+ retry.current = () => {}}- }, [])- const caughtUp = !previewUrl || (front != null && slots[front] === previewUrl)- const [heldDraft, setHeldDraft] = useState<string | null>(null)- const liveDraft = draft && renderable(draft) ? draft : null+ }, [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+ 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) => {@@ -135,43 +400,45 @@ export default function PreviewPane({aria-label="preview"className="order-1 flex min-h-0 min-w-0 flex-1 flex-col bg-background overscroll-contain lg:order-none lg:border-l lg:border-border">- {draftLayer || shownUrl || slots[0] || slots[1] ? (- <div className="relative min-h-0 flex-1">- {slots.map((url, index) => url && (- <iframe- key={index}- ref={(element) => { frames.current[index] = element }}- src={url}- referrerPolicy="no-referrer"- title={index === front ? 'Design artifact preview' : undefined}- aria-hidden={index !== front || undefined}- onLoad={() => {- if (index === front) return- if (fallback.current) clearTimeout(fallback.current)- fallback.current = setTimeout(() => bringToFront(index), 1500)- }}- className={`absolute inset-0 h-full w-full bg-background ${frameLayer(index === front, front != null)}`}- />- ))}- {draftLayer && (- <div className="absolute inset-0 z-20 flex">- <DraftPreview html={draftLayer} />- </div>- )}+ {current && display.error && (+ <div role="status" aria-live="polite" className="flex items-center justify-between gap-3 border-b border-border px-4 py-3 text-sm">+ <p>{display.error}</p>+ <button type="button" onClick={() => retry.current()} className="shrink-0 rounded px-3 py-2 underline focus-visible:outline-2 focus-visible:outline-offset-2">+ Retry preview+ </button></div>- ) : intro ? (- // A chat loading from its URL (html.chat-url) is not empty, so it stays blank too.- <div className="min-h-0 flex-1 overflow-y-auto [html.chat-url_&]:hidden">- <div className="flex min-h-full items-center justify-center px-6 py-10">- <div className="w-full max-w-sm">- <HowItWorksPanel />+ )}+ <div className="relative min-h-0 flex-1">+ {/* These two slots never move or change keys. A hot update never changes src. */}+ {slots.map((slot, index) => slot && (+ <iframe+ key={index}+ ref={(element) => { frames.current[index] = element }}+ src={slot.mountUrl}+ referrerPolicy="no-referrer"+ onLoad={() => frames.current[index]?.contentWindow?.postMessage({ type: 'fx0-preview-status', protocol: PREVIEW_PROTOCOL }, window.location.origin)}+ title={index === front ? 'Design artifact preview' : 'Loading design artifact preview'}+ aria-hidden={index !== front || undefined}+ tabIndex={index === front ? undefined : -1}+ className={`absolute inset-0 h-full w-full bg-background ${frameLayer(index === front, front != null)}`}+ />+ ))}+ {draftLayer ? (+ <div className="absolute inset-0 z-20 flex">+ <DraftPreview html={draftLayer} />+ </div>+ ) : !published && !slots[0] && !slots[1] && intro ? (+ // A chat loading from its URL (html.chat-url) is not empty, so it stays blank too.+ <div className="h-full min-h-0 overflow-y-auto [html.chat-url_&]:hidden">+ <div className="flex min-h-full items-center justify-center px-6 py-10">+ <div className="w-full max-w-sm">+ <HowItWorksPanel />+ </div></div></div>- </div>- ) : (- <div className="flex-1" />- )}- <DesignLinkDialog url={linkRequest} onClose={closeLinkRequest} />+ ) : null}+ </div>+ <DesignLinkDialog url={linkRequest?.scope === scope ? linkRequest.url : null} onClose={closeLinkRequest} /></section>)}diff --git a/lib/design-artifact.ts b/lib/design-artifact.tsindex ad1714b..c91a027 100644--- a/lib/design-artifact.ts+++ b/lib/design-artifact.ts@@ -1,3 +1,6 @@+// @ts-expect-error Node strip-types tests require the source extension.+import { previewUpdateRuntime, type PreviewPayload } from './preview-update.ts'+export const MAX_DESIGN_ARTIFACT_BYTES = 512 * 1024export const MAX_REMOTE_IMAGE_URL_LENGTH = 2048@@ -75,7 +78,7 @@ export const MAX_EMBEDDED_IMAGE_BYTES = 4 * 1024 * 1024// 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.-export function designFrameHtml(preparedArtifact: string, readyToken: string, images: { marker: string; src: string }[] = []): string {+export function designFrameHtml(preparedArtifact: string, readyToken: string, images: { marker: string; src: string }[] = [], preview?: PreviewPayload): 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@@ -83,6 +86,11 @@ export function designFrameHtml(preparedArtifact: string, readyToken: string, imconst 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())// 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.@@ -99,8 +107,14 @@ export function designFrameHtml(preparedArtifact: string, readyToken: string, im<script>const design=${serializedArtifact};const images=${serializedImages};+const preview=${scriptJson(preview ?? null)};let artifact=null;-const token=${serializedReadyToken};+let token=${serializedReadyToken};+let documentId=token;+let current=null;+let pending=null;+let hotReady=false;+let hasPainted=false;const frame=document.createElement('iframe');frame.title='Interactive design artifact';frame.setAttribute('sandbox','allow-scripts');@@ -109,45 +123,133 @@ frame.setAttribute('credentialless','');let readySignals=0;let consumedSignals=0;let lastHeartbeat=Date.now();-const restore=()=>{if(!artifact)return;lastHeartbeat=Date.now();frame.src=artifact;};+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 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();},500);-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;+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 --git a/lib/preview-update.ts b/lib/preview-update.tsnew file mode 100644index 0000000..f77c4ed--- /dev/null+++ b/lib/preview-update.ts@@ -0,0 +1,295 @@+export const PREVIEW_PROTOCOL = 1+export const PREVIEW_PREPARE_MS = 10_000++export interface PreviewPayload {+ protocol: 1+ sessionId: string+ revision: number+ sourceHtml: string+ renderHtml: string+ images: { marker: string; src: string }[]+}++export interface PreviewSeed {+ sessionId: string+ revision: number+ sourceHtml: string+ renderHtml: string+ documentId: string+ parentOrigin: string+ token: string+}++// Serialized into the opaque child with .toString(); all runtime dependencies stay inside.+export function previewUpdateRuntime(seed: PreviewSeed): void {+ const htmlNamespace = 'http://www.w3.org/1999/xhtml'+ const sourceLimit = 512 * 1024+ const renderLimit = 8 * 1024 * 1024+ const textTags = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'li', 'button', 'a', 'label'])+ type Snapshot = {+ source: Document+ render: Document+ authored: Map<Element, Element>+ ids: Map<string, Element | null>+ }+ type Change = { kind: 'css' | 'style' | 'text'; before: Element; after: Element }+ let baseline: Snapshot | undefined+ let bindings = new Map<Element, Element>()+ const sheets = new Map<Element, CSSStyleSheet | null>()+ let revision = seed.revision+ let initialized = false+ let failed = false+ let busy = false+ let lastRequestId = ''++ function reject(reason: string): never { throw new Error(reason) }+ function sameElement(a: Element, b: Element): boolean {+ return a.namespaceURI === b.namespaceURI && a.localName === b.localName && a.id === b.id+ }+ function sameAttributes(a: Element, b: Element): boolean {+ return a.attributes.length === b.attributes.length && [...a.attributes].every(attribute => {+ const other = b.getAttributeNodeNS(attribute.namespaceURI, attribute.localName)+ return other?.name === attribute.name && other.value === attribute.value+ })+ }+ function children(node: Node): Node[] {+ // Template contents must also be compared, but can never be live patch targets.+ return [...(node instanceof HTMLTemplateElement ? node.content : node).childNodes]+ }+ function sameType(a: Node, b: Node): void {+ if (a.nodeType !== b.nodeType) reject('tree-shape-changed')+ if (a.nodeType === 1 && !sameElement(a as Element, b as Element)) reject('element-identity-changed')+ if (a.nodeType === 10) {+ const left = a as DocumentType, right = b as DocumentType+ if (left.name !== right.name || left.publicId !== right.publicId || left.systemId !== right.systemId) reject('doctype-changed')+ }+ }+ function isStyle(element: Element): element is HTMLStyleElement {+ return element.namespaceURI === htmlNamespace && element.localName === 'style'+ }+ function textOnly(element: Element): boolean {+ return [...element.childNodes].every(node => node.nodeType === 3)+ }+ function bounded(source: unknown, render: unknown): source is string {+ return typeof source === 'string' && source.length <= sourceLimit &&+ typeof render === 'string' && render.length <= renderLimit &&+ new TextEncoder().encode(source).byteLength <= sourceLimit+ }+ function snapshot(source: string, render: string): Snapshot {+ const parser = new DOMParser()+ const result: Snapshot = {+ source: parser.parseFromString(source, 'text/html'),+ render: parser.parseFromString(render, 'text/html'),+ authored: new Map(), ids: new Map(),+ }+ if (result.source.doctype?.name !== 'html' || result.render.doctype?.name !== 'html') reject('missing-doctype')+ function pair(a: Node, b: Node): void {+ sameType(a, b)+ if (a.nodeType === 1) {+ const authored = a as Element, rendered = b as Element+ result.authored.set(rendered, authored)+ if (authored.id) result.ids.set(authored.id, result.ids.has(authored.id) ? null : authored)+ // Embedding CSS images may change raw style text, including an empty style.+ if (isStyle(authored) && textOnly(authored) && textOnly(rendered)) return+ }+ const left = children(a), right = children(b)+ if (left.length !== right.length) reject('source-render-shape-mismatch')+ left.forEach((node, index) => pair(node, right[index]))+ }+ pair(result.source, result.render)+ return result+ }+ function editable(element: Element): boolean {+ for (let current: Element | null = element; current; current = current.parentElement) {+ const value = current.getAttribute('contenteditable')?.toLowerCase()+ if (value === 'false') return false+ if (value === '' || value === 'true' || value === 'plaintext-only') return true+ }+ return false+ }+ function standard(element: Element): boolean {+ return element.namespaceURI === htmlNamespace && element instanceof HTMLElement && !(element instanceof HTMLUnknownElement) &&+ !element.localName.includes('-') && !element.hasAttribute('is')+ }+ function identified(element: Element, state: Snapshot, rendered: boolean): boolean {+ const authored = rendered ? state.authored.get(element) : element+ return !!authored?.id && state.ids.get(authored.id) === authored && standard(authored) &&+ standard(element) && !editable(authored) && !editable(element)+ }+ function compare(previous: Snapshot, next: Snapshot, rendered: boolean, changes: Change[], successors: Map<Element, Element>): void {+ function walk(a: Node, b: Node, inert: boolean): void {+ sameType(a, b)+ if (a.nodeType === 1) {+ const before = a as Element, after = b as Element+ if (rendered) successors.set(before, after)+ const locked = inert || before.localName === 'script'+ let styleChanged = false+ for (const attribute of [...before.attributes, ...after.attributes]) {+ const left = before.getAttributeNodeNS(attribute.namespaceURI, attribute.localName)+ const right = after.getAttributeNodeNS(attribute.namespaceURI, attribute.localName)+ if (left?.name === right?.name && left?.value === right?.value) continue+ if (locked || attribute.namespaceURI !== null || attribute.name !== 'style' ||+ !identified(before, previous, rendered) || !identified(after, next, rendered)) reject('unsupported-attribute-change')+ styleChanged = true+ }+ if (rendered && styleChanged) changes.push({ kind: 'style', before, after })+ if (!locked && isStyle(before) && textOnly(before) && textOnly(after)) {+ if (before.textContent !== after.textContent && rendered) changes.push({ kind: 'css', before, after })+ return+ }+ if (!locked && before.childNodes.length === 1 && after.childNodes.length === 1 &&+ before.firstChild!.nodeType === 3 && after.firstChild!.nodeType === 3 && before.textContent !== after.textContent) {+ if (!textTags.has(before.localName) || !identified(before, previous, rendered) || !identified(after, next, rendered)) reject('unsupported-text-change')+ if (rendered) changes.push({ kind: 'text', before, after })+ return+ }+ inert = inert || before.localName === 'template'+ } else if (a.nodeValue !== b.nodeValue) reject('unsupported-content-change')+ const left = children(a), right = children(b)+ if (left.length !== right.length) reject('tree-shape-changed')+ left.forEach((node, index) => walk(node, right[index], inert))+ }+ walk(rendered ? previous.render : previous.source, rendered ? next.render : next.source, false)+ }+ function liveIds(): Map<string, Element | null> {+ const ids = new Map<string, Element | null>()+ for (const element of document.querySelectorAll('[id]')) {+ if (element.id) ids.set(element.id, ids.has(element.id) ? null : element)+ }+ return ids+ }+ function locate(element: Element, state: Snapshot, ids: Map<string, Element | null>): Element | null {+ const authored = state.authored.get(element)!+ if (authored.id) {+ if (state.ids.get(authored.id) !== authored) return null+ const live = ids.get(authored.id)+ return live && sameElement(element, live) ? live : null+ }+ if (!isStyle(element)) return null+ const expected = [...state.authored.keys()].filter(candidate => isStyle(candidate) &&+ candidate.textContent === element.textContent && sameAttributes(candidate, element))+ const matches = [...document.querySelectorAll('style')].filter(candidate => isStyle(candidate) &&+ candidate.textContent === element.textContent && sameAttributes(candidate, element))+ return expected.length === 1 && matches.length === 1 ? matches[0] : null+ }+ function rules(sheet: CSSStyleSheet): string {+ return JSON.stringify([...sheet.cssRules].map(rule => rule.cssText))+ }+ function checkSheet(live: HTMLStyleElement, expected: Element, identity: boolean): CSSStyleSheet {+ const sheet = live.sheet+ if (!sheet || (identity && sheets.get(live) !== sheet)) reject('stylesheet-replaced')+ if (live.textContent !== expected.textContent) reject('stylesheet-text-conflict')+ for (const name of ['media', 'type', 'title']) {+ if (live.getAttribute(name) !== expected.getAttribute(name)) reject('stylesheet-state-conflict')+ }+ // Constructed sheets normalize through the same browser CSS parser without touching+ // the live tree. Unsupported rules (for example @import) conservatively conflict.+ const canonical = new CSSStyleSheet({ media: expected.getAttribute('media') ?? '' })+ canonical.replaceSync(expected.textContent ?? '')+ if (sheet.ownerNode !== live || sheet.disabled || sheet.href !== null || sheet.ownerRule !== null ||+ sheet.parentStyleSheet !== null || sheet.media.mediaText !== canonical.media.mediaText || rules(sheet) !== rules(canonical)) reject('stylesheet-cssom-conflict')+ return sheet+ }+ function preflight(changes: Change[], state: Snapshot): (() => void)[] {+ const ids = liveIds()+ return changes.map(change => {+ const { before, after, kind } = change+ const live = locate(before, state, ids)+ if (!live || !live.isConnected || bindings.get(before) !== live) reject('target-missing-or-replaced')+ if (kind === 'css') {+ if (!isStyle(live)) reject('stylesheet-target-mismatch')+ checkSheet(live, before, true)+ return () => {+ live.textContent = after.textContent+ sheets.set(live, checkSheet(live, after, false))+ }+ }+ if (!standard(live) || editable(live) || (live as HTMLElement).isContentEditable || document.designMode === 'on') reject('editable-or-custom-target')+ if (kind === 'style') {+ if (live.getAttribute('style') !== before.getAttribute('style')) reject('inline-style-conflict')+ const value = after.getAttribute('style')+ return () => { if (value === null) live.removeAttribute('style'); else live.setAttribute('style', value) }+ }+ if (live.childNodes.length !== 1 || live.firstChild!.nodeType !== 3 || live.firstChild!.nodeValue !== before.firstChild!.nodeValue) reject('leaf-text-conflict')+ const text = live.firstChild!+ return () => { text.nodeValue = after.firstChild!.nodeValue }+ })+ }+ function result(requestId: string, status: 'applied' | 'reload', appliedRevision: number, reason?: string): void {+ parent.postMessage({ type: 'fx0-preview-result', protocol: 1, token: seed.token, documentId: seed.documentId,+ requestId, status, revision: appliedRevision, ...(reason ? { reason } : {}) }, seed.parentOrigin)+ }++ // This runs before authored scripts. Never reconstruct either baseline from the live DOM.+ try {+ if (!Number.isSafeInteger(revision) || revision < 0 || typeof seed.sessionId !== 'string' || !seed.sessionId ||+ typeof seed.documentId !== 'string' || !seed.documentId || typeof seed.token !== 'string' || !seed.token ||+ typeof seed.parentOrigin !== 'string' || !seed.parentOrigin || seed.parentOrigin === '*' || seed.parentOrigin === 'null' ||+ !bounded(seed.sourceHtml, seed.renderHtml)) reject('invalid-seed')+ baseline = snapshot(seed.sourceHtml, seed.renderHtml)+ } catch { failed = true }++ function loaded(): void {+ try {+ if (!baseline || failed) reject('baseline-unavailable')+ const ids = liveIds()+ for (const element of baseline.authored.keys()) {+ const live = locate(element, baseline, ids)+ if (live) {+ bindings.set(element, live)+ if (isStyle(live)) sheets.set(live, live.sheet)+ }+ }+ initialized = true+ } catch { failed = true }+ parent.postMessage({ type: 'fx0-preview-ready', protocol: 1, token: seed.token, documentId: seed.documentId,+ revision: seed.revision, ready: initialized && !failed }, seed.parentOrigin)+ }+ if (document.readyState === 'complete') loaded()+ else addEventListener('load', loaded, { once: true })++ addEventListener('message', event => {+ if (event.source !== parent || event.origin !== seed.parentOrigin) return+ const data = event.data+ const keys = ['type', 'protocol', 'token', 'documentId', 'requestId', 'baseRevision', 'revision', 'sourceHtml', 'renderHtml']+ if (!data || typeof data !== 'object' || Array.isArray(data) || Object.keys(data).length !== keys.length ||+ !Object.keys(data).every(key => keys.includes(key)) || data.type !== 'fx0-preview-apply' || data.protocol !== 1 ||+ data.token !== seed.token || data.documentId !== seed.documentId || typeof data.requestId !== 'string' ||+ !data.requestId.length || data.requestId.length > 128 || !Number.isSafeInteger(data.baseRevision) || data.baseRevision < 0 ||+ !Number.isSafeInteger(data.revision) || data.revision <= data.baseRevision || !bounded(data.sourceHtml, data.renderHtml)) return+ const requestId: string = data.requestId, requestedRevision: number = data.revision+ if (busy) { result(requestId, 'reload', revision, 'update-busy'); return }+ if (requestId === lastRequestId) { result(requestId, 'reload', revision, 'duplicate-request'); return }+ if (data.baseRevision !== revision) { result(requestId, 'reload', revision, 'stale-base-revision'); return }+ if (!initialized || failed || !baseline) { result(requestId, 'reload', revision, 'baseline-unavailable'); return }+ busy = true+ lastRequestId = requestId+ try {+ const next = snapshot(data.sourceHtml, data.renderHtml)+ const changes: Change[] = [], successors = new Map<Element, Element>()+ compare(baseline, next, false, changes, successors)+ // Even an authored no-op must account for every fully embedded render difference.+ compare(baseline, next, true, changes, successors)+ const operations = preflight(changes, baseline)+ const nextBindings = new Map<Element, Element>()+ for (const [before, after] of successors) {+ const live = bindings.get(before)+ if (live) nextBindings.set(after, live)+ }+ for (const apply of operations) apply()+ baseline = next+ bindings = nextBindings+ revision = requestedRevision+ // Capture this request's revision; a later message must not change its ACK.+ requestAnimationFrame(() => requestAnimationFrame(() => {+ result(requestId, 'applied', requestedRevision)+ busy = false+ }))+ } catch (error) {+ // A partial write cannot safely be rolled back in the presence of authored code.+ failed = true+ busy = false+ result(requestId, 'reload', revision, error instanceof Error ? error.message : 'update-exception')+ }+ })+}diff --git a/package.json b/package.jsonindex f239754..d13a3a4 100644--- a/package.json+++ b/package.json@@ -14,7 +14,7 @@"test:journal:integration": "node --env-file-if-exists=.env.local --experimental-strip-types --test tests/journal.integration.mjs","test:smoke": "node tests/local-auth-smoke.mjs","db:migrate": "node --env-file-if-exists=.env.local scripts/migrate-database.mjs",- "test:artifact:browser": "node --experimental-strip-types --test tests/design-artifact.browser.mjs tests/attach-image.browser.mjs",+ "test:artifact:browser": "node --experimental-strip-types --test tests/design-artifact.browser.mjs tests/attach-image.browser.mjs tests/preview-update.browser.mjs","test:budget:integration": "node --experimental-strip-types --test tests/turn-budget.integration.mjs","test:turns:integration": "node --experimental-strip-types --test tests/turn-work.integration.mjs","test:trial:integration": "node --experimental-strip-types --test tests/trial.integration.mjs",diff --git a/tests/core.test.mjs b/tests/core.test.mjsindex f3560cb..98afa8e 100644--- a/tests/core.test.mjs+++ b/tests/core.test.mjs@@ -747,12 +747,15 @@ async function frameWatchdog() {const html = designFrameHtml(SAFE_DESIGN, 'watchdog-test')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() {},+ clearTimeout() {},})await new Promise(setImmediate)assert.equal(loads, 1, 'the initial artifact loads')diff --git a/tests/html-ui.test.mjs b/tests/html-ui.test.mjsindex c5369fd..2beb03c 100644--- a/tests/html-ui.test.mjs+++ b/tests/html-ui.test.mjs@@ -142,6 +142,18 @@ test('a chat with a published design renders its transcript and the isolated preassert.match(markup, /aria-label="copy, download or publish the design"/)})+test('a denied preview renders neither its published frame nor an in-progress private draft', () => {+ const markup = renderToStaticMarkup(createElement(PreviewPane, {+ source: { kind: 'design', sessionId: 'private-session', revision: 2 },+ viewing: null,+ draft: '<!doctype html><html><head></head><body><p>Private draft</p></body></html>',+ accessAllowed: false,+ intro: false,+ onClose: () => {},+ }))+ assert.doesNotMatch(markup, /<iframe|artifact-frame|Design preview while generating|Private draft/)+})+test('a reloaded transcript is anchored at its end until the client takes over', () => {const markup = renderChat({ revision: 0, events: [{ type: 'user', seq: 1, id: 1, text: 'Keep this history', author: 'Ada' }] })// A reversed flex column scrolls from its end, so every paint of a partly parseddiff --git a/tests/preview-update.browser.mjs b/tests/preview-update.browser.mjsnew file mode 100644index 0000000..b64a7e2--- /dev/null+++ b/tests/preview-update.browser.mjs@@ -0,0 +1,820 @@+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 { 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 = '' } = {}) {+ return `<!doctype html><html><head><title>Interactive presentation</title>+<style 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 refs = Object.fromEntries(['title', 'inline', 'input', 'next', 'theme'].map(id => [id, document.getElementById(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 = document.getElementById('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]) => document.getElementById(id) === node),+ runtimeLabel: document.getElementById('runtime-label').textContent, generated: !!document.getElementById('generated'),+ cssText: document.getElementById('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)+ useEffect(() => {+ Object.assign(window, { setRevision, setViewing, setSession, setDraft, setAccessAllowed, 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) })+}`)+ 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 = [], bundleHeld = []+ 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))+ }+ 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/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"}')+ if (!json) return sendFrame(response, preview)+ const mode = paneModes.get(`${session}:${wanted}`)+ 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('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+ 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)'))+ publish(104, { color: 'rgb(60, 70, 80)', title: 'Next patch after actual revision', padding: 12 })+ await evaluate('setRevision(104)')+ 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')+ 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')+ // 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 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]) 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 })+ }+})diff --git a/tests/route-security.test.mjs b/tests/route-security.test.mjsindex b7be32c..e984356 100644--- a/tests/route-security.test.mjs+++ b/tests/route-security.test.mjs@@ -491,8 +491,8 @@ test('the artifact preview permits iframe origins but preserves opaque credentia// The design only asks to open a link; the wrapper passes the ask to the app on this// origin, which shows the address and opens it on the user's own click.assert.doesNotMatch(html, /window\.open/)- assert.match(html, /if\(event\.source!==frame\.contentWindow\|\|event\.data\?\.token!==token\)return;/)- assert.match(html, /parent\.postMessage\(\{type:'fx0-artifact-open',url:event\.data\.url\},location\.origin\)/)+ assert.match(html, /if\(event\.source!==frame\.contentWindow\|\|data\?\.token!==token\)return;/)+ assert.match(html, /parent\.postMessage\(\{type:'fx0-artifact-open',url:data\.url\},location\.origin\)/)assert.match(html, /navigator\.userActivation\?\.isActive!==false/)assert.doesNotMatch(html, /allow-popups/)assert.match(html, /setAttribute\('credentialless',''\)/)@@ -629,6 +629,46 @@ test('the browser keeps a preview only when its URL names the revision that is lassert.equal(missing.headers.get('cache-control'), 'private, no-store')})+test('preview update data names the actual revision, never shares HTML validators, and contains no host bootstrap', async () => {+ const state = reset({ liveRevision: 4 })+ const req = request('artifact-frame', 'GET', `${own}&v=2&format=json`)+ req.headers.set('if-none-match', `"${own}:4"`)+ const response = await routes['artifact-frame'].GET(req)+ assert.equal(response.status, 200)+ assert.match(response.headers.get('content-type'), /^application\/json/)+ assert.equal(response.headers.get('cache-control'), 'private, no-store')+ assert.equal(response.headers.get('etag'), null)+ assert.equal(response.headers.get('x-content-type-options'), 'nosniff')+ const data = await response.json()+ assert.equal(data.protocol, 1)+ assert.equal(data.sessionId, own)+ assert.equal(data.revision, 4)+ assert.equal(data.sourceHtml, data.renderHtml)+ assert.deepEqual(data.images, [])+ assert.doesNotMatch(JSON.stringify(data), /fx0-preview-ready|Content-Security-Policy|user-token|secret-refresh/)+ assert.equal(state.redisReads.filter(id => id === own).length, 1, 'source and revision come from one read')+})++test('preview JSON uses the same ownership boundary and refuses missing artifacts or unknown formats', async () => {+ const state = reset()+ assert.equal((await routes['artifact-frame'].GET(request('artifact-frame', 'GET', `${foreign}&format=json`))).status, 404)+ assert.equal(state.redisReads.includes(foreign), false)+ state.liveRevision = 0+ const missing = await routes['artifact-frame'].GET(request('artifact-frame', 'GET', `${own}&format=json`))+ assert.equal(missing.status, 404)+ assert.equal(missing.headers.get('cache-control'), 'private, no-store')+ assert.equal((await routes['artifact-frame'].GET(request('artifact-frame', 'GET', `${own}&format=unknown`))).status, 400)+})++test('image-free wrappers can prepare later images without granting the design network access', async () => {+ reset()+ const response = await routes['artifact-frame'].GET(request('artifact-frame'))+ assert.match(response.headers.get('content-security-policy'), /connect-src https:\/\/fx0\.example\/api\/artifact-image(?:;|$)/)+ const html = await response.text()+ assert.match(html, /connect-src 'none'/)+ assert.doesNotMatch(html, /allow-same-origin|allow-popups/)+})+test('the design download is the stored HTML, served so this origin never renders it', async () => {reset()const response = await routes.artifact.GET(request('artifact', 'GET', own))