fix(web): an async message listener does not serialize, and a watchdog must not overwrite a real error

Three findings from the review-only PR #13, which put 28 already-merged
commits in front of a second reader, plus two comments that had gone false.

worker.js — `self.onmessage` was `async` and awaited `handle()`, which awaits
`server.flush()`. An async listener does NOT serialize: the event loop may
start the next `message` while an earlier one is suspended at an await, so two
`on_message`/`flush` pairs interleave and a later frame's replies can be posted
before an earlier frame's. That breaks the one rule the file names first — a
`GridUpdate::Cells` that overtakes its labels is DROPPED by the client's fold,
not replayed (gotcha 33) — and the pre-start `pending` drain had the same race
twice over, since `server` was assigned before the loop that drained it, so a
message arriving mid-drain overtook the frames it was queued behind. Every
frame is now chained onto one tail promise, which also makes "arrived before
start() finished" an ordinary case of the same rule instead of a second path.

app.js — the handshake watchdog fires 8s after the handshake and writes "the
peer did not answer". A peer that failed LOUDLY has already said something more
precise (worker `error`, `messageerror`, socket `error`), and the watchdog then
overwrote it with the vaguer guess. Those three paths now disarm it:
`setShellFailure` clears the timer rather than merely pre-empting it. The
watchdog is for silence only, which is what it was always for.

README — the "In the browser" section still said the deployed page needs a
server and that the in-page worker "is not built yet". Both landed in the same
unreviewed batch (improvise-9x6, improvise-djm), so the README described the
published site as a client with nowhere to connect while index.html described
it correctly. Rewritten, and it now states the caveat the commits state: no
line of that JavaScript has ever run.

Two comments that had gone false with it, and for the same reason — a follow-up
commit updated one copy and not the others. `web/app.js`'s keyboard note said
key resolution was "text entry, and nothing else" and that upstream keys would
work "until improvise-bpq2 lands"; bpq2 landed, moved the grid, panel and tile
cursors to the client, and settled that the host must not know the keymap.
`Host::handle`'s `ClientFrame::Key` arm said the same thing; 43422d4 corrected
the worker's copy of that argument and missed this one.

NOT VERIFIED, and it cannot be here: there is no browser and no headless DOM in
this environment, so neither JavaScript change has been executed. Both are
argued rather than tested, which is why each carries its argument in the file.
`node --check` passes on both, the wasm bundles build, and the Rust gates are
unchanged: 1172 passing / 0 failed, clippy clean, fmt clean, actionlint clean,
wasm32 clean for all seven bundle crates.

Declined from the same review, with the reason on the thread: `Host::commands`
can apply a batch's earlier commands before rejecting a later one. The finding
is correct, the hole is real, and it is already stated on `ClientFrame::Commands`
and in `Host::commands` — closing it means the basis check moving from the
command to the batch, which is a design change with ADR 001 consequences and
not a patch to land beside three small ones.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EoW5BB87ZZdm96SvBTWawH
This commit is contained in:
Edward Langley
2026-09-19 20:30:18 -07:00
parent d0cecff1be
commit bf02472d89
4 changed files with 98 additions and 56 deletions
+39 -24
View File
@@ -16,6 +16,17 @@
// 2. Await `flush()` after each message. `Storage::delete` is visible to
// `read`/`list` immediately but only reaches OPFS here (gotcha 28).
//
// Rule 1 is about frames within one call's replies AND about the calls
// themselves, which is why every message is chained onto one tail promise
// below rather than handled by an `async` listener: an `async` listener does
// not serialize. The event loop is free to start the next `message` while an
// earlier one is suspended at an `await`, so two `on_message`/`flush` pairs
// interleave and a later frame's replies can be posted before an earlier
// frame's. The chain is also what makes "frames that arrived before start()
// finished" an ordinary case of the same rule instead of a second code path
// with its own drain loop — and that loop had the race in it twice over,
// since `server` was set before it ran.
//
// The document is named in this worker's own URL — `new
// Worker('worker.js?doc=demo.improv')` — the analogue of the socket server
// naming it in the ws:// path. It is deliberately not a `ClientFrame`: the
@@ -44,10 +55,6 @@ async function seedBytes() {
}
let server = null;
// Frames that arrived before `start()` finished. The client sends its
// `Viewport` as soon as it loads, and losing it would leave the page showing
// an empty grid forever.
let pending = [];
function post(replies) {
for (const reply of replies) self.postMessage(reply);
@@ -59,27 +66,35 @@ async function handle(data) {
await server.flush();
}
self.onmessage = async (event) => {
if (!server) {
pending.push(event.data);
return;
}
try {
await handle(event.data);
} catch (err) {
// An unhandled rejection inside a `message` listener reaches the devtools
// console and nothing else. Say which frame it was; the main thread cannot
// see this and has no way to ask.
console.error("improvise worker: frame rejected", event.data, err);
}
};
(async () => {
// Startup, and the head of the chain. The client sends its `Viewport` as soon
// as it loads, so frames arrive before this settles; chaining onto it is what
// holds them, in arrival order, without a queue to drain.
const started = (async () => {
await init();
server = await start(DOC, await seedBytes());
const queued = pending;
pending = [];
for (const data of queued) await handle(data);
})().catch((err) => {
})();
started.catch((err) => {
console.error("improvise worker: failed to start", err);
});
// One frame at a time, in arrival order: the listener is deliberately NOT
// `async`. It appends to the chain and returns, so the ordering does not
// depend on when the event loop chooses to resume a suspended listener.
let tail = started.catch(() => {});
self.onmessage = (event) => {
tail = tail
.then(async () => {
// `start()` failed. There is nothing to answer with, and the main
// thread's handshake watchdog is what tells the user.
if (!server) return;
await handle(event.data);
})
.catch((err) => {
// An unhandled rejection inside a `message` listener reaches the
// devtools console and nothing else. Say which frame it was; the main
// thread cannot see this and has no way to ask. Caught here rather than
// left on the chain so one bad frame does not poison every later one.
console.error("improvise worker: frame rejected", event.data, err);
});
};