A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.
TypeScript
Load the first design preview without a JSON round trip
Esteban Suarez22e99a73bf68
diff --git a/app/api/artifact-frame/route.ts b/app/api/artifact-frame/route.tsindex da909a2..5e193a6 100644--- a/app/api/artifact-frame/route.ts+++ b/app/api/artifact-frame/route.ts@@ -10,7 +10,7 @@ import { log } from '../../../lib/session'export const maxDuration = 30-export const GET = withSessionRoute(async (request, { id: sessionId, user }) => {+const serveFrame = 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).searchParamsconst format = params.get('format')@@ -26,6 +26,14 @@ export const GET = withSessionRoute(async (request, { id: sessionId, user }) =>// 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'))+ // A frame that asks for a newer revision than the live one is a raced or stale load. It+ // fails here, before any design is prepared, so the parent retries instead of booting+ // the old design (components/preview-pane.tsx). Current or newer revisions are served.+ if (!json && !past && request.headers.get('sec-fetch-dest') === 'iframe' && Number.isSafeInteger(version) && version > 0 && actualRevision < version) {+ return Response.json({ error: 'The requested design version is not available yet. Try again.' }, {+ status: 404, headers: { 'cache-control': 'private, no-store' },+ })+ }const cacheable = live?.html != null && Number.isSafeInteger(version) && version > 0 && version === live.revisionconst etag = cacheable ? `"${sessionId}:${live.revision}"` : nullif (!json && etag && request.headers.get('if-none-match') === etag) {@@ -61,7 +69,7 @@ export const GET = withSessionRoute(async (request, { id: sessionId, user }) =>// Every preview is photographed where it is (lib/design-capture.ts): the wrapper gives each child document its own capture runtime.const html = designFrameHtml(preparedArtifact, readyToken, images, payload ?? undefined, { relay: DESIGN_CAPTURE_RELAY, script: designCaptureScript })return new Response(html, {- status: artifact == null ? 404 : 200,+ status: artifact == null ? 404 : prepared == null ? 422 : 200,headers: {'cache-control': etag ? 'private, no-cache' : 'private, no-store',...(etag ? { etag } : {}),@@ -74,3 +82,29 @@ export const GET = withSessionRoute(async (request, { id: sessionId, user }) =>},})})++export async function GET(request: Request): Promise<Response> {+ return reportFrameError(request, await serveFrame(request))+}++// A frame cannot read a JSON error, so a failed document reports its status to the+// preview that loaded it (components/preview-pane.tsx). Programmatic callers keep JSON.+function reportFrameError(request: Request, response: Response): Response {+ if (response.status < 400 || request.headers.get('sec-fetch-dest') !== 'iframe'+ || new URL(request.url).searchParams.get('format') === 'json') return response+ // The status is the only value in the script; the body never carries session or user data.+ const nonce = crypto.randomUUID().replaceAll('-', '')+ const headers = new Headers(response.headers)+ headers.delete('content-length')+ headers.set('cache-control', 'private, no-store')+ headers.set('content-type', 'text/html; charset=utf-8')+ headers.set('content-security-policy', `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'self'`)+ headers.set('referrer-policy', 'no-referrer')+ headers.set('x-content-type-options', 'nosniff')+ // The parent asks for the status on mount. A frame can finish loading before that listener exists, so it also posts once on its own.+ const script = `const report=()=>parent.postMessage({type:'fx0-preview-error',protocol:${PREVIEW_PROTOCOL},status:${response.status}},location.origin);`+ + `addEventListener('message',event=>{if(event.source===parent&&event.origin===location.origin&&event.data&&event.data.type==='fx0-preview-status'&&event.data.protocol===${PREVIEW_PROTOCOL})report()});report()`+ return new Response(`<!doctype html><meta charset="utf-8"><title>Design preview unavailable</title><script nonce="${nonce}">${script}</script>`, {+ status: response.status, statusText: response.statusText, headers,+ })+}diff --git a/components/auth-ui.ts b/components/auth-ui.tsindex 36dce86..a020abd 100644--- a/components/auth-ui.ts+++ b/components/auth-ui.ts@@ -34,6 +34,23 @@ export function clearUserStorage() {let authFailure: AuthRouteError | null = nullconst authRequests = new AbortController()+// Shared path that closes the gate for a 401/403: fetchUi calls it for a JSON response,+// and the preview calls it for a frame that failed with that status (components/preview-pane.tsx).+// signOutAccount closes the gate directly, with its own synthetic 401.+export function signalAuthRequired(status: 401 | 403): AuthRouteError {+ if (authFailure) return authFailure+ const error = new AuthRouteError(status)+ authFailure = error+ window.dispatchEvent(new CustomEvent(AUTH_REQUIRED_EVENT, { detail: error.status }))+ return error+}++// The gate's current error, with no side effects: a full document load checks it before+// it starts, since a document load does not go through fetchUi.+export function uiAuthError(): AuthRouteError | null {+ return authFailure+}+export async function fetchUi(input: string, init?: RequestInit): Promise<Response> {if (authFailure) throw authFailureconst signal = init?.signal ? AbortSignal.any([init.signal, authRequests.signal]) : authRequests.signal@@ -43,13 +60,10 @@ export async function fetchUi(input: string, init?: RequestInit): Promise<Responthrow authFailure}if (response.status === 401 || response.status === 403) {- const error = new AuthRouteError(response.status)- authFailure = errorvoid response.body?.cancel().catch(() => {})- window.dispatchEvent(new CustomEvent(AUTH_REQUIRED_EVENT, { detail: error.status }))// Keep the app visible. The prompt gate owns the optional sign-in dialog;// a background request must never navigate away or discard an unsent draft.- throw error+ throw signalAuthRequired(response.status)}return response}diff --git a/components/preview-pane.tsx b/components/preview-pane.tsxindex a4e270d..b6748db 100644--- a/components/preview-pane.tsx+++ b/components/preview-pane.tsx@@ -5,8 +5,8 @@ import { designLinkUrl } from '../lib/design-link'import { EMPTY_DRAFT_DOCUMENT, patchDraftDocument } from '../lib/draft-preview'import { CAPTURE_PAINT_MS, CAPTURE_PREVIEW_START_MS, type CaptureFailure } from '../lib/capture-protocol'import { captureFrame, reportCaptureFailure, sendCapture, type CaptureRequest } from './design-capture'-import { PREVIEW_PREPARE_MS, PREVIEW_PROTOCOL, type PreviewPayload } from '../lib/preview-update'-import { AuthRouteError, fetchUi } from './auth-ui'+import { isPreviewErrorStatus, PREVIEW_PREPARE_MS, PREVIEW_PROTOCOL, type PreviewPayload } from '../lib/preview-update'+import { AuthRouteError, fetchUi, signalAuthRequired, uiAuthError } from './auth-ui'import DesignLinkDialog from './design-link-dialog'import { HowItWorksPanel } from './how-it-works'@@ -192,6 +192,12 @@ export default function PreviewPane({}if (loading != null) watchLoad(loading)const loadFull = (revision: number) => {+ // A document load does not pass through fetchUi, so it honors the same closed gate here.+ const blocked = uiAuthError()+ if (blocked) {+ fail(blocked.message)+ return+ }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@@ -208,6 +214,11 @@ export default function PreviewPane({const pump = async () => {if (!active() || !desired || error || attempt || loading != null || capturingScope.current === scope) returnconst shown = front == null ? null : slots[front]+ // Nothing is on screen yet, so the document itself is the first paint: no JSON round trip.+ if (!shown) {+ loadFull(desired)+ return+ }// A legacy wrapper can confirm a full load, but cannot advertise hot updates.if (shown && (shown.appliedRevision ?? shown.requestedRevision) >= desired) returnconst next: PreviewAttempt = {@@ -336,6 +347,15 @@ export default function PreviewPane({setLinkRequest((current) => current ?? { scope, url })return}+ if (data.type === 'fx0-preview-error') {+ // Only the frame being loaded can fail the preview; a shown design keeps its place.+ if (index !== loading || data.protocol !== PREVIEW_PROTOCOL || !isPreviewErrorStatus(data.status)) return+ clearLoading()+ fail(data.status === 401 || data.status === 403 ? signalAuthRequired(data.status).message+ : data.status === 404 ? 'This design is not available. Try again.'+ : 'The design could not be loaded. Try again.')+ return+ }if (data.type === 'fx0-preview-result') {const posted = attempt?.postedif (!posted || index !== front || posted.index !== index || data.protocol !== PREVIEW_PROTOCOLdiff --git a/lib/preview-update.ts b/lib/preview-update.tsindex de98bc0..0509a9b 100644--- a/lib/preview-update.ts+++ b/lib/preview-update.ts@@ -1,6 +1,11 @@export const PREVIEW_PROTOCOL = 1export const PREVIEW_PREPARE_MS = 10_000+// The HTTP status a failed preview frame reports (app/api/artifact-frame/route.ts).+export function isPreviewErrorStatus(value: unknown): value is number {+ return typeof value === 'number' && Number.isInteger(value) && value >= 400 && value <= 599+}+export interface PreviewPayload {protocol: 1sessionId: stringdiff --git a/tests/auth-ui.test.mjs b/tests/auth-ui.test.mjsindex 694d65b..46f8902 100644--- a/tests/auth-ui.test.mjs+++ b/tests/auth-ui.test.mjs@@ -72,6 +72,57 @@ test('403 requests reauthorization without login navigation or repeated requestsassert.equal(events[0].detail, 403)})+test('a failed preview frame opens the same gate once, and later requests reuse its error', async (t) => {+ const ui = await loadUi()+ const { events } = browser(t)+ const fetch = t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 200 }))+ const first = ui.signalAuthRequired(401)+ assert.ok(first instanceof ui.AuthRouteError)+ assert.equal(first.status, 401)+ assert.equal(ui.signalAuthRequired(403), first)+ await assert.rejects(ui.fetchUi('/api/prompt'), (error) => error === first)+ assert.equal(fetch.mock.callCount(), 0)+ assert.deepEqual(events.map((event) => [event.type, event.detail]), [[ui.AUTH_REQUIRED_EVENT, 401]])+})++test('a fetch 403 and a later frame signal share one gate error without a second event', async (t) => {+ const ui = await loadUi()+ const { events } = browser(t)+ t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 403 }))+ const fetched = await ui.fetchUi('/api/sessions').catch((error) => error)+ assert.equal(fetched.status, 403)+ assert.equal(ui.signalAuthRequired(401), fetched)+ assert.deepEqual(events.map((event) => [event.type, event.detail]), [[ui.AUTH_REQUIRED_EVENT, 403]])+})++test('uiAuthError is null while open, then the same error for frame and fetch signals, with no extra event', async (t) => {+ const ui = await loadUi()+ const { events } = browser(t)+ const fetch = t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 403 }))+ assert.equal(ui.uiAuthError(), null)+ assert.equal(events.length, 0, 'reading the gate dispatches nothing')+ const frame = ui.signalAuthRequired(401)+ assert.equal(ui.uiAuthError(), frame)+ assert.equal(ui.signalAuthRequired(403), frame)+ const fetched = await ui.fetchUi('/api/prompt').catch((error) => error)+ assert.equal(fetched, frame, 'a fetch after the gate closed reuses the frame error')+ assert.equal(ui.uiAuthError(), frame)+ assert.equal(fetch.mock.callCount(), 0)+ assert.deepEqual(events.map((event) => [event.type, event.detail]), [[ui.AUTH_REQUIRED_EVENT, 401]])+})++test('a fetch 403 closes the gate for uiAuthError, and a later frame signal reuses that error', async (t) => {+ const ui = await loadUi()+ const { events } = browser(t)+ t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 403 }))+ assert.equal(ui.uiAuthError(), null)+ const fetched = await ui.fetchUi('/api/sessions').catch((error) => error)+ assert.equal(ui.uiAuthError(), fetched)+ assert.equal(ui.signalAuthRequired(401), fetched)+ assert.equal(ui.uiAuthError(), fetched)+ assert.deepEqual(events.map((event) => [event.type, event.detail]), [[ui.AUTH_REQUIRED_EVENT, 403]])+})+test('ordinary API errors stay with the owning UI and do not close the auth gate', async (t) => {const ui = await loadUi()const { events } = browser(t)diff --git a/tests/preview-update.browser.mjs b/tests/preview-update.browser.mjsindex 7ed93c9..7121d83 100644--- a/tests/preview-update.browser.mjs+++ b/tests/preview-update.browser.mjs@@ -2,7 +2,7 @@ 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 { mkdir, 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'@@ -22,6 +22,19 @@ const CHROME = process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Conteconst PIXEL = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')const SESSION = 'preview-browser-session'const TOKEN = 'preview-browser-ready'+// Opt-in experiment only (FX0_PREVIEW_PERF=1): it replaces the regular cases with a perf comparison.+const PERF = process.env.FX0_PREVIEW_PERF === '1'+// Restore the old JSON-first behavior only in a temporary baseline compile. The candidate+// runs the current production component unchanged; no benchmark switch enters production.+const LEGACY_BASELINE = {+ marker: 'fx0-perf-baseline-json-first',+ from: 'if (!shown) {\n loadFull(desired);\n return;\n }',+ to: '/* fx0-perf-baseline-json-first */',+}+const median = values => {+ const sorted = values.filter(Number.isFinite).sort((a, b) => a - b), middle = sorted.length >> 1+ return sorted.length === 0 ? null : sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2+}function design({ color = 'rgb(10, 20, 30)', title = 'Original title', padding = 4, image = '', photo = false, program = 'original', structure = '', beforeLoad = '', sheetId = true } = {}) {return `<!doctype html><html><head><title>Interactive presentation</title>@@ -75,15 +88,16 @@ function payload(revision, html, imageName) {// Observe real window messages without intercepting any production listener or send.const OBSERVER = `-window.observed = { paints: [], results: [], boots: [], reports: [], errors: [] }+window.observed = { paints: [], results: [], boots: [], reports: [], errors: [], frameErrors: [] }addEventListener('message', event => {const frames = [...document.querySelectorAll('#active, #preview-pane iframe')], data = event.dataif (!data || typeof data !== 'object') returnconst wrapper = frames.find(frame => event.source === frame.contentWindow)if (wrapper && event.origin === location.origin) {- const entry = { ...data, mountUrl: wrapper.getAttribute('src') }+ const entry = { ...data, mountUrl: wrapper.getAttribute('src'), observedAt: performance.now() }if (data.type === 'fx0-artifact-painted') observed.paints.push(entry)if (data.type === 'fx0-preview-result') observed.results.push(entry)+ if (data.type === 'fx0-preview-error') observed.frameErrors.push(entry)}const frame = frames.find(frame => event.source === frame.contentWindow.frames[0])if (frame && data.fixture === 'preview-update') {@@ -103,7 +117,7 @@ window.mount = url => {}</script></body></html>`-async function buildPaneFixture(directory) {+async function buildPaneFixture(directory, experiment = null) {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'),@@ -111,25 +125,34 @@ async function buildPaneFixture(directory) {'--jsx', 'react-jsx', '--target', 'esnext', '--module', 'esnext','--moduleResolution', 'bundler', '--skipLibCheck', '--esModuleInterop', 'components/preview-pane.tsx',], { cwd: root, maxBuffer: 4 * 1024 * 1024 })+ if (experiment) {+ // Perf-only: remove the direct-load guard in the temporary legacy baseline, never in production.+ const file = join(output, 'compiled/components/preview-pane.js'), source = await readFile(file, 'utf8')+ assert.equal(source.split(experiment.from).length - 1, 1, 'the baseline matches exactly one compiled guard')+ await writeFile(file, source.replace(experiment.from, experiment.to))+ assert.equal((await readFile(file, 'utf8')).split(experiment.marker).length - 1, 1, 'the baseline marker is unique')+ }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'+import { signalAuthRequired } from './compiled/components/auth-ui.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), [capture, setCapture] = useState(null)useEffect(() => {window.captureResults = []- Object.assign(window, { setRevision, setViewing, setSession, setDraft, setAccessAllowed, setCapture, fixtureReady: true })- const revoke = () => { setAccessAllowed(false); setRevision(0) }+ window.authErrors = []+ Object.assign(window, { setRevision, setViewing, setSession, setDraft, setAccessAllowed, setCapture, closeAuthGate: signalAuthRequired, fixtureReady: true })+ const revoke = event => { window.authErrors.push(event.detail); 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),- capture, onCaptureDone: (cid, answered) => { window.captureResults.push({ cid, answered }); setCapture(current => current?.cid === cid ? null : current) },+ capture, onCaptureDone: (cid, answered) => { window.captureResults.push({ cid, answered, observedAt: performance.now() }); setCapture(current => current?.cid === cid ? null : current) },})}`)await writeFile(join(output, 'pane-entry.js'), `@@ -253,7 +276,7 @@ async function connectCdp(url, errors) {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 => {+test('in Chrome, the production preview wrapper and React PreviewPane preserve state, reload safely and recover', { timeout: PERF ? 200_000 : 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 = []@@ -262,14 +285,22 @@ test('in Chrome, the production preview wrapper and React PreviewPane preserve sconst largeImage = Buffer.alloc(Math.floor(1.1 * 1024 * 1024), 0x41)PIXEL.copy(largeImage)const paneArtifacts = new Map(), paneLatest = new Map(), paneModes = new Map(), paneRequests = [], paneHeld = [], paneHtmlHeld = [], bundleHeld = [], paneCaptures = []- let paneFixture, holdBundle = true+ let paneFixture, holdBundle = true, artifactDelayMs = 0let origin, chrome, cdp, chromeError = '', frameNumber = 0, requestNumber = 0, offRouteHits = 0const 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, { relay: DESIGN_CAPTURE_RELAY, script: designCaptureScript }))}- const server = http.createServer((request, response) => {+ // Model the frame-error response contract; the real route and its script are covered+ // independently in route-security.test.mjs, including the nonce and status handshake.+ const sendFrameError = (response, status) => {+ const nonce = randomBytes(16).toString('hex')+ response.writeHead(status, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'private, no-store',+ 'content-security-policy': `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'self'` })+ response.end(`<!doctype html><script nonce="${nonce}">const report=()=>parent.postMessage({type:'fx0-preview-error',protocol:1,status:${status}},location.origin);addEventListener('message',event=>{if(event.source===parent&&event.origin===location.origin&&event.data?.type==='fx0-preview-status'&&event.data.protocol===1)report()});report()</script>`)+ }+ const route = (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) {@@ -294,13 +325,17 @@ test('in Chrome, the production preview wrapper and React PreviewPane preserve sconst revision = url.searchParams.has('revision') ? wanted : paneLatest.get(session)const preview = paneArtifacts.get(`${session}:${revision}`), json = url.searchParams.get('format') === 'json'paneRequests.push({ session, wanted, revision, json })- if (!preview) return response.writeHead(404, { 'content-type': 'application/json' }).end('{"error":"No local design"}')const mode = paneModes.get(`${session}:${wanted}`)+ const staleFrame = !json && !url.searchParams.has('revision') && Number.isSafeInteger(wanted) && wanted > 0 && revision < wanted+ const failure = typeof mode === 'number' ? mode : mode === 'error' ? 503 : !preview || staleFrame ? 404 : null+ if (failure) {+ if (!json) return sendFrameError(response, failure)+ return response.writeHead(failure, { 'content-type': 'application/json', 'cache-control': 'private, no-store' }).end('{"error":"Local failure"}')+ }if (!json) {if (mode === 'hold-html') return void paneHtmlHeld.push({ response, preview })return sendFrame(response, preview)}- if (mode === 'error') return response.writeHead(503, { 'content-type': 'application/json' }).end('{"error":"Local failure"}')// Only the external snapshot/data source is simulated. JSON never mounts or// executes a candidate; the real React effect decides what to do with it.const text = JSON.stringify(preview)@@ -331,6 +366,11 @@ test('in Chrome, the production preview wrapper and React PreviewPane preserve sif (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()+ }+ // Perf-only synthetic latency: the artifact frame's HTML and JSON are delayed; every other route is immediate.+ const server = http.createServer((request, response) => {+ if (artifactDelayMs && new URL(request.url, 'http://fixture').pathname === '/api/artifact-frame') setTimeout(route, artifactDelayMs, request, response)+ else route(request, response)})try {await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })@@ -393,6 +433,110 @@ test('in Chrome, the production preview wrapper and React PreviewPane preserve s}const noErrors = async () => { assert.deepEqual(errors, []); assert.deepEqual((await observed()).errors, []) }+ // Perf-only (FX0_PREVIEW_PERF=1): first publish and one compatible hot update in the real+ // PreviewPane, for the baseline compile and the experimental candidate. Every duration is+ // read from this page's performance.now (or Date.now) clock; the host only waits, never times.+ // Mock excludes auth, Redis, model providers and generation; the delay is synthetic.+ if (PERF) {+ const J = JSON.stringify, fixtures = {}+ for (const [name, experiment] of [['baseline', LEGACY_BASELINE], ['candidate', null]]) {+ await mkdir(join(dir, name))+ fixtures[name] = await buildPaneFixture(join(dir, name), experiment)+ }+ holdBundle = false+ // Fetch the page, bundle and frames on every sample rather than from Chrome's HTTP cache.+ await cdp.call('Network.enable'); await cdp.call('Network.setCacheDisabled', { cacheDisabled: true })+ const frontSelector = '#preview-pane iframe[title="Design artifact preview"]:not([aria-hidden="true"])'+ const frontCount = () => evaluate("document.querySelectorAll('#preview-pane iframe').length")+ const paneState = () => evaluate(`(() => { const frame = document.querySelector(${J(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 }, 'perf PreviewPane state')+ const publish = (session, revision, options) => {+ paneArtifacts.set(`${session}:${revision}`, { ...payload(revision, design(options)), sessionId: session })+ paneLatest.set(session, revision)+ }+ // The seeded session bootstraps real SSR and hydration; each sample then starts a new chat.+ publish(SESSION, 101, { title: 'Seed design' })+ const METRICS = ['publishToReadyMs', 'readyToCaptureDoneMs', 'publishToCaptureDoneMs', 'uploadLagMs', 'previewWaitMs', 'libraryMs', 'encodeMs', 'jsonDurationMs', 'htmlDurationMs', 'jsonRequests', 'htmlRequests']+ // One publish: the prop change, the screenshot request in the same turn, then ready and capture-done times.+ const phase = async (session, revision, options) => {+ const cid = `${session}-${revision}`, mark = paneRequests.length+ publish(session, revision, options)+ await evaluate(`{ window.frontBefore = document.querySelector(${J(frontSelector)}); window.captureUploads = []; performance.clearResourceTimings(); window.publishAt = performance.now(); setRevision(${revision}); setCapture({ cid: ${J(cid)}, revision: ${revision}, sessionId: ${J(session)}, receivedAt: Date.now() }) }`)+ // The first paint (no confirmed document) or the applied acknowledgement (hot update), whichever arrives.+ const ready = await until(() => evaluate(`[...observed.paints, ...observed.results].find(e => e.sessionId === ${J(session)} && e.revision === ${revision} && (e.type === 'fx0-preview-result' ? e.status === 'applied' : e.updateReady === true)) ?? null`), `${cid} ready`, 20_000)+ const captured = await until(() => evaluate(`captureResults.find(r => r.cid === ${J(cid)}) ?? null`), `${cid} capture done`, 20_000)+ const page = await evaluate(`({ publishAt: window.publishAt, sameFront: window.frontBefore != null && window.frontBefore === document.querySelector(${J(frontSelector)}), uploads: window.captureUploads.slice(),+ resources: performance.getEntriesByType('resource').filter(e => e.name.includes('/api/artifact-frame')).map(e => ({ kind: new URL(e.name).searchParams.has('format') ? 'json' : 'html', initiatorType: e.initiatorType, durationMs: e.duration, waitMs: e.responseStart - e.requestStart, transferMs: e.responseEnd - e.responseStart })) })`)+ const shot = paneCaptures.find(capture => capture.cid === cid)+ assert.ok(shot, `${cid} reached /api/capture`)+ assert.equal(shot.failed, null, `${cid} uploaded a photo`)+ assert.equal(shot.images.length, 1)+ assert.equal(captured.answered, true)+ const requests = paneRequests.slice(mark).filter(request => request.session === session), upload = page.uploads.at(-1)+ const resource = kind => page.resources.find(entry => entry.kind === kind)+ return {+ readyEvent: ready.type === 'fx0-preview-result' ? 'applied' : 'paint', documentId: ready.documentId ?? null, sameFront: page.sameFront,+ publishToReadyMs: ready.observedAt - page.publishAt, readyToCaptureDoneMs: captured.observedAt - ready.observedAt,+ publishToCaptureDoneMs: captured.observedAt - page.publishAt, uploadLagMs: upload ? upload.headersAt - upload.start : null,+ previewWaitMs: shot.timing.previewWaitMs, libraryMs: shot.timing.frame?.libraryMs ?? null, encodeMs: shot.timing.frame?.encodeMs ?? null,+ jsonDurationMs: resource('json')?.durationMs ?? null, htmlDurationMs: resource('html')?.durationMs ?? null,+ jsonRequests: requests.filter(request => request.json).length, htmlRequests: requests.filter(request => !request.json).length,+ requestOrder: requests.map(request => (request.json ? 'json' : 'html')), resources: page.resources,+ }+ }+ const sample = async (variant, delay, index) => {+ const session = `perf-${variant}-${delay}-${index}-${randomBytes(4).toString('hex')}`+ artifactDelayMs = delay+ paneFixture = fixtures[variant]+ await cdp.call('Page.navigate', { url: `${origin}/pane` })+ await until(() => evaluate('window.fixtureReady === true'), 'perf hydration', 20_000)+ await until(() => evaluate(`observed.paints.some(p => p.sessionId === ${J(SESSION)} && p.revision === 101 && p.updateReady === true)`), 'perf seeded SSR paint', 20_000)+ // Shadow the production fetch only to timestamp the capture upload's response headers.+ await evaluate(`{ window.captureUploads = []; const send = window.fetch; window.fetch = (input, init) => { const url = String(input?.url ?? input); if (!url.includes('/api/capture')) return send(input, init); const start = performance.now(); return send(input, init).then(response => { window.captureUploads.push({ start, headersAt: performance.now() }); return response }) } }`)+ // A new chat: no frame until its first publish, then a patch that keeps the same confirmed document.+ await evaluate(`setSession(${J(session)}); setRevision(0)`)+ await until(async () => await frontCount() === 0, 'perf new chat has no preview frame')+ const initial = await phase(session, 1, { title: 'Perf first design' })+ assert.deepEqual(initial.requestOrder, variant === 'baseline' ? ['json', 'html'] : ['html'], `${variant} initial artifact requests`)+ await interact()+ const before = await waitPane(s => s.scroll === 900 && s.focused), boots = (await observed()).boots.length+ const update = await phase(session, 2, { color: 'rgb(90, 80, 70)', title: 'Perf edited title', padding: 12 })+ preserved(before, await waitPane(s => s.title === 'Perf edited title' && s.color === 'rgb(90, 80, 70)' && s.padding === '12px'))+ assert.deepEqual(update.requestOrder, ['json'], `${variant} hot update requests JSON only`)+ assert.equal(update.documentId, initial.documentId, 'the hot update keeps the first document')+ assert.equal(update.sameFront, true, 'the front frame node is not replaced')+ assert.equal(await frontCount(), 1)+ assert.equal((await observed()).boots.length, boots, 'no document reload or script restart')+ return { variant, artifactDelayMs: delay, index, session, initial, update }+ }+ const samples = []+ for (const delay of [0, 150]) {+ for (let index = 0; index < 5; index++) {+ // Alternate the order so drift affects both variants alike.+ for (const variant of index % 2 ? ['candidate', 'baseline'] : ['baseline', 'candidate']) samples.push(await sample(variant, delay, index))+ }+ }+ artifactDelayMs = 0+ await noErrors()+ const cells = {}+ for (const sample of samples) {+ const cell = cells[`${sample.variant}@${sample.artifactDelayMs}ms`] ??= { n: 0, initial: {}, update: {} }+ cell.n+++ for (const phaseName of ['initial', 'update']) for (const metric of METRICS) (cell[phaseName][metric] ??= []).push(sample[phaseName][metric])+ }+ for (const cell of Object.values(cells)) for (const phaseName of ['initial', 'update']) for (const metric of METRICS) cell[phaseName][metric] = median(cell[phaseName][metric])+ const report = {+ kind: 'fx0-preview-perf', candidate: { id: 'first-load-html-only', status: 'current production source, local verification', baselineRemoves: LEGACY_BASELINE.from },+ chrome: (await (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(8000) })).json()).Browser, node: process.version,+ synthetic: { artifactFrameDelayMs: [0, 150], delayed: 'HTML and JSON of /api/artifact-frame', notMeasured: ['production auth', 'Redis', 'model provider', 'generation', 'real network'], uploadEndpoint: 'local mock /api/capture without storage' },+ clocks: 'Browser performance.now for ready and capture boundaries; Date.now for previewWait (same browser clock); upload lag from the browser fetch promise',+ samples, cells,+ }+ if (process.env.FX0_PREVIEW_PERF_OUT) await writeFile(process.env.FX0_PREVIEW_PERF_OUT, JSON.stringify(report, null, 2))+ console.log(`FX0_PREVIEW_PERF_RESULT ${JSON.stringify(report)}`)+ return+ }+// Fail once, rather than running every case against a legacy three-argument wrapper.let paint = await mounted(payload(1, design({ photo: true })))@@ -936,6 +1080,7 @@ test('in Chrome, the production preview wrapper and React PreviewPane preserve sawait 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.deepEqual(paneRequests.filter(r => r.session === otherSession && r.wanted === 1).map(r => r.json ? 'json' : 'html'), ['html'], 'a first load goes straight to HTML')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.@@ -959,21 +1104,21 @@ test('in Chrome, the production preview wrapper and React PreviewPane preserve sawait 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.+ // With no confirmed document, an initial HTML failure is recoverable via+ // the component's own Retry button, without a JSON preflight.publish(2, { program: 'initial retry', title: 'Initial failure recovered' }, otherSession)paneModes.set(`${otherSession}:2`, 'error')const htmlBeforeInitialError = htmlCount(), bootsBeforeInitialError = (await observed()).boots.lengthawait 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)+ assert.equal(htmlCount(), htmlBeforeInitialError + 1)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(htmlCount(), htmlBeforeInitialError + 2)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(paneRequests.filter(r => r.session === otherSession && r.wanted === 2 && r.json).length, 0)assert.equal(await status(), '')await noErrors()} catch (error) {@@ -988,6 +1133,114 @@ test('in Chrome, the production preview wrapper and React PreviewPane preserve s}})+ for (const firstLoad of ['client', 'pre-hydration SSR']) {+ for (const code of [401, 403, 404, 422, 503]) {+ await t.test(`${firstLoad} HTML ${code} reports errors without a JSON preflight`, async () => {+ paneFixture ??= await buildPaneFixture(dir)+ const session = firstLoad === 'client' ? `first-load-${code}` : SESSION+ const revision = firstLoad === 'client' ? 1 : 101+ const key = `${session}:${revision}`+ paneArtifacts.set(`${SESSION}:101`, payload(101, design({ program: 'error baseline' })))+ paneLatest.set(SESSION, 101)+ paneArtifacts.set(key, payload(revision, design({ program: `recovered ${code}` }), session))+ paneLatest.set(session, revision)+ if (firstLoad !== 'client') paneModes.set(key, code)+ const start = paneRequests.length+ const countFrames = () => evaluate("document.querySelectorAll('#preview-pane iframe').length")+ const status = () => evaluate("document.querySelector('#preview-pane [role=status]')?.textContent ?? ''")+ try {+ holdBundle = firstLoad !== 'client'+ await cdp.call('Page.navigate', { url: `${origin}/pane` })+ if (holdBundle) {+ await until(async () => (await observed()).frameErrors.some(error => error.status === code), 'SSR error arrived before hydration')+ assert.equal(await evaluate('window.fixtureReady === true'), false)+ 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'), 'error fixture hydration')+ if (firstLoad === 'client') {+ await until(async () => (await observed()).paints.some(paint => paint.revision === 101), 'healthy bootstrap before a new scope')+ paneModes.set(key, code)+ await evaluate(`setSession(${JSON.stringify(session)}); setRevision(${revision})`)+ }+ if (code === 401 || code === 403) {+ await until(() => evaluate(`window.authErrors.includes(${code})`), 'frame error closes the shared auth gate')+ assert.deepEqual(await evaluate('window.authErrors'), [code], 'status replies cannot dispatch duplicate auth errors')+ } else {+ await until(async () => (await status()).includes(code === 404 ? 'not available' : 'could not be loaded'), 'frame error is immediately retryable')+ }+ await until(async () => await countFrames() === 0, 'failed and revoked private frames are removed')+ const requests = () => paneRequests.slice(start).filter(request => request.session === session && request.wanted === revision)+ assert.deepEqual(requests().map(request => request.json ? 'json' : 'html'), ['html'])+ if (code === 401 || code === 403) {+ await sleep(50)+ assert.equal(await countFrames(), 0, 'late frame replies do not revive revoked access')+ assert.equal(requests().length, 1)+ } else {+ paneModes.delete(key)+ await evaluate("[...document.querySelectorAll('#preview-pane button')].find(button => button.textContent === 'Retry preview').click()")+ await until(async () => (await observed()).boots.some(boot => boot.program === `recovered ${code}`), 'Retry loads the corrected response')+ await until(async () => await countFrames() === 1 && await status() === '', 'Retry confirms one healthy frame')+ assert.deepEqual(requests().map(request => request.json ? 'json' : 'html'), ['html', 'html'])+ }+ await noErrors()+ } finally {+ paneModes.delete(key)+ holdBundle = false+ for (const response of bundleHeld.splice(0)) response.destroy()+ }+ })+ }+ }++ await t.test('a closed client auth gate blocks the first HTML request even when access props are stale', async () => {+ paneFixture ??= await buildPaneFixture(dir)+ paneArtifacts.set(`${SESSION}:101`, payload(101, design({ program: 'auth gate baseline' })))+ paneLatest.set(SESSION, 101)+ const session = 'auth-gate-must-not-load'+ paneArtifacts.set(`${session}:1`, payload(1, design({ program: 'must not bypass client auth gate' }), session))+ paneLatest.set(session, 1) // The external backend would return 200 if incorrectly requested.+ await cdp.call('Page.navigate', { url: `${origin}/pane` })+ await until(() => evaluate('window.fixtureReady === true'), 'closed-gate fixture hydration')+ await until(async () => (await observed()).paints.some(paint => paint.revision === 101), 'closed-gate fixture bootstrap')+ await evaluate('closeAuthGate(401)')+ await until(() => evaluate("document.querySelectorAll('#preview-pane iframe').length === 0"), 'auth revocation clears the old frame')+ const start = paneRequests.length+ await evaluate(`setSession(${JSON.stringify(session)}); setRevision(1); setAccessAllowed(true)`)+ await until(() => evaluate("document.querySelector('#preview-pane [role=status]')?.textContent.includes('session has expired')"), 'the independent auth gate still blocks navigation')+ assert.equal(paneRequests.length, start, 'neither HTML nor JSON can leave the closed gate')+ assert.equal(await evaluate("document.querySelectorAll('#preview-pane iframe').length"), 0)+ assert.deepEqual(await evaluate('window.authErrors'), [401])+ assert.equal((await observed()).boots.some(boot => boot.program === 'must not bypass client auth gate'), false)+ await noErrors()+ })++ await t.test('a stale first HTML load never runs the old design and Retry fetches the requested version', async () => {+ paneFixture ??= await buildPaneFixture(dir)+ const session = 'stale-first-load'+ paneArtifacts.set(`${SESSION}:101`, payload(101, design({ program: 'stale test baseline' })))+ paneLatest.set(SESSION, 101)+ paneArtifacts.set(`${session}:1`, payload(1, design({ program: 'must never run stale design' }), session))+ paneLatest.set(session, 1)+ await cdp.call('Page.navigate', { url: `${origin}/pane` })+ await until(() => evaluate('window.fixtureReady === true'), 'stale fixture hydration')+ await until(async () => (await observed()).paints.some(paint => paint.revision === 101), 'stale fixture bootstrap')+ const start = paneRequests.length+ await evaluate(`setSession(${JSON.stringify(session)}); setRevision(2)`)+ const status = () => evaluate("document.querySelector('#preview-pane [role=status]')?.textContent ?? ''")+ await until(async () => (await status()).includes('not available'), 'a stale source fails without waiting for the paint deadline')+ assert.equal((await observed()).boots.some(boot => boot.program === 'must never run stale design'), false)+ assert.deepEqual(paneRequests.slice(start).map(request => request.json ? 'json' : 'html'), ['html'])+ paneArtifacts.set(`${session}:2`, payload(2, design({ program: 'requested fresh design' }), session))+ paneLatest.set(session, 2)+ await evaluate("[...document.querySelectorAll('#preview-pane button')].find(button => button.textContent === 'Retry preview').click()")+ await until(async () => (await observed()).paints.some(paint => paint.revision === 2), 'fresh revision paints after Retry')+ assert.equal((await observed()).boots.some(boot => boot.program === 'requested fresh design'), true)+ assert.deepEqual(paneRequests.slice(start).map(request => request.json ? 'json' : 'html'), ['html', 'html'])+ assert.equal(await status(), '')+ await noErrors()+ })+await t.test('a loaded replacement survives background time while a genuinely visible load still has a deadline', async () => {paneFixture ??= await buildPaneFixture(dir)holdBundle = falsediff --git a/tests/route-security.test.mjs b/tests/route-security.test.mjsindex ae6a940..26e80e1 100644--- a/tests/route-security.test.mjs+++ b/tests/route-security.test.mjs@@ -2,6 +2,7 @@ import assert from 'node:assert/strict'import test from 'node:test'import { registerHooks } from 'node:module'import { readFileSync } from 'node:fs'+import vm from 'node:vm'import babel from 'next/dist/compiled/babel/core.js'import presetTypescript from 'next/dist/compiled/babel/preset-typescript.js'import presetReact from 'next/dist/compiled/babel/preset-react.js'@@ -73,7 +74,7 @@ const mocks = {}`,'lib/history.ts': `- export async function readGeneration() { globalThis.securityTest.trace.push('history'); return null; }+ export async function readGeneration() { const s = globalThis.securityTest; s.trace.push('history'); return s.generationHtml ?? null; }export async function recordTurn() { return true; }export async function recordGeneration() { return true; }`,@@ -110,7 +111,7 @@ const mocks = {export async function readDesignArtifact(id) { record('artifact', id); return '<!doctype html><html><head><title>private design</title></head><body>private artifact</body></html>'; }export async function readDesignArtifactAt(id) {const s = record('artifact', id);- return { html: s.liveRevision === 0 ? null : '<!doctype html><html><head><title>private design</title></head><body>private artifact</body></html>', revision: s.liveRevision ?? 1 };+ return { html: s.liveHtml ?? (s.liveRevision === 0 ? null : '<!doctype html><html><head><title>private design</title></head><body>private artifact</body></html>'), revision: s.liveRevision ?? 1 };}export async function currentSeq(id) { record('seq', id); return 0; }export async function acknowledgeCapture(id) { record('capture-ack', id); return true; }@@ -721,6 +722,159 @@ test('preview JSON uses the same ownership boundary and refuses missing artifactassert.equal((await routes['artifact-frame'].GET(request('artifact-frame', 'GET', `${own}&format=unknown`))).status, 400)})+const frameRequest = (query = '', headers = {}) => {+ const req = request('artifact-frame', 'GET', own, undefined, 'null')+ return new Request(`${req.url}${query}`, { headers: { ...Object.fromEntries(req.headers), ...headers } })+}+const reportsStatus = (status) => new RegExp(`parent\\.postMessage\\(\\{type:'fx0-preview-error',protocol:1,status:${status}\\},location\\.origin\\)`)++test('a failed preview frame reports its status by message and keeps its headers and session cookies', async () => {+ process.env.SESSION_SECRET ??= 'deterministic-route-security-secret-32+'+ const { grantCookieName } = await import('../lib/auth-protocol.ts')+ const s = reset({ session: null })+ const stale = `${grantCookieName('c'.repeat(32))}=expired`+ const response = await routes['artifact-frame'].GET(frameRequest('', { 'sec-fetch-dest': 'iframe', cookie: stale }))+ assert.equal(response.status, 401)+ assert.match(response.headers.get('content-type'), /^text\/html; charset=utf-8/)+ assert.equal(response.headers.get('cache-control'), 'private, no-store')+ assert.equal(response.headers.get('x-content-type-options'), 'nosniff')+ assert.equal(response.headers.get('referrer-policy'), 'no-referrer')+ assert.equal(response.headers.get('content-length'), null)+ // The session renewal that the wrapper itself adds to every response survives the rewrap.+ assert.ok(response.headers.getSetCookie().some((cookie) => cookie.startsWith(`${grantCookieName('c'.repeat(32))}=`)))+ const html = await response.text()+ const nonce = /<script nonce="([0-9a-f]{32})">/.exec(html)?.[1]+ assert.ok(nonce)+ assert.equal(response.headers.get('content-security-policy'), `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'self'`)+ assert.match(html, reportsStatus(401))+ assert.doesNotMatch(html, new RegExp(`${own}|user-token|secret-refresh|${grantCookieName('c'.repeat(32))}`))+ // Signed out: only the session read runs; no ownership query, journal read, history read or runtime work.+ assert.deepEqual(s.trace.filter((step) => step !== 'auth'), [])+ assert.deepEqual(s.queries, [])+ assert.deepEqual(s.redisReads, [])+})++test('frame errors keep their statuses; healthy, revalidated and JSON responses are unchanged', async () => {+ const frame = { 'sec-fetch-dest': 'iframe' }+ const cases = [+ ['missing design', '', { liveRevision: 0 }, 404],+ ['unrenderable design', '', { liveHtml: '<p>no doctype</p>' }, 422],+ ['unknown format', '&format=unknown', {}, 400],+ ]+ for (const [name, query, state, status] of cases) {+ reset(state)+ const response = await routes['artifact-frame'].GET(frameRequest(query, frame))+ assert.equal(response.status, status, name)+ assert.match(await response.text(), reportsStatus(status), name)+ }+ reset({ liveHtml: '<p>no doctype</p>' })+ const unprepared = await routes['artifact-frame'].GET(frameRequest(''))+ assert.equal(unprepared.status, 422)+ assert.match(await unprepared.text(), /could not be prepared/)++ reset({ liveRevision: 2 })+ const healthy = await routes['artifact-frame'].GET(frameRequest('&v=2', frame))+ assert.equal(healthy.status, 200)+ const html = await healthy.text()+ assert.doesNotMatch(html, /parent\.postMessage\(\{type:'fx0-preview-error'/)+ const revalidated = await routes['artifact-frame'].GET(frameRequest('&v=2', { ...frame, 'if-none-match': healthy.headers.get('etag') }))+ assert.equal(revalidated.status, 304)+ assert.equal(await revalidated.text(), '')++ reset({ liveRevision: 0 })+ const json = await routes['artifact-frame'].GET(frameRequest('&format=json', frame))+ assert.equal(json.status, 404)+ assert.match(json.headers.get('content-type'), /^application\/json/)+ assert.deepEqual(await json.json(), { error: 'No design artifact.' })+ const programmatic = await routes['artifact-frame'].GET(frameRequest('&format=json', { 'sec-fetch-dest': 'empty' }))+ assert.equal(programmatic.status, 404)+ assert.match(programmatic.headers.get('content-type'), /^application\/json/)+ assert.deepEqual(await programmatic.json(), { error: 'No design artifact.' })+})++test('a failed preview frame answers the parent status handshake only from its own parent, with constant data', async () => {+ reset({ liveRevision: 0 })+ const response = await routes['artifact-frame'].GET(frameRequest('', { 'sec-fetch-dest': 'iframe' }))+ const html = await response.text()+ const [, nonce, script] = /<script nonce="([0-9a-f]{32})">([\s\S]*?)<\/script>/.exec(html)+ assert.equal(response.status, 404)+ assert.equal(response.headers.get('content-security-policy'), `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'self'`)+ // Only the status reaches the script: no session, user, token or design identity.+ assert.doesNotMatch(script, new RegExp(`${own}|session|user|token|secret`))+ const posts = []+ const parent = { postMessage: (message, target) => posts.push([JSON.stringify(message), target]) }+ const listeners = []+ vm.runInNewContext(script, { parent, location: { origin: 'https://fx0.example' }, addEventListener: (type, listener) => listeners.push([type, listener]) })+ const error = JSON.stringify({ type: 'fx0-preview-error', protocol: 1, status: 404 })+ assert.deepEqual(posts, [[error, 'https://fx0.example']], 'the initial post reports the status without waiting')+ const deliver = (data, { source = parent, origin = 'https://fx0.example' } = {}) => {+ for (const [type, listener] of listeners) if (type === 'message') listener({ data, source, origin })+ }+ deliver({ type: 'fx0-preview-status', protocol: 1 })+ assert.deepEqual(posts[1], [error, 'https://fx0.example'], 'the status handshake from the parent is answered')+ deliver({ type: 'fx0-preview-status', protocol: 1 }, { source: {} })+ deliver({ type: 'fx0-preview-status', protocol: 1 }, { origin: 'https://evil.example' })+ deliver({ type: 'fx0-preview-status', protocol: 2 })+ deliver({ type: 'fx0-artifact-open', protocol: 1, url: 'https://example.com' })+ deliver(null)+ assert.equal(posts.length, 2, 'other windows, origins, types and protocols get no answer')+})++test('an iframe asking for a newer revision than is live fails before any design is prepared', async () => {+ const s = reset({ liveRevision: 2 })+ const stale = await routes['artifact-frame'].GET(frameRequest('&v=3', { 'sec-fetch-dest': 'iframe' }))+ assert.equal(stale.status, 404)+ assert.equal(stale.headers.get('etag'), null)+ const html = await stale.text()+ assert.match(html, reportsStatus(404))+ // The wrapper's JSON body is dropped: no design, image marker, runtime or frame remains.+ assert.doesNotMatch(html, /private artifact|frame-root|artifact-image|connect-src|Design artifact preview/)+ assert.equal(stale.headers.get('cache-control'), 'private, no-store')+ // Ownership and sign-in still come first: a signed-out frame answers 401, not the version check.+ reset({ session: null, liveRevision: 2 })+ assert.equal((await routes['artifact-frame'].GET(frameRequest('&v=3', { 'sec-fetch-dest': 'iframe' }))).status, 401)+ assert.equal(s.redisReads.length, 1, 'only the stale request read the journal')+})++test('an iframe asking for the current or a newer revision is served; invalid versions and past revisions are unaffected', async () => {+ for (const [live, v] of [[3, '&v=3'], [4, '&v=3']]) {+ reset({ liveRevision: live })+ const response = await routes['artifact-frame'].GET(frameRequest(v, { 'sec-fetch-dest': 'iframe' }))+ assert.equal(response.status, 200, `live ${live} ${v}`)+ assert.match(await response.text(), /frame-root/)+ }+ reset({ liveRevision: 2 })+ for (const query of ['&v=abc', '&v=0', '&v=-1', '&v=1.5', '']) {+ const response = await routes['artifact-frame'].GET(frameRequest(query, { 'sec-fetch-dest': 'iframe' }))+ assert.equal(response.status, 200, query || 'no v')+ }+ reset({ liveRevision: 2, generationHtml: '<!doctype html><html><head><title>old</title></head><body>old version</body></html>' })+ const past = await routes['artifact-frame'].GET(frameRequest('&revision=1&v=3', { 'sec-fetch-dest': 'iframe' }))+ assert.equal(past.status, 200)+ assert.match(await past.text(), /frame-root/)+})++test('programmatic HTML and JSON keep their current-revision contracts for a newer v', async () => {+ reset({ liveRevision: 2 })+ const html = await routes['artifact-frame'].GET(frameRequest('&v=3', { 'sec-fetch-dest': 'empty' }))+ assert.equal(html.status, 200)+ assert.equal(html.headers.get('cache-control'), 'private, no-store')+ assert.match(await html.text(), /frame-root/)+ const json = await routes['artifact-frame'].GET(frameRequest('&v=3&format=json', { 'sec-fetch-dest': 'iframe' }))+ assert.equal(json.status, 200)+ assert.equal((await json.json()).revision, 2)+ const programmaticJson = await routes['artifact-frame'].GET(frameRequest('&v=3&format=json'))+ assert.equal((await programmaticJson.json()).revision, 2)+})++test('a preview frame status is accepted only as an integer error from 400 to 599', async () => {+ const { isPreviewErrorStatus } = await import('../lib/preview-update.ts')+ for (const status of [400, 401, 404, 422, 503, 599]) assert.equal(isPreviewErrorStatus(status), true, String(status))+ for (const status of [0, 200, 304, 399, 600, 404.5, Number.NaN, Infinity, '404', null, undefined, { status: 404 }]) {+ assert.equal(isPreviewErrorStatus(status), false, String(status))+ }+})+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'))