From f2c4a451a865321fba01bf9308f01aa6c55a5e82 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 1 Nov 2026 09:36:57 -0500 Subject: [PATCH 1/3] probe: Firefox two-window store timing on CI, temporary Co-Authored-By: Claude Opus 5.5 --- .ci-probe/probe.mjs | 52 +++++++++++++++++++++++++++++++++++++ .github/workflows/probe.yml | 23 ++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 .ci-probe/probe.mjs create mode 100644 .github/workflows/probe.yml diff --git a/.ci-probe/probe.mjs b/.ci-probe/probe.mjs new file mode 100644 index 0000000..61918fc --- /dev/null +++ b/.ci-probe/probe.mjs @@ -0,0 +1,52 @@ +import http from 'node:http'; +import path from 'node:path'; +const WT = path.resolve(process.argv[2]), RUNS = +(process.argv[3] || 10), ID = process.argv[4] || 'p'; +const pw = await import('file://' + WT + '/node_modules/playwright/index.mjs'); +const {create} = await import('file://' + WT + '/bin/create.mjs'); +const model = () => ({w: 960, h: 540, title: 'probe', slides: [ + {els: [{x: 60, y: 80, w: 800, role: 'H1', text: 'One'}, {x: 60, y: 200, w: 400, role: 'Body', text: 'body one'}]}, + {els: [{x: 60, y: 80, w: 800, role: 'H1', text: 'Two'}]}, +]}); +const served = create(model()).html; +const server = http.createServer((q, r) => { r.setHeader('content-type', 'text/html; charset=utf-8'); r.end(served); }); +await new Promise(r => server.listen(0, '127.0.0.1', r)); +const settled = p => p.waitForFunction(() => document.getElementById('autosave').dataset.state !== 'busy', null, {timeout: 15000}); +const spy = () => { window.__w = []; const o = Storage.prototype.setItem; Storage.prototype.setItem = function (k, v) { if (this === localStorage && k === KEY) window.__w.push([Math.round(performance.timeOrigin + performance.now()), JSON.parse(v).slides[0].els[0].text]); return o.call(this, k, v); }; }; +const has = p => p.evaluate(() => { try { return JSON.parse(localStorage.getItem(KEY)).slides[0].els[0].text; } catch (e) { return String(e); } }); +const until = (p, fn, ms = 15000) => p.waitForFunction(fn, null, {timeout: ms}); +let bad = 0, good = 0, errs = 0; +for (let run = 0; run < RUNS; run++) { + const b = await pw.firefox.launch(); + try { + const ctx = await b.newContext(), url = `http://127.0.0.1:${server.address().port}/${ID}-${run}.html`, t = {id: ID, run}; + const A = await ctx.newPage(); await A.goto(url); await A.evaluate(() => localStorage.clear()); await A.reload(); await settled(A); + const B = await ctx.newPage(); await B.goto(url); await settled(B); + await A.evaluate(spy); await B.evaluate(spy); + await B.evaluate(() => nav(1)); + await A.evaluate(() => { snap(); slide().els[1].x = 123; save(); }); + await until(B, () => deck.slides[0].els[1].x === 123); + await B.evaluate(() => { nav(-1); sel.clear(); sel.add(0); render(); edit(0); }); await B.keyboard.type('typed in B'); + await A.evaluate(() => { snap(); slide().els[1].y = 250; save(); }); + await until(B, () => deck.slides[0].els[1].y === 250); + await until(A, () => deck.slides[0].els[0].text === 'typed in B'); + t.first = await has(A); + const s = Date.now(); + try { await until(A, () => JSON.parse(localStorage.getItem(KEY)).slides[0].els[0].text === 'typed in B', 2000); t.poll2s = true; } catch { t.poll2s = false; } + t.pollMs = Date.now() - s; + if (t.first !== 'typed in B' || !t.poll2s) { + t.aNow = await has(A); t.bNow = await has(B); + const C = await ctx.newPage(); await C.goto(url + '?fresh'); t.freshNow = await has(C).catch(e => String(e)); await C.close(); + const r = Date.now(); let reads = 0; + while (Date.now() - r < 30000 && await has(A) !== 'typed in B') { reads++; await new Promise(x => setTimeout(x, 100)); } + t.settledMs = Date.now() - r; t.reads = reads; t.aEnd = await has(A); t.bEnd = await has(B); + t.aWrites = await A.evaluate(() => window.__w); t.bWrites = await B.evaluate(() => window.__w); + t.aFocus = await A.evaluate(() => [document.hidden, document.hasFocus()]); + } + const flagged = t.first !== 'typed in B' || !t.poll2s; + if (flagged) { bad++; console.log('FLAG ' + JSON.stringify(t)); } else good++; + await ctx.close(); + } catch (e) { errs++; console.log('ERR ' + ID + ' ' + run + ' ' + String(e).slice(0, 200)); } + await b.close(); +} +console.log(`DONE ${ID} good ${good} bad ${bad} errs ${errs}`); +server.close(); diff --git a/.github/workflows/probe.yml b/.github/workflows/probe.yml new file mode 100644 index 0000000..b6bc87f --- /dev/null +++ b/.github/workflows/probe.yml @@ -0,0 +1,23 @@ +name: probe +on: + push: + branches: ['claude/firefox-store-flake-*'] +jobs: + probe: + runs-on: ubuntu-latest + timeout-minutes: 40 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: { node-version: 22 } + - run: npm i -D playwright && npx playwright install --with-deps chromium webkit firefox + timeout-minutes: 15 + - name: probe under suite load + run: | + for i in 1 2 3; do node .ci-probe/probe.mjs . 60 p$i > p$i.log 2>&1 & done + node --test --test-reporter=tap test/**/*.test.mjs > suite.log 2>&1 || true + wait + grep -hE '^(FLAG|ERR|DONE)' p*.log + grep -E '^not ok|^# (pass|fail) ' suite.log | cut -c1-140 + - name: probe alone + run: node .ci-probe/probe.mjs . 60 solo | grep -E '^(FLAG|ERR|DONE)' From 2db9aae2d1b0f1e593a91110134e12f62e992bfb Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 1 Nov 2026 09:53:24 -0500 Subject: [PATCH 2/3] editor: a window restores its newer model when an older save lands late Co-Authored-By: Claude Opus 5.5 --- .ci-probe/probe.mjs | 9 +++++---- CHANGELOG.md | 1 + deck.html | 7 ++++--- docs/editor.md | 2 +- library.html | 7 ++++--- template.html | 7 ++++--- test/autosave.test.mjs | 20 ++++++++++++++++++++ 7 files changed, 39 insertions(+), 14 deletions(-) diff --git a/.ci-probe/probe.mjs b/.ci-probe/probe.mjs index 61918fc..17205d2 100644 --- a/.ci-probe/probe.mjs +++ b/.ci-probe/probe.mjs @@ -14,7 +14,7 @@ const settled = p => p.waitForFunction(() => document.getElementById('autosave') const spy = () => { window.__w = []; const o = Storage.prototype.setItem; Storage.prototype.setItem = function (k, v) { if (this === localStorage && k === KEY) window.__w.push([Math.round(performance.timeOrigin + performance.now()), JSON.parse(v).slides[0].els[0].text]); return o.call(this, k, v); }; }; const has = p => p.evaluate(() => { try { return JSON.parse(localStorage.getItem(KEY)).slides[0].els[0].text; } catch (e) { return String(e); } }); const until = (p, fn, ms = 15000) => p.waitForFunction(fn, null, {timeout: ms}); -let bad = 0, good = 0, errs = 0; +let bad = 0, good = 0, errs = 0, late = 0, maxMs = 0; for (let run = 0; run < RUNS; run++) { const b = await pw.firefox.launch(); try { @@ -33,7 +33,8 @@ for (let run = 0; run < RUNS; run++) { const s = Date.now(); try { await until(A, () => JSON.parse(localStorage.getItem(KEY)).slides[0].els[0].text === 'typed in B', 2000); t.poll2s = true; } catch { t.poll2s = false; } t.pollMs = Date.now() - s; - if (t.first !== 'typed in B' || !t.poll2s) { + if (t.first !== 'typed in B') late++; maxMs = Math.max(maxMs, t.pollMs); + if (!t.poll2s) { t.aNow = await has(A); t.bNow = await has(B); const C = await ctx.newPage(); await C.goto(url + '?fresh'); t.freshNow = await has(C).catch(e => String(e)); await C.close(); const r = Date.now(); let reads = 0; @@ -42,11 +43,11 @@ for (let run = 0; run < RUNS; run++) { t.aWrites = await A.evaluate(() => window.__w); t.bWrites = await B.evaluate(() => window.__w); t.aFocus = await A.evaluate(() => [document.hidden, document.hasFocus()]); } - const flagged = t.first !== 'typed in B' || !t.poll2s; + const flagged = !t.poll2s; if (flagged) { bad++; console.log('FLAG ' + JSON.stringify(t)); } else good++; await ctx.close(); } catch (e) { errs++; console.log('ERR ' + ID + ' ' + run + ' ' + String(e).slice(0, 200)); } await b.close(); } -console.log(`DONE ${ID} good ${good} bad ${bad} errs ${errs}`); +console.log(`DONE ${ID} good ${good} bad ${bad} errs ${errs} storeLateAtFirstRead ${late} maxPollMs ${maxMs}`); server.close(); diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c962b5..86a8890 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## Unreleased +- **Two windows no longer lose an edit in the store.** When window B was typing as window A saved, B saved its words on top of A's model, but A's older save could reach localStorage after B's. Both windows looked right and the store held A's model without B's words, so a reload lost them. A CI probe caught this on Firefox in 12 of 180 runs under load and 0 of 60 alone. A window now watches the `storage` event: when the store holds a model it already built on, it writes its newer model back, and it writes the log back when entries are missing. This was the Firefox two-window failure on `main`. - **JSON Schema for model.json and style.json (#203).** `schemas/model.schema.json` and `schemas/style.schema.json` (draft 2020-12) carry the structure and every enum the engine checks: formats, pages, densities, the 115 template ids, anims, arrows, heads, connector styles, plates, chart marks and the eight roles. `node schemas/build.mjs` writes both from the constants in code (`lib/chart.mjs` now exports `MARKS`), so an enum cannot drift. `bin/new.mjs` writes `$schema` as the model's first key, relative to the model, so editors complete and flag props; `create` strips it before hashing or embedding, so no local path reaches a deck and the deck id is unchanged. `validate` still owns fit, air, density and coverage. The package ships `schemas/`. Gate: test/schema.test.mjs (committed files equal the build output, every enum equals its constant, every example model and style kit passes, the `new.mjs` round trip, the package list). - **Coded validate diagnostics (#201, validate half).** Every one of `validate`'s 134 findings carries a code (`fit/nowrap-width`, `air/gap`, `coverage/text-only`, seventeen families in all, catalogued in docs/verify.md) and lands in a new `diagnostics` array beside the unchanged `errors` and `warnings` strings: `{code, severity, message, subject: {slide, el, id}, evidence?, fixes}`. `fit/nowrap-width` carries `{need, have}` and offers `w: `. `node bin/validate.mjs model.json --json` prints them, and the `finalize` receipt carries them per stage. Gate: test/diagnostics.test.mjs (a static check that every call site passes a code, the catalogue covers every family, the strings are unchanged on every example, `--json` matches the in-process result, and the receipt carries them). The verify half follows. - **Receipts bound to the deck's bytes (#200).** `node bin/finalize.mjs --check deck.html` (API `checkReceipt`) exits 0 only when the deck's receipt passed and its `deck.sha256` still matches the file, and names both hashes when it does not. `verify` writes `deck: {sha256, id, rev}` into `results.json`, so a rebuilt `deck.html` no longer sits beside an older pass that reads as its own. `create` and `finalize` write the deck through a temp file and a rename (`writeDeck`). Gate: test/finalize.test.mjs (a changed byte, a failed run, a missing receipt, the atomic write, and a live verify whose `results.json` carries the deck's hash). diff --git a/deck.html b/deck.html index e236bb5..732664a 100644 --- a/deck.html +++ b/deck.html @@ -632,15 +632,16 @@ addEventListener('beforeunload',e=>{commitEdit();if(route()==='tab'&&unsynced){e.preventDefault();e.returnValue=''}}); // ── sync: the other windows and tabs of this browser showing this deck. Every save is told to them — a `storage` event on the // localStorage tier, a BroadcastChannel on any tier that has one (Safari 15.4+) — and a window that hears one takes the model as -// its own: last write wins, the slide you were on is kept by id, an edit in flight lands on top of theirs, and NOTHING is written -// in response (no echo: a second window is a reader of what it hears). Logs merge by entry, so no window's edits go missing from +// its own: last write wins, the slide you were on is kept by id, an edit in flight lands on top of theirs. Logs merge by entry, so no window's edits go missing from // the replay; a file another agent version wrote (a different rev) is left to the reload path, which reconciles by log. const bc=(()=>{try{return new BroadcastChannel(NS)}catch{return null}})(); const tell=m=>{if(bc)bc.postMessage(m)}; if(bc)bc.onmessage=e=>receive(e.data); -addEventListener('storage',e=>{if(e.key===KEY)receive({model:e.newValue});else if(e.key===LKEY)receive({log:e.newValue})}); +addEventListener('storage',e=>{if(e.key===KEY){receive({model:e.newValue});restoreModel(e.newValue)}else if(e.key===LKEY){receive({log:e.newValue});restoreLog()}}); let heard=null;const ekey=e=>JSON.stringify({...e,rev:undefined}); // an entry's identity: what changed and when — never the rev a later write stamped on it function mergeLog(rl){const mine=new Map(log.map(e=>[ekey(e),e]));let ch=false;for(const e of rl){const k=ekey(e),m=mine.get(k);if(!m){log.push(e);mine.set(k,e);ch=true}else if(e.rev&&!m.rev){m.rev=e.rev;ch=true}}if(ch){log.sort((a,b)=>(a.t||'').localeCompare(b.t||''));unsynced=log.filter(e=>!e.rev).length}return ch} +const restoreModel=v=>{if(LS&&v!=null&&v===heard&&base!==heard&&LS.getItem(KEY)===v)store.set(KEY,base)}; +const restoreLog=()=>{if(!LS)return;let held;try{held=new Set(JSON.parse(LS.getItem(LKEY)).map(ekey))}catch{return}if(log.some(e=>!held.has(ekey(e))))store.set(LKEY,JSON.stringify(log))}; function receive(m){ if(!m)return;if(m.log)try{mergeLog(JSON.parse(m.log))}catch{} if(m.model==null||m.model===base||m.model===heard)return;heard=m.model;let d;try{d=JSON.parse(m.model)}catch{return}if(!d||d.rev!==DECK.rev)return; // one save reaches a window twice on the localStorage tier (the storage event and the channel): the second copy is ignored diff --git a/docs/editor.md b/docs/editor.md index 0f81370..ab03653 100644 --- a/docs/editor.md +++ b/docs/editor.md @@ -30,7 +30,7 @@ This manifest is a contract: the gate compares it against the template, so the H ## Persistence, honestly -**Persistence, honestly.** Every edit autosaves to the browser's storage under `deck.id` — localStorage; IndexedDB where localStorage is refused (a cross-site iframe); memory as the last resort — and is appended to the in-file **edit log** (slide id, row id, keys before → after). This holds on a desktop, on a phone (a touch edit persists; switching apps commits the edit in flight) and inside an iframe (same origin, srcdoc, or cross-site on whichever tier the browser allows). Every window or tab of the same browser showing the deck picks up an edit live (`storage` events + a BroadcastChannel): last write wins, each tab keeps its own slide, an edit in flight lands on top of what arrived, and a window that hears an edit never writes back. **The deck file writes itself:** in Chrome/Edge the first ⌘S (or a tap on the dot) asks for the file once (File System Access, remembered per browser), and from then on every edit rewrites it in place on an 800 ms trailing debounce — ⌘S, the dot, a hidden tab or an unload flush the pending write now — with the model and the log inside, so an agent reading the file sees exactly what the human did. The dot is green only when the file has everything; amber counts the edits that have not reached it. Safari (and any browser without File System Access) cannot write the file: there ⌘S downloads a self-contained copy. Before each write the page compares the file's `lastModified` with the value from its last read or write; when another program (an agent's `create --from`, another editor) changed the file, the page does not write, reads the new file, and replays its unwritten edits on top, exactly as the hosted page does. A live text edit or a drag in flight is committed when the tab hides or unloads, so a refresh mid-edit loses nothing. +**Persistence, honestly.** Every edit autosaves to the browser's storage under `deck.id` — localStorage; IndexedDB where localStorage is refused (a cross-site iframe); memory as the last resort — and is appended to the in-file **edit log** (slide id, row id, keys before → after). This holds on a desktop, on a phone (a touch edit persists; switching apps commits the edit in flight) and inside an iframe (same origin, srcdoc, or cross-site on whichever tier the browser allows). Every window or tab of the same browser showing the deck picks up an edit live (`storage` events + a BroadcastChannel): last write wins, each tab keeps its own slide, an edit in flight lands on top of what arrived, and a window that hears an edit writes nothing back. One exception: when an older save from another window lands in the store after this window saved on top of it, this window puts its newer model and any missing log entries back. **The deck file writes itself:** in Chrome/Edge the first ⌘S (or a tap on the dot) asks for the file once (File System Access, remembered per browser), and from then on every edit rewrites it in place on an 800 ms trailing debounce — ⌘S, the dot, a hidden tab or an unload flush the pending write now — with the model and the log inside, so an agent reading the file sees exactly what the human did. The dot is green only when the file has everything; amber counts the edits that have not reached it. Safari (and any browser without File System Access) cannot write the file: there ⌘S downloads a self-contained copy. Before each write the page compares the file's `lastModified` with the value from its last read or write; when another program (an agent's `create --from`, another editor) changed the file, the page does not write, reads the new file, and replays its unwritten edits on top, exactly as the hosted page does. A live text edit or a drag in flight is committed when the tab hides or unloads, so a refresh mid-edit loses nothing. **Save routes.** The page picks one at load by what the browser can do, never by its name: the host (a `bin/serve.mjs` probe answered), then a file handle (File System Access, with a handle this browser still trusts), then a durable store (localStorage, or IndexedDB), then the tab. The tab route covers Safari on `file://`, sandboxed frames and embedded browsers that refuse storage: the page keeps the model and the unsaved log in `window.name`, with `history.state` as a second copy, both tagged with the deck id, so a reload in the same tab restores the edits and a copy another deck left in the tab is ignored. The save button reads **Not saving** in amber, its tooltip and a banner shown once at load (dismissed, it stays gone for that tab) say `This browser cannot save here. Edits survive reload in this tab only. Host it: node bin/serve.mjs `, and leaving the page asks first while edits exist only in the tab (embedded browsers may suppress that prompt). Closing the tab loses them; ⌘S still downloads a copy where downloads work. **Position:** a new window opens on slide 1; a refresh, and a new version of the file, keep the slide you were on — by slide id, so inserting slides above does not move you. A stored working copy is trusted only on the same `rev`; a newer file wins as the base and the browser replays its own edit log onto it (human wins, conflicts flagged on the entries), so an agent's rewrite neither hides its changes nor drops the human's. **Versions:** none in the file since 0.9.0. Version history is weave's job; decklet keeps the edit log, which `create --from` replays. diff --git a/library.html b/library.html index e243906..ae5b984 100644 --- a/library.html +++ b/library.html @@ -631,15 +631,16 @@ addEventListener('beforeunload',e=>{commitEdit();if(route()==='tab'&&unsynced){e.preventDefault();e.returnValue=''}}); // ── sync: the other windows and tabs of this browser showing this deck. Every save is told to them — a `storage` event on the // localStorage tier, a BroadcastChannel on any tier that has one (Safari 15.4+) — and a window that hears one takes the model as -// its own: last write wins, the slide you were on is kept by id, an edit in flight lands on top of theirs, and NOTHING is written -// in response (no echo: a second window is a reader of what it hears). Logs merge by entry, so no window's edits go missing from +// its own: last write wins, the slide you were on is kept by id, an edit in flight lands on top of theirs. Logs merge by entry, so no window's edits go missing from // the replay; a file another agent version wrote (a different rev) is left to the reload path, which reconciles by log. const bc=(()=>{try{return new BroadcastChannel(NS)}catch{return null}})(); const tell=m=>{if(bc)bc.postMessage(m)}; if(bc)bc.onmessage=e=>receive(e.data); -addEventListener('storage',e=>{if(e.key===KEY)receive({model:e.newValue});else if(e.key===LKEY)receive({log:e.newValue})}); +addEventListener('storage',e=>{if(e.key===KEY){receive({model:e.newValue});restoreModel(e.newValue)}else if(e.key===LKEY){receive({log:e.newValue});restoreLog()}}); let heard=null;const ekey=e=>JSON.stringify({...e,rev:undefined}); // an entry's identity: what changed and when — never the rev a later write stamped on it function mergeLog(rl){const mine=new Map(log.map(e=>[ekey(e),e]));let ch=false;for(const e of rl){const k=ekey(e),m=mine.get(k);if(!m){log.push(e);mine.set(k,e);ch=true}else if(e.rev&&!m.rev){m.rev=e.rev;ch=true}}if(ch){log.sort((a,b)=>(a.t||'').localeCompare(b.t||''));unsynced=log.filter(e=>!e.rev).length}return ch} +const restoreModel=v=>{if(LS&&v!=null&&v===heard&&base!==heard&&LS.getItem(KEY)===v)store.set(KEY,base)}; +const restoreLog=()=>{if(!LS)return;let held;try{held=new Set(JSON.parse(LS.getItem(LKEY)).map(ekey))}catch{return}if(log.some(e=>!held.has(ekey(e))))store.set(LKEY,JSON.stringify(log))}; function receive(m){ if(!m)return;if(m.log)try{mergeLog(JSON.parse(m.log))}catch{} if(m.model==null||m.model===base||m.model===heard)return;heard=m.model;let d;try{d=JSON.parse(m.model)}catch{return}if(!d||d.rev!==DECK.rev)return; // one save reaches a window twice on the localStorage tier (the storage event and the channel): the second copy is ignored diff --git a/template.html b/template.html index 5c6bf2d..9b4cd70 100644 --- a/template.html +++ b/template.html @@ -631,15 +631,16 @@ addEventListener('beforeunload',e=>{commitEdit();if(route()==='tab'&&unsynced){e.preventDefault();e.returnValue=''}}); // ── sync: the other windows and tabs of this browser showing this deck. Every save is told to them — a `storage` event on the // localStorage tier, a BroadcastChannel on any tier that has one (Safari 15.4+) — and a window that hears one takes the model as -// its own: last write wins, the slide you were on is kept by id, an edit in flight lands on top of theirs, and NOTHING is written -// in response (no echo: a second window is a reader of what it hears). Logs merge by entry, so no window's edits go missing from +// its own: last write wins, the slide you were on is kept by id, an edit in flight lands on top of theirs. Logs merge by entry, so no window's edits go missing from // the replay; a file another agent version wrote (a different rev) is left to the reload path, which reconciles by log. const bc=(()=>{try{return new BroadcastChannel(NS)}catch{return null}})(); const tell=m=>{if(bc)bc.postMessage(m)}; if(bc)bc.onmessage=e=>receive(e.data); -addEventListener('storage',e=>{if(e.key===KEY)receive({model:e.newValue});else if(e.key===LKEY)receive({log:e.newValue})}); +addEventListener('storage',e=>{if(e.key===KEY){receive({model:e.newValue});restoreModel(e.newValue)}else if(e.key===LKEY){receive({log:e.newValue});restoreLog()}}); let heard=null;const ekey=e=>JSON.stringify({...e,rev:undefined}); // an entry's identity: what changed and when — never the rev a later write stamped on it function mergeLog(rl){const mine=new Map(log.map(e=>[ekey(e),e]));let ch=false;for(const e of rl){const k=ekey(e),m=mine.get(k);if(!m){log.push(e);mine.set(k,e);ch=true}else if(e.rev&&!m.rev){m.rev=e.rev;ch=true}}if(ch){log.sort((a,b)=>(a.t||'').localeCompare(b.t||''));unsynced=log.filter(e=>!e.rev).length}return ch} +const restoreModel=v=>{if(LS&&v!=null&&v===heard&&base!==heard&&LS.getItem(KEY)===v)store.set(KEY,base)}; +const restoreLog=()=>{if(!LS)return;let held;try{held=new Set(JSON.parse(LS.getItem(LKEY)).map(ekey))}catch{return}if(log.some(e=>!held.has(ekey(e))))store.set(LKEY,JSON.stringify(log))}; function receive(m){ if(!m)return;if(m.log)try{mergeLog(JSON.parse(m.log))}catch{} if(m.model==null||m.model===base||m.model===heard)return;heard=m.model;let d;try{d=JSON.parse(m.model)}catch{return}if(!d||d.rev!==DECK.rev)return; // one save reaches a window twice on the localStorage tier (the storage event and the channel): the second copy is ignored diff --git a/test/autosave.test.mjs b/test/autosave.test.mjs index 2168e69..eab9872 100644 --- a/test/autosave.test.mjs +++ b/test/autosave.test.mjs @@ -163,3 +163,23 @@ for (const bn of projects()) live(`two windows (${bn}): an edit in one shows in assert.deepEqual(JSON.parse(await A.evaluate(() => localStorage.getItem(KEY))).slides[0].els.map(e => [e.text, e.x, e.y]).slice(0, 2), [['typed in B', 60, 80], ['body one', 123, 250]], 'the store has both windows\' edits'); assert.deepEqual([...A.errs, ...B.errs], []); })); +for (const bn of projects()) live(`two windows (${bn}): an older save landing after an edit on top of it never replaces that edit in the store`, async () => withProject(pw, bn, async ({context}) => { + const url = `http://127.0.0.1:${server.address().port}/late-${bn}.html`; const ctx = await context(); + const A = watch(await ctx.newPage()); await A.goto(url); await A.evaluate(() => localStorage.clear()); await A.reload(); await settled(A); + const B = watch(await ctx.newPage()); await B.goto(url); await settled(B); + await B.evaluate(() => { sel.clear(); sel.add(0); render(); edit(0); }); await B.keyboard.type('typed in B'); + await A.evaluate(() => { snap(); slide().els[1].y = 250; save(); window.__older = [localStorage.getItem(KEY), localStorage.getItem(LKEY)]; }); + await until(B, () => deck.slides[0].els[1].y === 250); + await until(A, () => deck.slides[0].els[0].text === 'typed in B'); + await until(A, () => JSON.parse(localStorage.getItem(KEY)).slides[0].els[0].text === 'typed in B'); + const count = p => p.evaluate(() => { window.__sets = 0; const o = Storage.prototype.setItem; Storage.prototype.setItem = function (...a) { if (this === localStorage) window.__sets++; return o.apply(this, a); }; }); + await count(B); + await A.evaluate(() => { localStorage.setItem(KEY, window.__older[0]); localStorage.setItem(LKEY, window.__older[1]); }); + await until(A, () => JSON.parse(localStorage.getItem(KEY)).slides[0].els[0].text === 'typed in B'); + await until(A, () => JSON.parse(localStorage.getItem(LKEY)).length === 2); + assert.deepEqual(JSON.parse(await A.evaluate(() => localStorage.getItem(KEY))).slides[0].els.map(e => [e.text, e.y]).slice(0, 2), [['typed in B', 80], ['body one', 250]], 'the store has both windows\' edits again'); + assert.equal(await B.evaluate(() => window.__sets), 2, 'B wrote the model and the log once each'); + await A.reload(); await settled(A); + assert.equal(await A.evaluate(() => slide().els[0].text), 'typed in B', 'a reload keeps the words'); + assert.deepEqual([...A.errs, ...B.errs], []); +})); From 76fe23d894b6e526abb032931e20c4141cfbb61b Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 1 Nov 2026 10:06:52 -0500 Subject: [PATCH 3/3] test: the storage listener's shape, probe removed Co-Authored-By: Claude Opus 5.5 --- .ci-probe/probe.mjs | 53 ------------------------------------- .github/workflows/probe.yml | 23 ---------------- test/autosave.test.mjs | 2 +- 3 files changed, 1 insertion(+), 77 deletions(-) delete mode 100644 .ci-probe/probe.mjs delete mode 100644 .github/workflows/probe.yml diff --git a/.ci-probe/probe.mjs b/.ci-probe/probe.mjs deleted file mode 100644 index 17205d2..0000000 --- a/.ci-probe/probe.mjs +++ /dev/null @@ -1,53 +0,0 @@ -import http from 'node:http'; -import path from 'node:path'; -const WT = path.resolve(process.argv[2]), RUNS = +(process.argv[3] || 10), ID = process.argv[4] || 'p'; -const pw = await import('file://' + WT + '/node_modules/playwright/index.mjs'); -const {create} = await import('file://' + WT + '/bin/create.mjs'); -const model = () => ({w: 960, h: 540, title: 'probe', slides: [ - {els: [{x: 60, y: 80, w: 800, role: 'H1', text: 'One'}, {x: 60, y: 200, w: 400, role: 'Body', text: 'body one'}]}, - {els: [{x: 60, y: 80, w: 800, role: 'H1', text: 'Two'}]}, -]}); -const served = create(model()).html; -const server = http.createServer((q, r) => { r.setHeader('content-type', 'text/html; charset=utf-8'); r.end(served); }); -await new Promise(r => server.listen(0, '127.0.0.1', r)); -const settled = p => p.waitForFunction(() => document.getElementById('autosave').dataset.state !== 'busy', null, {timeout: 15000}); -const spy = () => { window.__w = []; const o = Storage.prototype.setItem; Storage.prototype.setItem = function (k, v) { if (this === localStorage && k === KEY) window.__w.push([Math.round(performance.timeOrigin + performance.now()), JSON.parse(v).slides[0].els[0].text]); return o.call(this, k, v); }; }; -const has = p => p.evaluate(() => { try { return JSON.parse(localStorage.getItem(KEY)).slides[0].els[0].text; } catch (e) { return String(e); } }); -const until = (p, fn, ms = 15000) => p.waitForFunction(fn, null, {timeout: ms}); -let bad = 0, good = 0, errs = 0, late = 0, maxMs = 0; -for (let run = 0; run < RUNS; run++) { - const b = await pw.firefox.launch(); - try { - const ctx = await b.newContext(), url = `http://127.0.0.1:${server.address().port}/${ID}-${run}.html`, t = {id: ID, run}; - const A = await ctx.newPage(); await A.goto(url); await A.evaluate(() => localStorage.clear()); await A.reload(); await settled(A); - const B = await ctx.newPage(); await B.goto(url); await settled(B); - await A.evaluate(spy); await B.evaluate(spy); - await B.evaluate(() => nav(1)); - await A.evaluate(() => { snap(); slide().els[1].x = 123; save(); }); - await until(B, () => deck.slides[0].els[1].x === 123); - await B.evaluate(() => { nav(-1); sel.clear(); sel.add(0); render(); edit(0); }); await B.keyboard.type('typed in B'); - await A.evaluate(() => { snap(); slide().els[1].y = 250; save(); }); - await until(B, () => deck.slides[0].els[1].y === 250); - await until(A, () => deck.slides[0].els[0].text === 'typed in B'); - t.first = await has(A); - const s = Date.now(); - try { await until(A, () => JSON.parse(localStorage.getItem(KEY)).slides[0].els[0].text === 'typed in B', 2000); t.poll2s = true; } catch { t.poll2s = false; } - t.pollMs = Date.now() - s; - if (t.first !== 'typed in B') late++; maxMs = Math.max(maxMs, t.pollMs); - if (!t.poll2s) { - t.aNow = await has(A); t.bNow = await has(B); - const C = await ctx.newPage(); await C.goto(url + '?fresh'); t.freshNow = await has(C).catch(e => String(e)); await C.close(); - const r = Date.now(); let reads = 0; - while (Date.now() - r < 30000 && await has(A) !== 'typed in B') { reads++; await new Promise(x => setTimeout(x, 100)); } - t.settledMs = Date.now() - r; t.reads = reads; t.aEnd = await has(A); t.bEnd = await has(B); - t.aWrites = await A.evaluate(() => window.__w); t.bWrites = await B.evaluate(() => window.__w); - t.aFocus = await A.evaluate(() => [document.hidden, document.hasFocus()]); - } - const flagged = !t.poll2s; - if (flagged) { bad++; console.log('FLAG ' + JSON.stringify(t)); } else good++; - await ctx.close(); - } catch (e) { errs++; console.log('ERR ' + ID + ' ' + run + ' ' + String(e).slice(0, 200)); } - await b.close(); -} -console.log(`DONE ${ID} good ${good} bad ${bad} errs ${errs} storeLateAtFirstRead ${late} maxPollMs ${maxMs}`); -server.close(); diff --git a/.github/workflows/probe.yml b/.github/workflows/probe.yml deleted file mode 100644 index b6bc87f..0000000 --- a/.github/workflows/probe.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: probe -on: - push: - branches: ['claude/firefox-store-flake-*'] -jobs: - probe: - runs-on: ubuntu-latest - timeout-minutes: 40 - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: { node-version: 22 } - - run: npm i -D playwright && npx playwright install --with-deps chromium webkit firefox - timeout-minutes: 15 - - name: probe under suite load - run: | - for i in 1 2 3; do node .ci-probe/probe.mjs . 60 p$i > p$i.log 2>&1 & done - node --test --test-reporter=tap test/**/*.test.mjs > suite.log 2>&1 || true - wait - grep -hE '^(FLAG|ERR|DONE)' p*.log - grep -E '^not ok|^# (pass|fail) ' suite.log | cut -c1-140 - - name: probe alone - run: node .ci-probe/probe.mjs . 60 solo | grep -E '^(FLAG|ERR|DONE)' diff --git a/test/autosave.test.mjs b/test/autosave.test.mjs index eab9872..353176c 100644 --- a/test/autosave.test.mjs +++ b/test/autosave.test.mjs @@ -57,7 +57,7 @@ test('storage is a tier chain — localStorage → IndexedDB → memory — and assert.match(tpl, /let TIER=LS\?'local':'mem';/); assert.match(tpl, /indexedDB\.open\('decklet',2\)/, 'one db, bumped to v2 for the kv store'); assert.match(tpl, /for\(const s of \['h','kv'\]\)if\(!r\.result\.objectStoreNames\.contains\(s\)\)r\.result\.createObjectStore\(s\)/, 'the handle store and the kv store'); assert.match(tpl, /async function idbLoad\(\)/); assert.match(tpl, /if\(LS\)settle\(\);else\{autosave\('busy','Loading…'\);idbLoad\(\)\.then\(settle\)\}/, 'the deck draws from DECK first, the IndexedDB copy lands after'); - assert.match(tpl, /new BroadcastChannel\(NS\)/); assert.match(tpl, /addEventListener\('storage',e=>\{if\(e\.key===KEY\)receive/); + assert.match(tpl, /new BroadcastChannel\(NS\)/); assert.match(tpl, /addEventListener\('storage',e=>\{if\(e\.key===KEY\)\{receive/); const recv = tpl.slice(tpl.indexOf('function receive(m){'), tpl.indexOf('const slide=()=>')); assert.ok(!/store\.set\(|LS\.setItem|localStorage\.setItem|tell\(/.test(recv), 'receive() writes nothing and tells no one: ' + recv); assert.match(recv, /commitEdit\(\)/, 'an edit in flight is committed on top of what was heard');