aqua-listen: autosave keyed on kit id and clip ids, not the content hash; hash-keyed saves are adopted
A rebuilt page changed kit.hash and orphaned the listener's answers. The key is now aqua-listen.v2:<kit id>:<sorted clip ids>; pickLegacySave adopts the fullest earlier hash-keyed save of the same kit that names only this kit's clips. Erase also removes adoptable legacy saves. Browser smoke covers reload, rebuild, migration and erase. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5c377c1728
commit
c210dc9d86
5 changed files with 120 additions and 8 deletions
|
|
@ -42,7 +42,7 @@ node smoke.mjs dist/listen.html # optional
|
|||
- Title, id and group are hidden from the listener and appear only in the export. The intended feel is shown, since "did it land" needs it.
|
||||
- Order is shuffled from a random seed kept with the listener's answers (it is in the export). A pair is shuffled as one unit, with A/B position shuffled inside it.
|
||||
- Audio is embedded as-is (base64), so the page is about 1.4x the clip bytes. The build warns over 100 MB.
|
||||
- Autosave key is the kit id plus a hash of the manifest and clip bytes: a rebuilt kit with changed clips starts fresh instead of mixing answers.
|
||||
- Autosave key is the kit id plus the sorted clip ids (`aqua-listen.v2:<kit id>:<ids>`), not the content hash: a rebuilt page (edited note, re-rendered clip) keeps the listener's answers, and a kit with a different clip-id set starts fresh while the old entry stays in the browser. Saved state is the shuffle seed, answers by clip id and pair choices by `idA|idB`; a pair's A/B/same value is positional (A is the first of the pair in the seed's order), so it holds only while the manifest's clip order is unchanged. When the new key is empty, the page adopts the fullest earlier `aqua-listen:<kit id>:<hash>` save whose answers name only this kit's clips; a save already under the new key is never overwritten. "Erase my answers" removes the new key and any adoptable hash-keyed save.
|
||||
|
||||
### Export
|
||||
|
||||
|
|
@ -52,7 +52,7 @@ The blank verdict files this was meant to match were not found under `/opt/commo
|
|||
|
||||
### Browser smoke
|
||||
|
||||
`PLAYWRIGHT_CORE=/path/to/playwright-core CHROME=/path/to/chrome node smoke.mjs dist/listen.html` ticks through consent, answers a clip, reloads, exports, and fails on any network request or page error. It is not in `node test.mjs` because the repo carries no browser dependency.
|
||||
`PLAYWRIGHT_CORE=/path/to/playwright-core CHROME=/path/to/chrome node smoke.mjs dist/listen.html` ticks through consent, answers a clip, reloads, exports, then serves the page over a local http server, rebuilds it with a different content hash and checks that answers survive, that a hash-keyed save is adopted, and that erase leaves nothing to resurrect; it fails on any network request or page error. It is not in `node test.mjs` because the repo carries no browser dependency.
|
||||
|
||||
### Kits in the repo
|
||||
|
||||
|
|
|
|||
|
|
@ -100,4 +100,31 @@ function verdictMarkdown(v) {
|
|||
return L.join("\n") + "\n";
|
||||
}
|
||||
|
||||
module.exports = { SCHEMA, VERDICTS, DEVICES, AUDIO_EXT, validateManifest, planOrder, buildVerdict, verdictMarkdown, rng };
|
||||
// Autosave. The key names the kit by its id and its clip-id set, not by the content hash: a rebuild that fixes a note or
|
||||
// re-renders a clip is the same kit and keeps the listener's answers; a different clip-id set is a different kit and starts
|
||||
// fresh (the old entry is left untouched in the browser). Saved state is answers by clip id and pairs by "idA|idB", plus the
|
||||
// seed; the A/B/same value of a pair is positional (A is the first of the pair in the seed's order), so it stays meaningful
|
||||
// only while the manifest's clip order is unchanged.
|
||||
const SAVE_PREFIX = "aqua-listen.v2:";
|
||||
function saveKey(manifest) { return `${SAVE_PREFIX}${manifest.kit.id}:${manifest.clips.map((c) => c.id).sort().join(",")}`; }
|
||||
|
||||
// Earlier pages keyed the save by `aqua-listen:<kitid>:<8-hex content hash>`. Given every localStorage entry as
|
||||
// [{key, state}] (state already parsed, null if unparseable), returns the key of the legacy entry to adopt, or null:
|
||||
// same kit id, a seed, and answers/pairs that mention only clip ids of this kit. Fullest entry wins (most answered fields);
|
||||
// ties go to the later key so the choice is deterministic.
|
||||
function pickLegacySave(manifest, entries) {
|
||||
const ids = new Set(manifest.clips.map((c) => c.id)), prefix = `aqua-listen:${manifest.kit.id}:`;
|
||||
let best = null, bestScore = -1;
|
||||
for (const { key, state } of entries) {
|
||||
if (typeof key !== "string" || !key.startsWith(prefix) || !/^[0-9a-f]{8}$/.test(key.slice(prefix.length))) continue;
|
||||
if (!state || typeof state !== "object" || !state.seed || typeof state.answers !== "object" || !state.answers) continue;
|
||||
const pairs = state.pairs && typeof state.pairs === "object" ? state.pairs : {};
|
||||
if (!Object.keys(state.answers).every((id) => ids.has(id))) continue;
|
||||
if (!Object.keys(pairs).every((k) => k.split("|").every((id) => ids.has(id)))) continue;
|
||||
const score = Object.values(state.answers).reduce((n, a) => n + (a ? ["verdict", "landed", "reason"].filter((f) => a[f]).length : 0), 0) + Object.keys(pairs).length;
|
||||
if (score > bestScore || (score === bestScore && key > best)) { best = key; bestScore = score; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
module.exports = { SCHEMA, VERDICTS, DEVICES, AUDIO_EXT, validateManifest, planOrder, buildVerdict, verdictMarkdown, rng, saveKey, pickLegacySave };
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
// Browser smoke for a built page: node smoke.mjs listen.html (needs playwright-core and a Chromium; set PLAYWRIGHT_CORE=/path/to/playwright-core
|
||||
// and optionally CHROME=/path/to/chrome). Not part of `node test.mjs`: the repo has no browser dependency.
|
||||
import { createRequire } from "node:module";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { readFileSync, writeFileSync, mkdtempSync } from "node:fs";
|
||||
import { createServer } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { buildKit } from "./build.mjs";
|
||||
import { resolve, join } from "node:path";
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_CORE ?? "playwright-core");
|
||||
const file = resolve(process.argv[2]);
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROME || undefined });
|
||||
|
|
@ -46,4 +49,49 @@ await page.click("#export");
|
|||
check((await page.inputValue("#export-text")).includes('"verdict": "fix"'), "reload loses nothing: export after reload still has the answers");
|
||||
check(requests.length === 0, `no network requests (${requests.join(", ")})`);
|
||||
check(errors.length === 0, `no page errors (${errors.join("; ")})`);
|
||||
// ---- Autosave persistence across a rebuild. Served over http at one fixed path so the origin (and localStorage) is the same for
|
||||
// the page as given (A) and a rebuild of the same kit with a different content hash (B: a note edit and one byte appended to a clip).
|
||||
const html = readFileSync(file, "utf8"), kit = JSON.parse(html.match(/<script id="kit-data"[^>]*>([\s\S]*?)<\/script>/)[1].replace(/\\u003c/g, "<"));
|
||||
const tmp = mkdtempSync(join(tmpdir(), "aqua-listen-smoke-"));
|
||||
for (const c of kit.manifest.clips) { const buf = Buffer.from(kit.audio[c.id].b64, "base64"); writeFileSync(join(tmp, c.file), c.id === kit.manifest.clips[0].id ? Buffer.concat([buf, Buffer.from([0])]) : buf); }
|
||||
const B = buildKit({ ...kit.manifest, kit: { ...kit.manifest.kit, note: (kit.manifest.kit.note || "") + " (rebuilt)" } }, tmp);
|
||||
check(B.hash !== kit.hash, `the rebuilt page has a different content hash (${kit.hash} -> ${B.hash})`);
|
||||
let serving = html;
|
||||
const srv = createServer((q, r) => { r.setHeader("content-type", "text/html"); r.end(q.url.startsWith("/p/listen.html") ? serving : "x"); });
|
||||
await new Promise((ok) => srv.listen(0, "127.0.0.1", ok));
|
||||
const url = `http://127.0.0.1:${srv.address().port}/p/listen.html`;
|
||||
const ids = kit.manifest.clips.map((c) => c.id), mfst = kit.manifest.kit.id;
|
||||
const ctx2 = await browser.newContext(), pg = await ctx2.newPage(), errs2 = [];
|
||||
pg.on("pageerror", (e) => errs2.push(e.message));
|
||||
const begin = async () => { await pg.goto(url); if (await pg.locator("#consent").count()) { await pg.check("#consent"); await pg.click("button:has-text('Start listening')"); } };
|
||||
const firstId = async () => (await pg.locator("section.card").first().getAttribute("id")).slice(5);
|
||||
await begin();
|
||||
const id1 = await firstId(), card = () => pg.locator("#clip-" + id1);
|
||||
await card().locator("input[value=drop]").check(); await card().locator("input[type=text]").fill("rebuild survivor");
|
||||
await pg.reload();
|
||||
check(await card().locator("input[value=drop]").isChecked(), "persistence: answer survives a reload of the same page");
|
||||
serving = B.html; await pg.reload();
|
||||
check((await pg.locator("body").innerText()).includes("(rebuilt)"), "persistence: the rebuilt page is what loaded");
|
||||
check(await card().locator("input[value=drop]").isChecked() && (await card().locator("input[type=text]").inputValue()) === "rebuild survivor", "persistence: answers survive a rebuild with a different content hash");
|
||||
const keys = await pg.evaluate(() => Object.keys(localStorage));
|
||||
check(keys.length === 1 && keys[0].startsWith("aqua-listen.v2:"), `persistence: one save, under the hash-free key (${keys})`);
|
||||
// an earlier build's hash-keyed save is adopted when the new key is empty, and never overwrites a new-key save
|
||||
await pg.evaluate(() => localStorage.clear());
|
||||
const old = (seed, verdict) => JSON.stringify({ seed, answers: { [ids[ids.length - 1]]: { verdict, landed: 2, reason: "typed before the rebuild" } }, pairs: {}, device: "speakers", notes: "", listener: "Meta", consent: true });
|
||||
const oldKey = `aqua-listen:${mfst}:${kit.hash}`;
|
||||
await pg.evaluate(([k, v, k2, v2]) => { localStorage.setItem(k, v); localStorage.setItem(k2, v2); }, [oldKey, old(11, "keep"), `aqua-listen:other-kit:${kit.hash}`, old(12, "drop")]);
|
||||
await pg.reload();
|
||||
await pg.click("button:has-text('Start listening')").catch(() => {});
|
||||
const lastCard = pg.locator("#clip-" + ids[ids.length - 1]);
|
||||
check(await lastCard.locator("input[value=keep]").isChecked() && (await lastCard.locator("input[type=text]").inputValue()) === "typed before the rebuild", "migration: the hash-keyed save from the earlier build is adopted");
|
||||
check((await pg.evaluate(() => Object.keys(localStorage))).some((k) => k.startsWith("aqua-listen.v2:")) && (await pg.evaluate(([k]) => JSON.parse(localStorage.getItem(Object.keys(localStorage).find((x) => x.startsWith("aqua-listen.v2:")))).seed, [0])) === 11, "migration: saved under the new key, with the old seed");
|
||||
check(await pg.evaluate((k) => localStorage.getItem(k) !== null, `aqua-listen:other-kit:${kit.hash}`), "migration: another kit's entry is left untouched");
|
||||
await pg.evaluate(([k, v]) => { localStorage.setItem(k, v); localStorage.setItem(Object.keys(localStorage).find((x) => x.startsWith("aqua-listen.v2:")), v); }, [oldKey, old(13, "fix")]);
|
||||
await pg.reload();
|
||||
check(await pg.locator("#clip-" + ids[ids.length - 1]).locator("input[value=fix]").isChecked(), "migration: an existing new-key save is used, not overwritten by the hash-keyed one");
|
||||
await pg.evaluate(([k, v]) => localStorage.setItem(k, v), [oldKey, old(14, "drop")]);
|
||||
pg.once("dialog", (d) => d.accept()); await pg.click("text=Erase my answers"); await pg.waitForLoadState();
|
||||
check(await pg.evaluate(() => Object.keys(localStorage).filter((k) => k.startsWith("aqua-listen:") && !k.includes("other-kit") || k.startsWith("aqua-listen.v2:")).length) === 0 && await pg.locator("#consent").count() === 1, "erase removes the new-key save and the adoptable hash-keyed one (nothing resurrects)");
|
||||
check(errs2.length === 0, `persistence: no page errors (${errs2.join("; ")})`);
|
||||
srv.close();
|
||||
await browser.close();
|
||||
|
|
|
|||
|
|
@ -117,4 +117,34 @@ test("markup in a title cannot break the page", () => {
|
|||
const h = buildKit(m, dir).html;
|
||||
assert.equal((h.match(/<\/script>/g) || []).length, 3);
|
||||
});
|
||||
const st = (answers, pairs = {}) => ({ seed: 7, answers, pairs, consent: true });
|
||||
test("autosave key is stable across a content-hash change and moves with the clip-id set", () => {
|
||||
const m = mf([clip("b"), clip("a")]);
|
||||
assert.equal(L.saveKey(m), L.saveKey(mf([clip("a"), clip("b", { title: "reworded", feel: "other" })])), "title/feel edits and clip order do not move the key");
|
||||
assert.notEqual(L.saveKey(m), L.saveKey(mf([clip("a"), clip("b"), clip("c")])));
|
||||
assert.notEqual(L.saveKey(m), L.saveKey(mf([clip("a"), clip("z")])));
|
||||
assert.notEqual(L.saveKey(m), L.saveKey({ kit: { id: "k2", title: "Kit" }, clips: m.clips }));
|
||||
assert.ok(!/^aqua-listen:/.test(L.saveKey(m)), "new keys are never mistaken for hash-keyed legacy entries");
|
||||
const dir2 = mkdtempSync(join(tmpdir(), "aqlk-")); writeFileSync(join(dir2, "a.wav"), Buffer.alloc(50)); writeFileSync(join(dir2, "b.wav"), Buffer.alloc(50));
|
||||
const b1 = buildKit(m, dir2); writeFileSync(join(dir2, "b.wav"), Buffer.alloc(51)); const b2 = buildKit(m, dir2);
|
||||
assert.notEqual(b1.hash, b2.hash);
|
||||
assert.ok(b1.html.includes("saveKey") && !b1.html.includes("${kit.hash}"), "the built page keys on saveKey, not the hash");
|
||||
});
|
||||
test("legacy migration adopts the hash-keyed entry of the same kit", () => {
|
||||
const m = mf([clip("a"), clip("b")]);
|
||||
const old = { key: "aqua-listen:k1:93312816", state: st({ a: { verdict: "keep", landed: 3 } }) };
|
||||
assert.equal(L.pickLegacySave(m, [{ key: "unrelated", state: null }, old]), old.key);
|
||||
const fuller = { key: "aqua-listen:k1:00000001", state: st({ a: { verdict: "keep", landed: 3, reason: "x" }, b: { verdict: "fix" } }) };
|
||||
assert.equal(L.pickLegacySave(m, [old, fuller]), fuller.key, "the fuller entry wins");
|
||||
});
|
||||
test("legacy migration ignores other kits, foreign clip ids, malformed keys and empty state", () => {
|
||||
const m = mf([clip("a"), clip("b")]), ans = { a: { verdict: "keep" } };
|
||||
for (const e of [
|
||||
{ key: "aqua-listen:k2:93312816", state: st(ans) }, // another kit
|
||||
{ key: "aqua-listen:k1:93312816", state: st({ zz: { verdict: "keep" } }) }, // foreign clip id in answers
|
||||
{ key: "aqua-listen:k1:93312816", state: st(ans, { "a|zz": "A" }) }, // foreign clip id in pairs
|
||||
{ key: "aqua-listen:k1:nothex", state: st(ans) }, { key: "aqua-listen:k1:93312816:x", state: st(ans) },
|
||||
{ key: "aqua-listen:k1:93312816", state: null }, { key: "aqua-listen:k1:93312816", state: { answers: ans } }])
|
||||
assert.equal(L.pickLegacySave(m, [e]), null, JSON.stringify(e.key) + JSON.stringify(e.state));
|
||||
});
|
||||
console.log(`${n} tests passed`);
|
||||
|
|
|
|||
|
|
@ -1,11 +1,18 @@
|
|||
// Page glue. The kit (manifest, content hash, base64 audio, optional base64 PNGs per clip id) is in #kit-data; logic is AquaListen (logic.cjs, inlined).
|
||||
(() => {
|
||||
const L = globalThis.AquaListen, kit = JSON.parse(document.getElementById("kit-data").textContent);
|
||||
const app = document.getElementById("app"), KEY = `aqua-listen:${kit.manifest.kit.id}:${kit.hash}`;
|
||||
const app = document.getElementById("app"), KEY = L.saveKey(kit.manifest);
|
||||
let state = null, order = null;
|
||||
|
||||
const save = () => { try { localStorage.setItem(KEY, JSON.stringify(state)); } catch (e) { /* private mode: the export still works */ } };
|
||||
const load = () => { try { const s = JSON.parse(localStorage.getItem(KEY)); return s && s.seed ? s : null; } catch (e) { return null; } };
|
||||
const read = (k) => { try { return JSON.parse(localStorage.getItem(k)); } catch (e) { return null; } };
|
||||
const valid = (s) => (s && s.seed ? s : null);
|
||||
const legacyEntries = () => { const e = []; for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); e.push({ key: k, state: read(k) }); } return e; };
|
||||
// Own key first; if empty, adopt a hash-keyed save from an earlier build of this kit (L.pickLegacySave) and keep using the new key.
|
||||
const load = () => {
|
||||
const own = valid(read(KEY)); if (own) return own;
|
||||
try { const from = L.pickLegacySave(kit.manifest, legacyEntries()); return from ? valid(read(from)) : null; } catch (e) { return null; }
|
||||
};
|
||||
const h = (tag, attrs, ...kids) => {
|
||||
const e = document.createElement(tag);
|
||||
for (const [k, v] of Object.entries(attrs || {})) { if (k === "class") e.className = v; else if (k.startsWith("on")) e.addEventListener(k.slice(2), v); else if (v !== false && v != null) e.setAttribute(k, v === true ? "" : v); }
|
||||
|
|
@ -122,7 +129,7 @@
|
|||
panel.replaceChildren(h("h3", {}, "Your answers"), msg, area, h("div", { class: "row" }, buttons));
|
||||
area.focus(); area.select(); panel.scrollIntoView();
|
||||
}
|
||||
function reset() { if (confirm("Erase every answer you've given in this browser?")) { try { localStorage.removeItem(KEY); } catch (e) {} location.reload(); } }
|
||||
function reset() { if (confirm("Erase every answer you've given in this browser?")) { try { localStorage.removeItem(KEY); for (let k; (k = L.pickLegacySave(kit.manifest, legacyEntries())); ) localStorage.removeItem(k); } catch (e) {} location.reload(); } }
|
||||
|
||||
if (load() && load().consent) start(); else consent();
|
||||
})();
|
||||
|
|
|
|||
Loading…
Reference in a new issue