A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.
TypeScript
Wait for wrapper load before revealing published previews
Esteban Suarezbbffc3ee1db2
diff --git a/lib/design-artifact.ts b/lib/design-artifact.tsindex c91a027..789447a 100644--- a/lib/design-artifact.ts+++ b/lib/design-artifact.ts@@ -115,6 +115,7 @@ let current=null;let pending=null;let hotReady=false;let hasPainted=false;+let hasLoaded=false;const frame=document.createElement('iframe');frame.title='Interactive design artifact';frame.setAttribute('sandbox','allow-scripts');@@ -124,7 +125,10 @@ let readySignals=0;let consumedSignals=0;let lastHeartbeat=Date.now();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);+// A child's rAF can run before this wrapper finishes loading. Revealing that+// still-loading wrapper exposes the app background (black in dark mode).+const painted=()=>{if(hasLoaded)parent.postMessage(preview?{type:'fx0-artifact-painted',protocol:1,sessionId:preview.sessionId,revision:current.revision,documentId,updateReady:hotReady}:{type:'fx0-artifact-painted'},location.origin);};+addEventListener('load',()=>{hasLoaded=true;if(hasPainted)painted();},{once:true});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=()=>{diff --git a/tests/fixtures/simple-house.html b/tests/fixtures/simple-house.htmlnew file mode 100644index 0000000..17a7cde--- /dev/null+++ b/tests/fixtures/simple-house.html@@ -0,0 +1 @@+<!doctype html><html><head><meta charset="utf-8"><title>Simple House</title><style>body{margin:0;height:100vh;display:flex;align-items:center;justify-content:center;background:linear-gradient(#8fd3ff,#e6f7ff);font-family:sans-serif}svg{width:min(90vw,600px);height:auto}#door{cursor:pointer}</style></head><body><svg viewBox="0 0 400 320"><circle cx="340" cy="50" r="28" fill="#ffd84d"/><rect x="0" y="270" width="400" height="50" fill="#6cc04a"/><rect x="250" y="70" width="30" height="60" fill="#8a4b3a"/><rect x="90" y="150" width="220" height="120" fill="#f4e1c1"/><polygon points="70,155 200,60 330,155" fill="#c0392b"/><rect x="175" y="200" width="50" height="70" fill="#7b4a2a" id="door"/><circle cx="215" cy="237" r="3" fill="#ffd84d"/><g fill="#9fd8ff" stroke="#fff" stroke-width="4"><rect x="110" y="180" width="45" height="40"/><rect x="245" y="180" width="45" height="40"/></g><g stroke="#fff" stroke-width="3"><line x1="132.5" y1="180" x2="132.5" y2="220"/><line x1="110" y1="200" x2="155" y2="200"/><line x1="267.5" y1="180" x2="267.5" y2="220"/><line x1="245" y1="200" x2="290" y2="200"/></g></svg><script>const d=document.getElementById('door');let o=0;d.onclick=()=>{o=!o;d.setAttribute('fill',o?'#2b1a10':'#7b4a2a')}</script></body></html>diff --git a/tests/preview-update.browser.mjs b/tests/preview-update.browser.mjsindex 1a89f2a..2aff802 100644--- a/tests/preview-update.browser.mjs+++ b/tests/preview-update.browser.mjs@@ -101,7 +101,7 @@ window.mount = url => {}</script></body></html>`-async function buildPaneFixture(directory) {+async function buildPaneFixture(directory, initialRevision = 101) {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'),@@ -116,7 +116,7 @@ async function buildPaneFixture(directory) {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 [revision, setRevision] = useState(${initialRevision}), [viewing, setViewing] = useState(null)const [sessionId, setSession] = useState(${JSON.stringify(SESSION)}), [draft, setDraft] = useState(null)const [accessAllowed, setAccessAllowed] = useState(true)useEffect(() => {@@ -167,6 +167,7 @@ html,body,#app{margin:0;height:100%}#preview-pane{height:100%;display:flex;flex-#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}+.relative{position:relative}.absolute{position:absolute}.inset-0{inset:0}.flex{display:flex}.flex-1{flex:1}.min-h-0{min-height:0}.z-20{z-index:20}.opacity-0{opacity:0}.bg-background{background:white}</style></head><body><script>${OBSERVER}</script><div id="app">${markup}</div><script defer src="/bundle.js"></script></body></html>`,}}@@ -1024,3 +1025,111 @@ test('in Chrome, the production preview wrapper and React PreviewPane preserve sawait rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })}})++// The real first-generation capture exposed the draft -> published handoff before+// the wrapper's load event: 8 black frames at 120 Hz. Hold the wrapper response open+// after its scripts run, so its real child paints before the wrapper finishes loading.+// No synthetic paint messages or replacement slot coordinator participate.+test('first publish waits for wrapper load after child paint', { timeout: 60_000 }, async t => {+ assert.ok(existsSync(CHROME), `Chrome not found at ${CHROME}; set CHROME_PATH`)+ const dir = await mkdtemp(join(tmpdir(), 'fx0-first-publish-'))+ const errors = []+ const held = []+ let chrome, cdp, chromeError = ''+ const fixture = await buildPaneFixture(dir, 0)+ const house = await readFile(new URL('./fixtures/simple-house.html', import.meta.url), 'utf8')+ const candidate = payload(1, house)+ const server = http.createServer((request, response) => {+ const url = new URL(request.url, 'http://fixture')+ if (url.pathname === '/') return response.writeHead(200, { 'content-type': 'text/html' }).end(fixture.html.replace('</style>', ':root{color-scheme:light dark}body,.bg-background{background:light-dark(white,black)}</style>'))+ if (url.pathname === '/bundle.js') return response.writeHead(200, { 'content-type': 'text/javascript' }).end(fixture.bundle)+ if (url.pathname === '/api/artifact-frame') {+ if (url.searchParams.get('format') === 'json') return response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(candidate))+ const prepared = prepareDesignArtifactHtml(candidate.renderHtml, DESIGN_ARTIFACT_EMBEDDED_CSP, TOKEN)+ // Observe the real child's message without forwarding, delaying or replacing it.+ const html = designFrameHtml(prepared, TOKEN, [], candidate).replace('<script>', `<script>+window.childPainted = false;+addEventListener('message', event => {+ if (event.source === document.querySelector('#frame-root iframe')?.contentWindow && event.data?.type === 'painted') window.childPainted = true;+});`)+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-security-policy': designFrameCsp() })+ response.write(html)+ held.push(response)+ return+ }+ response.writeHead(404).end()+ })+ try {+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })+ 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('Emulation.setDeviceMetricsOverride', { width: 1000, height: 720, deviceScaleFactor: 1, mobile: false })+ const origin = `http://127.0.0.1:${server.address().port}`+ for (const scheme of ['light', 'dark']) await t.test(scheme, async () => {+ await cdp.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] })+ await cdp.call('Page.navigate', { url: `${origin}/?scheme=${scheme}` })+ await until(() => cdp.evaluate('window.fixtureReady === true'), 'first-generation fixture')+ try {+ await cdp.evaluate(`setDraft(${JSON.stringify(house)})`)+ await until(() => cdp.evaluate(`(() => {+ const frame = document.querySelector('iframe[title="Design preview while generating"]');+ return !!frame?.contentDocument?.getElementById('door') && getComputedStyle(frame).opacity === '1';+ })()`), 'the real house draft is visible')+ await cdp.evaluate(`window.originalDraft = document.querySelector('iframe[title="Design preview while generating"]'); setRevision(1); setDraft(null)`)+ await until(() => cdp.evaluate(`!!document.querySelector('iframe[src]')?.contentWindow?.childPainted`), 'the real child paints while its wrapper response is still open')+ // Let any erroneously forwarded paint reach React before checking its layers.+ await cdp.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))')+ const beforeLoad = await cdp.evaluate(`(() => {+ const wrapper = document.querySelector('iframe[src]');+ return { readyState: wrapper.contentDocument.readyState, paints: observed.paints.length,+ draftRetained: originalDraft.isConnected, draftOpacity: getComputedStyle(originalDraft).opacity,+ wrapperOpacity: getComputedStyle(wrapper).opacity, hidden: wrapper.getAttribute('aria-hidden') };+ })()`)+ t.diagnostic(`${scheme} before wrapper load: ${JSON.stringify(beforeLoad)}`)+ assert.notEqual(beforeLoad.readyState, 'complete', 'the HTTP fixture really delays wrapper load')+ assert.equal(beforeLoad.paints, 0, 'child paint cannot retire the draft before the wrapper loads')+ assert.equal(beforeLoad.draftRetained, true)+ assert.equal(beforeLoad.draftOpacity, '1')+ assert.equal(beforeLoad.wrapperOpacity, '0')+ assert.equal(beforeLoad.hidden, 'true')+ for (const response of held.splice(0)) response.end()+ await until(() => cdp.evaluate(`observed.paints.length > 0 && !originalDraft.isConnected`), 'wrapper load releases the retained child paint and retires the draft')+ assert.equal(await cdp.evaluate(`document.querySelector('iframe[title="Design artifact preview"]').contentDocument.readyState`), 'complete')+ assert.equal(await cdp.evaluate(`document.querySelectorAll('#preview-pane iframe').length`), 1, 'the handoff leaves only the interactive frame')+ assert.deepEqual(await cdp.evaluate('observed.errors'), [])+ } finally {+ for (const response of held.splice(0)) response.end()+ }+ })+ assert.deepEqual(errors, [], 'no browser execution errors')+ } finally {+ 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()+ server.closeAllConnections()+ await new Promise(resolve => server.close(resolve))+ for (const response of held) response.destroy()+ await rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })+ }+})