A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.
TypeScript
Preserve preview state when returning to a browser tab
Esteban Suarez830ada4f5e20
diff --git a/lib/design-artifact.ts b/lib/design-artifact.tsindex 510f0d8..ad1714b 100644--- a/lib/design-artifact.ts+++ b/lib/design-artifact.ts@@ -128,8 +128,14 @@ frame.addEventListener('load',()=>setTimeout(()=>{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(()=>{- if(document.visibilityState==='visible'&&Date.now()-lastHeartbeat>3000)restore();+ const now=Date.now(),paused=now-lastCheck>3000;+ lastCheck=now;+ if(document.visibilityState!=='visible'||paused){lastHeartbeat=now;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}};diff --git a/tests/core.test.mjs b/tests/core.test.mjsindex baa0a26..f3560cb 100644--- a/tests/core.test.mjs+++ b/tests/core.test.mjs@@ -1,9 +1,11 @@import assert from 'node:assert/strict'import test from 'node:test'+import { runInNewContext } from 'node:vm'import { urlChat } from '../lib/session-id.ts'import './runtime.test.mjs'import {DESIGN_ARTIFACT_EMBEDDED_CSP,+ designFrameHtml,MAX_DESIGN_ARTIFACT_BYTES,normalizeDesignArtifactHtml,prepareDesignArtifactHtml,@@ -723,6 +725,87 @@ test('a design that does not start with its doctype is rejected with what it sta}})+// Run the served wrapper itself with a controlled clock and browser scheduling.+async function frameWatchdog() {+ let now = 0+ let check+ let loads = 0+ const listeners = new Map()+ const documentListeners = new Map()+ const frame = {+ contentWindow: {},+ setAttribute() {},+ addEventListener() {},+ set src(value) { loads++ },+ }+ const document = {+ visibilityState: 'visible',+ createElement: () => frame,+ querySelector: () => ({ append() {} }),+ addEventListener: (type, listener) => documentListeners.set(type, listener),+ }+ const html = designFrameHtml(SAFE_DESIGN, 'watchdog-test')+ runInNewContext(html.match(/<script>([\s\S]*?)<\/script>/)[1], {+ document,+ Date: { now: () => now },+ Blob,+ URL: { createObjectURL: () => 'blob:design' },+ addEventListener: (type, listener) => listeners.set(type, listener),+ setInterval: (callback) => { check = callback },+ setTimeout() {},+ })+ await new Promise(setImmediate)+ assert.equal(loads, 1, 'the initial artifact loads')+ return {+ get loads() { return loads },+ tick(ms = 500) { now += ms; check() },+ visibility(state, notify = true) {+ document.visibilityState = state+ if (notify) documentListeners.get('visibilitychange')?.()+ },+ heartbeat() {+ listeners.get('message')({ source: frame.contentWindow, data: { type: 'heartbeat', token: 'watchdog-test' } })+ },+ }+}++test('the preview watchdog preserves the document on a tab return, even with delayed heartbeats', async () => {+ const frame = await frameWatchdog()+ frame.visibility('hidden')+ for (let i = 0; i < 120; i++) frame.tick()+ frame.visibility('visible')+ for (let i = 0; i < 5; i++) frame.tick()+ assert.equal(frame.loads, 1, 'background time is not a failure')+ frame.heartbeat()+ for (let i = 0; i < 10; i++) {+ frame.tick()+ frame.heartbeat()+ }+ assert.equal(frame.loads, 1, 'the original document stays alive after resuming')+})++test('the preview watchdog tolerates suspended timers before the visibility event is delivered', async () => {+ const frame = await frameWatchdog()+ // No callbacks run while the browser freezes the tab or the machine sleeps.+ frame.visibility('hidden')+ frame.visibility('visible', false)+ frame.tick(60_000)+ assert.equal(frame.loads, 1, 'a delayed timer is not evidence of a broken design')+ frame.visibility('visible')+ frame.tick()+ frame.heartbeat()+ assert.equal(frame.loads, 1)+})++test('the preview watchdog still restores a design that stays silent while visible', async () => {+ const frame = await frameWatchdog()+ for (let i = 0; i < 7; i++) frame.tick()+ assert.equal(frame.loads, 2)+ frame.heartbeat()+ for (let i = 0; i < 6; i++) frame.tick()+ assert.equal(frame.loads, 2, 'a fresh heartbeat resets the recovery deadline')+})+test('design artifact validation rejects fragments and oversized documents', () => {assertInvalid('<main>fragment</main>', 'design artifact must start with <!doctype html>, but it starts with "<main>fragment</main>"')const oversized = '<!doctype html><html><head></head><body>' + 'x'.repeat(MAX_DESIGN_ARTIFACT_BYTES) + '</body></html>'