From 4eba2ebb83b77a22a9a33d63439a34037a8946a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 06:54:45 -0600 Subject: [PATCH 1/6] feat(pm-console): the app works with no connection, and sends what was done once when it is back The app could not open without a connection, showed nothing, and lost whatever was done. Now: - It opens: the service worker keeps the app's own files. - It shows what the device last saw: the worker keeps the last good answer to everything the app reads, under the address it was asked for. The network is asked first; a copy is shown only when it gives no answer or is too slow, and is marked as one. An answer that says no is never replaced by a copy. The header says offline and how old. - What the owner does is kept and sent once. Every action gets a name on the device (a UUID) and is written to the browser's database before it is sent (public/outbox.js). With no connection it waits and is sent when there is one: by the page, or by the service worker if the app is closed (Background Sync). - The platform does an action once under its name however often it arrives. The edge writes down each name it did with its answer; a machine keeps its own record (src/named.ts, one for actions sent straight to it, relayed to it, and held for it). - What may have changed is not sent unasked: a merge, a deploy, a cancel, an unblock and a service action are sent by themselves only within ten minutes, and after that wait for the owner to look again. A merge names the commit the owner was shown, and GitHub merges only that. What sets the connection up or carries a secret is never kept. - A sign-in that ran out is told from no connection. More, On this device lists what is waiting, kept back, failed, with the platform, and sent; and can fetch a copy of every screen before a flight. Also: a first load that failed said "Loading" for ever instead of why; a toast's Undo was written in the page's ink, not the toast's. 321 tests under bun (was 278). 80 planted faults, all caught. In a real Chrome against the demo laptop and the demo edge, light and dark: taken offline it opens, shows, keeps, and sends each once; and with the app closed the worker sends when woken. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- ...rchitecture_pm_platform_cloudflare_core.md | 73 +++ pm-stack/console/README.md | 53 ++ pm-stack/console/edge/README.md | 12 + pm-stack/console/edge/build.mjs | 2 +- pm-stack/console/edge/src/edge.ts | 144 ++++- pm-stack/console/public/app.css | 26 + pm-stack/console/public/app.js | 514 +++++++++++++++-- pm-stack/console/public/index.html | 2 + pm-stack/console/public/outbox.js | 341 ++++++++++++ pm-stack/console/public/sw.js | 240 +++++++- pm-stack/console/scripts/demo-state.ts | 8 + pm-stack/console/scripts/edge-demo.ts | 3 + pm-stack/console/scripts/edge-smoke.ts | 2 +- pm-stack/console/src/actions.ts | 2 +- pm-stack/console/src/named.ts | 88 +++ pm-stack/console/src/ops.ts | 15 +- pm-stack/console/src/server.ts | 68 ++- pm-stack/console/src/sync.ts | 61 +- pm-stack/console/test/app.test.ts | 141 +++++ pm-stack/console/test/console.test.ts | 57 +- pm-stack/console/test/edge.test.ts | 283 +++++++++- pm-stack/console/test/outbox.test.ts | 524 ++++++++++++++++++ pm-stack/console/test/sw.test.ts | 472 +++++++++++++++- pm-stack/console/test/work.test.ts | 72 +++ 24 files changed, 3085 insertions(+), 118 deletions(-) create mode 100644 pm-stack/console/public/outbox.js create mode 100644 pm-stack/console/src/named.ts create mode 100644 pm-stack/console/test/outbox.test.ts diff --git a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md index 60a1396cd8..4b344626d2 100644 --- a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md +++ b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md @@ -362,3 +362,76 @@ Worker runtime with the switch on: all checks passed. A phone-sized Chrome over the Cloudflare screen in each state with the new control, and axe-core over the toasts and the danger dialog while they show, light and dark: no violations (three before the inks). + +## 2026-11-23T12:52Z Update: in service, and step 4 (with no connection) + +**Step 3 is in service.** Merged as #13205. At 12:00Z the public health +answer said `primary: true`, both tokens present, nothing refused, +and its own read of each kind (the board, pull requests, ranked issues, +the prompts) good with the real tokens. Not checked: a write with the +real token, which needs the owner's sign-in; a refusal would show under +`refused` and be the laptop's to do. + +The deploy of that merge failed twice at its rehearsal on a scratch +Worker: Cloudflare answered "This Worker does not exist" (10007) about +a Worker wrangler had uploaded a second before. The real Worker was +deployed by a manual run without the rehearsal; standing a Worker up is +now made up to four times (#13235), and the next deploy passed on the +third. + +**Step 4 is built: the app with no connection.** Decision 4 above, as +it turned out: + +- **The device keeps a copy of everything it read.** The service + worker asks the network first and keeps each good answer under the + address it was asked for: the app's files, the three documents, and + every screen's own read. A copy is shown only when the network gives + no answer or is too slow to wait for, and is marked as one; an answer + that says no is never replaced by a copy. So nothing about a screen + had to change for it to work offline, and a screen added later works + offline from its first visit. +- **Every action has a name, given on the device.** It is written to + the browser's database before it is sent, and sent at once when there + is a connection, as before. With none it waits, and goes when there + is one: from the page, or from the service worker if the app is + closed (Background Sync). One file (`public/outbox.js`) holds the + rules for both. +- **Once, however often it arrives.** The edge writes down each name it + did with its answer; a machine does the same (`src/named.ts`, one + record for actions sent straight to it, relayed to it, and held for + it). A name offered again is answered from the record. This is the + rule that already protected a relayed action whose answer was lost, + extended back to where the action starts. +- **What may have changed is not sent unasked.** The list the platform + already had for a machine that is away (what may be done late) is the + device's list too. A merge, a deploy, a cancel, an unblock and a + service action are kept, sent by themselves only within ten minutes, + and after that wait for the owner to look again. A merge now names + the commit the owner was shown, and GitHub merges only that: this + guards a merge asked for a second ago as much as one kept for hours. +- **Signed out is told from offline** by asking past the service + worker without following the way to the sign-in page. + +What the owner sees: `offline` and how old the state is in the corner; +a line under the header saying there is no connection and what is kept; +More, On this device, where what is waiting, kept back, failed, with +the platform or sent can be looked at, dropped, sent or tried again, +and where a copy of every screen can be fetched before a flight. + +Checked: 321 tests under bun and the keeper's 25. Planted faults: 23 in +the once-only rule on the edge and the laptop, 57 on the device (the +outbox, the worker, the app's wording), all caught. In a real Chrome, +against the demo laptop and the demo edge, light and dark: the app +taken offline opens, shows each screen it had seen, says so, keeps +three actions across a reload, sends each once when the connection is +back, answers a repeat of each name without doing it again, keeps a +three-hour-old merge back until it is confirmed, and forgets when +asked; and with the app closed, the worker, woken as the browser wakes +it, sends what was kept. axe-core over all 20 screens, the dialogs, the +toasts and the new screen in each state: no violations. + +Not checked: a real phone with no signal, and the Android app (it is +this site in Chrome, so nothing in it changed). Not done: copies are +not encrypted on the device beyond what the device does itself; a +screen never visited has no copy until it is visited or "keep a copy of +every screen" is pressed. diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 91db295072..cebdbc2247 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -178,6 +178,54 @@ Set `PM_CONSOLE_EDGE_URL` to turn the reporting on; `scripts/expose.py` does that when it sends the hostname through the Worker. Without it this service reports to nobody and serves the app itself, as before. +### With no connection + +The app opens and can be used with no connection, in a browser and in +the Android app alike (which is the same site in Chrome). + +- **It opens.** The service worker (`public/sw.js`) keeps the app's own + files, fetched when it is installed. +- **It shows what the device last saw.** The worker keeps the last + answer to everything the app reads: the three documents and every + screen's own read, each under the address it was asked for. The + network is always asked first; a copy is shown only when the network + gives no answer (or is too slow to wait for), and is marked as a copy. + An answer that says no (a refusal, a way to the sign-in page, an + error) is passed on as it is and never papered over. The corner of + the header then says `offline` and how old the state is, and a line + under the header says there is no connection. A screen the device + has never seen says it has no copy of it. More, On this device has + "Keep a copy of every screen now", for before a flight. +- **What the owner does is kept and sent once.** Every action is given + a name on the device (a UUID) and written to the browser's own + database before it is sent (`public/outbox.js`). With no connection it + waits there, and is sent when the connection is back: by the page if + the app is open, by the service worker if it is not (Background Sync, + where the browser has it). The platform does an action once under its + name however often it arrives, so sending again after an answer that + never came is safe: Cloudflare keeps the names it did (a week, three + hundred), and a machine keeps its own (`src/named.ts`). +- **Not everything is sent unasked.** What the owner says or decides + (a prompt, a reply, a rank, a note, a bug, an answer) does not go + stale and goes whenever it can. A merge, a deploy, a cancel, an + unblock and a service action act on something that may have changed: + they are kept too, sent by themselves only within ten minutes of + being asked for, and after that wait under "kept back" until the + owner looks again and says to send them. A merge also carries the + commit the owner was shown, and GitHub merges only that. What sets + the connection up or carries a secret (notifications, phones, + sign-in, the Cloudflare switch) is never kept: it says it needs a + connection. +- **A sign-in that ran out is not "offline".** The app tells the two + apart by asking past the worker without following the way to the + sign-in page. Signed out, it shows what it last saw, keeps what is + done, and says to sign in again; signing out by hand makes the device + forget what it last saw. + +More, On this device lists what is waiting, kept back, could not be +done, is with the platform for a machine, and was sent; each can be +dropped, sent, or tried again there. + ### Merges deploy themselves `pm-console-redeploy.timer` runs `redeploy.sh` every minute. When the @@ -289,3 +337,8 @@ itself, and More, Phones offers the newest release to the signed-in owner at `/console/pm-console.apk`, so the phone gets the app from the site it opens. Until then the host signs, and its build is what is offered. See its README. + +Because it is the site, it opens with no connection and keeps what is +done there exactly as the site does (above, "With no connection"): text +dictated or shared into it with no signal lands in Ask, is kept when +sent, and goes when the phone is connected again. diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index 2e34570409..c54333f353 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -330,5 +330,17 @@ open nothing. laptop cannot repeat it; an action that was relayed and got no answer is only ever resolved by the laptop, which wrote its name down before starting. That is the rule against doing anything twice. +- The same rule reaches the device. An action may come with a name the + device gave it (`id`, a UUID), because a device with no connection + keeps what the owner did and sends it later, and again if it never + heard back. What the edge does itself it writes down under that name + before starting and with its answer after (a week, three hundred + names, an answer of up to four thousand characters): the name offered + again is answered from that, marked `again`, and not done again. One + still being done is answered 409 `running`; one started by an object + that was put away before it ended is said to be unknown, once, and + not retried. What goes to the laptop goes under the same name, and + the laptop keeps the record. Held twice under one name, an action + waits once. - The storage is one Durable Object. A section larger than one stored value is kept in pieces. diff --git a/pm-stack/console/edge/build.mjs b/pm-stack/console/edge/build.mjs index 9cbac1b1d2..f62e73fbb8 100644 --- a/pm-stack/console/edge/build.mjs +++ b/pm-stack/console/edge/build.mjs @@ -14,7 +14,7 @@ const dist = join(here, "dist"); rmSync(dist, { recursive: true, force: true }); mkdirSync(join(dist, "console"), { recursive: true }); mkdirSync(join(dist, "icons"), { recursive: true }); -for (const name of ["index.html", "app.js", "app.css", "icon.svg", "sw.js"]) { +for (const name of ["index.html", "app.js", "outbox.js", "app.css", "icon.svg", "sw.js"]) { cpSync(join(here, "..", "public", name), join(dist, "console", name)); } for (const name of ["icon-192.png", "icon-512.png", "icon-maskable-512.png", "apple-touch-icon.png"]) { diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index f01b796005..dd551c7ec7 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -165,11 +165,28 @@ const SELF_CHECK_EVERY_MS = 60 * 60_000; const KEY_FETCH_EVERY_MS = 30_000; const STATIC: Record = { "app.js": "text/javascript; charset=utf-8", + "outbox.js": "text/javascript; charset=utf-8", "app.css": "text/css; charset=utf-8", "icon.svg": "image/svg+xml", "sw.js": "text/javascript; charset=utf-8", }; const ACT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +/** How many actions done here under a name are remembered, for how + * long, and how much of each answer is kept with it. A device offline + * for longer than this that sends again is answered as if for the + * first time; the names are its own, so nobody else can collide. */ +const ACTED_KEPT = 300; +const ACTED_FOR_MS = 7 * 24 * 60 * 60_000; +const ACTED_BODY_CHARS = 4000; + +/** An action done here under the name the device sent it with. */ +interface Acted { + at: number; + kind: string; + state: "running" | "done"; + status?: number; + body?: Record; +} const ICONS = /^\/icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png$/; interface Mirror { @@ -250,6 +267,8 @@ export class Edge { * they are a machine's to read, as they were before this side read * anything. */ private unread = new Map(); + /** Names of actions this object is doing right now. */ + private doing = new Set(); /** Both of those have been read back from storage. They are kept * there because this object is put away when idle: one that forgot * them would claim each section again on every start, and a machine, @@ -930,14 +949,22 @@ export class Edge { * recorded before and after like own(). It is never sent to a machine, * so no machine can do it a second time. The sections it changed that * this side reads are read again before the answer goes back. */ - private async directAct(kind: string, args: Record, by: string, via: string): Promise { + private async directAct( + kind: string, + args: Record, + by: string, + via: string, + id: string | null = null, + ): Promise { const cfg = await this.config(); const direct = this.mine(cfg); if (!direct) throw new Error("this cannot be done from here right now"); const action = direct.table[kind]; const base = { at: new Date(this.now()).toISOString(), who: by, via, action: kind, args: action.audit(args) }; await this.audit({ ...base, phase: "start" }); - const entry = { id: crypto.randomUUID(), kind, at: base.at, by, note: "" }; + // On the record under the name it was sent with, so the device that + // sent it can find how it came out. + const entry = { id: id ?? crypto.randomUUID(), kind, at: base.at, by, note: "" }; /** The task of a prompt: the packet carries the issue's number, and * the text is the owner's own. */ const prompt = (packet: unknown) => @@ -1483,7 +1510,7 @@ export class Edge { if (!sameSiteWrite(req)) return json({ error: "this request did not come from the console" }, 403); if (!(seg.length === 1 && seg[0] === "act")) return next("relay", { mode: "live" }); if (Number(req.headers.get("content-length") ?? "0") > ACT_LIMIT) return json({ error: "too large" }, 413); - let body: { kind?: unknown; args?: unknown }; + let body: { kind?: unknown; args?: unknown; id?: unknown }; try { const text = await req.text(); if (text.length > ACT_LIMIT) return json({ error: "too large" }, 413); @@ -1497,6 +1524,9 @@ export class Edge { if (args === null || typeof args !== "object" || Array.isArray(args)) { return json({ error: "args: expected an object" }, 400); } + // The name the device gave this, if it gave one: whatever does + // it, here or on a machine, does it once under that name. + const id = typeof body.id === "string" && ACT_ID.test(body.id) ? body.id : null; if (!Object.hasOwn(this.table, kind)) { // One this side does itself: it runs here, through the // console's own classes, and is never sent to a machine, so no @@ -1508,7 +1538,9 @@ export class Edge { !this.refusedKinds().includes(kind) ) { try { - return await this.directAct(kind, args as Record, by, who.via); + return await this.once(id, kind, () => + this.directAct(kind, args as Record, by, who.via, id), + ); } catch (error) { // Refused here before anything was done: a machine's, below. if (!(error instanceof HandOver)) throw error; @@ -1516,33 +1548,110 @@ export class Edge { } // The host's to do. The stateless part relays it, and if the // host cannot be reached comes back to have it held. - // It is named here, before it goes anywhere. If the host's answer - // is lost on the way back, the action is held under the same - // name, and the host, which wrote the name down before starting, - // does not do it a second time. + // It goes under the device's name for it, or one given here, + // before it goes anywhere. If the host's answer is lost on the + // way back, the action is held under the same name, and the + // host, which wrote the name down before starting, does not do + // it a second time. return next("relay", { mode: "act", - id: crypto.randomUUID(), + id: id ?? crypto.randomUUID(), kind, args, who: by, holdable: HOLDABLE.has(kind), }); } - return await this.own(kind, args as Record, by, who.via); + return await this.once(id, kind, () => this.own(kind, args as Record, by, who.via, id)); } catch (error) { - if (error instanceof OpError) return json({ error: error.message }, error.status); - console.error(`pm-edge: ${method} ${path}: ${(error as Error).message}`); - return json({ error: "the edge could not do that" }, 500); + return this.failed(error, `${method} ${path}`); } } + /** What a thrown error is answered with. */ + private failed(error: unknown, what: string): Response { + if (error instanceof OpError) return json({ error: error.message }, error.status); + console.error(`pm-edge: ${what}: ${(error as Error).message}`); + return json({ error: "the edge could not do that" }, 500); + } + + /** Do something once under the name the device sent it with. A device + * that is offline keeps what the owner did and sends it when it is + * connected again, and sends it again if it never heard back: the + * second arrival is answered from what was written down, not done + * again. With no name it is simply done. `work` may hand the action + * over to a machine (HandOver): then nothing was done here, nothing + * is written down, and the machine keeps its own record under the + * same name. */ + private async once(id: string | null, kind: string, work: () => Promise): Promise { + if (id === null) return work(); + const key = `a:${id}`; + const before = ((await this.kv.get(key)) as Acted | undefined) ?? null; + if (before?.state === "done") return json({ ...before.body, again: true }, before.status ?? 200); + if (before?.state === "running") { + if (this.doing.has(id)) return json({ error: "This is still being done.", running: true }, 409); + // Started, and this object was put away before it ended. Whether + // it happened is not known, and doing it again could do it twice. + const body = { error: "Cloudflare restarted while doing this; check whether it happened before trying again." }; + await this.kv.put(key, { at: this.now(), kind, state: "done", status: 502, body } satisfies Acted); + return json({ ...body, again: true }, 502); + } + this.doing.add(id); + try { + await this.kv.put(key, { at: this.now(), kind, state: "running" } satisfies Acted); + await this.actedIndex(id); + let res: Response; + try { + res = await work(); + } catch (error) { + if (error instanceof HandOver) { + await this.kv.delete(key); + throw error; + } + res = this.failed(error, `${kind} (${id})`); + } + const body = (await res + .clone() + .json() + .catch(() => null)) as Record | null; + const small = body !== null && JSON.stringify(body).length <= ACTED_BODY_CHARS; + await this.kv.put(key, { + at: this.now(), + kind, + state: "done", + status: res.status, + // An answer too long to keep is kept as how it went, without what it said. + body: small ? body : res.ok ? { ok: true, result: null } : { error: "it could not be done" }, + } satisfies Acted); + return res; + } finally { + this.doing.delete(id); + } + } + + /** Note a name as used, and forget the ones that are too old or too many. */ + private async actedIndex(id: string): Promise { + const now = this.now(); + const index = ((await this.kv.get("acted")) as { id: string; at: number }[] | undefined) ?? []; + index.push({ id, at: now }); + const keep = index.filter((entry) => now - entry.at < ACTED_FOR_MS).slice(-ACTED_KEPT); + const kept = new Set(keep.map((entry) => entry.id)); + for (const entry of index) if (!kept.has(entry.id)) await this.kv.delete(`a:${entry.id}`); + await this.kv.put("acted", keep); + } + /** An action this side runs itself, recorded before and after. */ - private async own(kind: string, args: Record, by: string, via: string): Promise { + private async own( + kind: string, + args: Record, + by: string, + via: string, + id: string | null = null, + ): Promise { const action = this.table[kind]; const base = { at: new Date(this.now()).toISOString(), who: by, via, action: kind, args: action.audit(args) }; await this.audit({ ...base, phase: "start" }); - const entry = { id: crypto.randomUUID(), kind, at: base.at, by, note: "" }; + const entry = { id: id ?? crypto.randomUUID(), kind, at: base.at, by, note: "" }; try { const result = await action.run(args); await this.audit({ ...base, phase: "done", ok: true }); @@ -1586,6 +1695,11 @@ export class Edge { } await this.ready(); const held = await this.heldList(); + // Offered again under a name that is already waiting (the device + // never heard that it was kept): it is kept once. + if (typeof body?.id === "string" && held.some((h) => h.id === body.id)) { + return json({ ok: true, held: true, result: null, again: true }); + } if (held.length >= HELD_MAX) { return json({ error: "The laptop cannot be reached, and too much is already waiting for it." }, 503); } diff --git a/pm-stack/console/public/app.css b/pm-stack/console/public/app.css index 632af5fdf9..c41c561417 100644 --- a/pm-stack/console/public/app.css +++ b/pm-stack/console/public/app.css @@ -103,6 +103,26 @@ a.button { .fresh.down { color: var(--bad); } +/* The line under the header: no connection, and what is kept to send. */ +.kept { + display: block; + width: 100%; + max-width: 760px; + min-height: 44px; + margin: 0 auto; + padding: 10px 16px; + border: 0; + border-bottom: 1px solid var(--line); + border-radius: 0; + background: var(--panel-2); + color: var(--text); + font-size: 0.9rem; + font-weight: 500; + text-align: left; +} +.kept.warn { + color: var(--warn); +} main { max-width: 760px; margin: 0 auto; @@ -627,6 +647,12 @@ pre { background: var(--bad); color: var(--bad-ink); } +/* A button on it (Undo) is written in the toast's own ink: the page's + text colour is made for the page, not for this green or red. */ +.toast button { + color: inherit; + border-color: currentColor; +} dialog { width: min(92vw, 520px); border: 1px solid var(--line); diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index a7349e182d..7b048ef720 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -11,6 +11,7 @@ const view = $("view"); const tabsEl = $("tabs"); const toastEl = $("toast"); const freshEl = $("fresh"); +const keptEl = $("kept"); // ---- small helpers ----------------------------------------------------- @@ -134,6 +135,48 @@ const etags = {}; const asOf = {}; let me = {}; let signedOut = false; +/** The last answer came from the copy this device keeps, not from the + * network: there is no connection (or no sign-in), and what is shown is + * what the device last saw. */ +let offline = false; + +/** What the owner did, kept on this device until the platform has it + * (outbox.js). Without a page there is none. */ +const Outbox = typeof self !== "undefined" ? self.PMOutbox : undefined; +let outbox = null; +/** The entries, as last read: for the line that says what is kept. */ +let kept = []; + +/** Why a request got no answer: no sign-in, or no connection. Asked + * past the service worker, which would otherwise answer from its copy, + * and without following the way to the sign-in page, which is how the + * two are told apart. */ +async function probe() { + try { + const res = await fetch(`${API}me`, { redirect: "manual", cache: "no-store", headers: { "X-PM-Probe": "1" } }); + signedOut = res.type === "opaqueredirect" || res.status === 401 || res.status === 403; + return true; + } catch { + signedOut = false; + return false; + } +} + +/** Note whether an answer was the network's or this device's copy. */ +function noteAnswer(res) { + const was = offline; + offline = res.headers.get("x-pm-offline") === "1"; + // Gone: find out which it is, a sign-in that ran out or no connection. + if (offline && !was) probe().then(drawKept); + // Back: send what was kept meanwhile. + if (!offline && was) { + signedOut = false; + flushOutbox(); + } +} + +const NO_ANSWER = "There is no connection, and this device has no copy of this yet."; +const NO_SIGNIN = "Your sign-in has run out. Reload to sign in again."; async function api(path, body) { const init = @@ -148,11 +191,12 @@ async function api(path, body) { try { res = await fetch(API + path, init); } catch { - // A sign-in that has run out answers with a redirect to another site, - // which a fetch may not follow. - signedOut = navigator.onLine !== false; - throw new Error(signedOut ? "Your sign-in may have run out. Reload to sign in again." : "You are offline."); + // No answer and no copy. A sign-in that has run out answers with a + // redirect to another site, which a fetch may not follow. + await probe(); + throw new Error(signedOut ? NO_SIGNIN : NO_ANSWER); } + if (body === undefined) noteAnswer(res); let data = null; let read = true; try { @@ -175,9 +219,10 @@ async function loadDoc(name) { try { res = await fetch(`${API}doc/${name}`, { headers: etags[name] ? { "If-None-Match": etags[name] } : {} }); } catch { - signedOut = navigator.onLine !== false; - throw new Error(signedOut ? "Your sign-in may have run out. Reload to sign in again." : "You are offline."); + await probe(); + throw new Error(signedOut ? NO_SIGNIN : NO_ANSWER); } + noteAnswer(res); if (res.headers.get("x-as-of")) asOf[name] = Number(res.headers.get("x-as-of")); // Served from the edge: when the laptop behind it last reported. if (res.headers.get("x-host-seen")) hostSeen = Number(res.headers.get("x-host-seen")) || null; @@ -215,21 +260,151 @@ let hostSeen = null; const HOST_QUIET_MS = 3 * 60_000; const HELD_NOTE = "Held: the laptop cannot be reached. It will be sent when it is back."; -/** Run one action, say how it went, and draw what changed. */ +const KEPT_NOTE = "Kept on this device. It is sent when you are connected."; + +/** Read what is kept, for the line that says so and the screen that lists it. */ +async function readKept() { + if (!outbox) return []; + try { + kept = (await outbox.all()).sort((a, b) => b.at - a.at); + } catch { + // The list as it was is better than none. + } + drawKept(); + return kept; +} + +/** Ask for what is kept to be sent when there is a connection, also if + * the app is closed by then (where the browser can do that). */ +function sendWhenConnected() { + navigator.serviceWorker?.ready.then((reg) => reg.sync?.register("pm-outbox")).catch(() => {}); +} + +/** What a flush did, in a line. */ +export function flushSaid(changed) { + const n = (state) => changed.filter((e) => e.state === state).length; + const sent = n("done") + n("held"); + const parts = [ + sent ? `${sent} sent` : "", + n("failed") ? `${n("failed")} could not be done` : "", + n("stale") ? `${n("stale")} kept back for you to look at` : "", + ].filter(Boolean); + return parts.length ? `What you did offline: ${parts.join(", ")}.` : ""; +} + +let flushing = null; +/** Send what is waiting, if anything is. One at a time, here and in + * the service worker: whichever holds the lock sends. */ +function flushOutbox() { + if (!outbox || !Outbox) return Promise.resolve(); + flushing ??= (async () => { + const run = async () => { + const out = await Outbox.flush(outbox, (entry) => Outbox.httpSend(entry)); + if (out.signin) signedOut = true; + const said = flushSaid(out.changed); + if (said) { + toast(said, out.changed.some((e) => e.state === "failed")); + refresh(true); + } + }; + try { + if (navigator.locks?.request) await navigator.locks.request("pm-outbox", { ifAvailable: true }, (lock) => (lock ? run() : undefined)); + else await run(); + } catch { + // Nothing was lost: what is waiting is still written down. + } finally { + flushing = null; + await readKept(); + // Still something waiting (the connection went again, or was + // never there): the browser is asked to wake the worker for it, + // in case the app is closed by the time there is one. + if (kept.some((e) => e.state === "waiting")) sendWhenConnected(); + } + })(); + return flushing; +} + +/** Give an action its name, write it down, and try to send it. Says + * what became of it: "done" (with its result), "held" (the platform + * has it, for a machine), "kept" (it waits on this device), or + * "failed"/"refused" (with why; nothing is kept). */ +async function submit(kind, args) { + if (!Outbox) return { state: "refused", note: "This page cannot send that." }; + const entry = Outbox.make(kind, args, Date.now()); + // What needs a connection by its nature is not written down. + let keeps = Outbox.rule(kind) !== "now" && outbox !== null; + if (keeps) { + try { + await outbox.put(entry); + } catch { + keeps = false; + } + } + const answer = await Outbox.httpSend(entry); + const out = Outbox.classify(answer); + const end = async (state, more = {}) => { + if (keeps) await outbox.put({ ...entry, ...more, state, tries: 1, triedAt: Date.now(), endedAt: Date.now() }).catch(() => {}); + }; + if (out.state === "done") { + await end("done", { result: out.result }); + return { state: "done", result: out.result }; + } + if (out.state === "held") { + await end("held", { note: out.note }); + return { state: "held" }; + } + if (out.state === "failed") { + // Said at once, to the owner's face: nothing to keep of it. + if (keeps) await outbox.remove(entry.id).catch(() => {}); + return { state: "failed", note: out.note }; + } + // Not taken: no connection, no sign-in, or nothing to take it just now. + if (out.signin) signedOut = true; + if (!keeps) { + const note = answer.network ? "This needs a connection." : out.signin ? NO_SIGNIN : out.note; + return { state: "refused", note }; + } + if (out.note) await outbox.put({ ...entry, note: out.note, tries: 1, triedAt: Date.now() }).catch(() => {}); + sendWhenConnected(); + return { state: "kept", id: entry.id, note: out.signin ? "Kept on this device. Sign in again to send it." : out.note ? `Kept on this device: ${out.note}` : KEPT_NOTE }; +} + +/** Take back something kept that has not been sent. */ +async function unkeep(id) { + await outbox?.remove(id).catch(() => {}); + toastEl.hidden = true; + await readKept(); + draw(); +} + +/** Run one action, say how it went, and draw what changed. With no + * connection it is kept on this device and sent when there is one. + * Answers with the action's result when it was done; with something + * that is not nothing when the platform or this device has it to do + * later (so a form may be cleared: it will not be lost); and with null + * when it was not done and nothing was kept. */ async function act(kind, args, done, button) { if (button) button.disabled = true; - try { - const { result, held } = await api("act", { kind, args }); - // Held is not done: the caller is told nothing happened yet, and the - // owner is told where it is waiting. - toast(held ? HELD_NOTE : typeof done === "function" ? done(result) : done); + const out = await submit(kind, args); + await readKept(); + if (out.state === "done") { + toast(typeof done === "function" ? done(out.result) : done); await refresh(true); - return held ? null : result; - } catch (error) { - toast(error.message, true); - if (button) button.disabled = false; - return null; + return out.result ?? { done: true }; + } + if (out.state === "held") { + toast(HELD_NOTE); + await refresh(true); + return { held: true }; } + if (out.state === "kept") { + toast(out.note, false, () => unkeep(out.id)); + draw(); + return { kept: true }; + } + toast(out.note, true); + if (button) button.disabled = false; + return null; } // ---- now --------------------------------------------------------------- @@ -479,15 +654,18 @@ function flushPending() { } async function sendAnswer(kind, args, key, said) { - try { - const { result, held } = await api("act", { kind, args }); - if (result?.refused?.length) toast(`Not recorded: ${result.refused[0].why}`, true); + const out = await submit(kind, args); + await readKept(); + if (out.state === "failed" || out.state === "refused") toast(out.note, true); + else { + if (out.result?.refused?.length) toast(`Not recorded: ${out.result.refused[0].why}`, true); else { answeredHere.add(key); // A choice was already acknowledged when it was made (with its // Undo); anything else says so now, or the question would simply // vanish. - if (held) toast(HELD_NOTE); + if (out.state === "held") toast(HELD_NOTE); + else if (out.state === "kept") toast(out.note); else if (said) toast(said); } picks.delete(key); @@ -496,8 +674,6 @@ async function sendAnswer(kind, args, key, said) { docs.questions.questions.total = open.length; docs.questions.questions.open = open; } - } catch (error) { - toast(error.message, true); } // The list above is already right; only the counts need reading again. await loadDoc("core").catch(() => {}); @@ -878,6 +1054,7 @@ function viewMore() { tile("more/phone", "Phones", "the Android app and its home-screen widget"), tile("more/signin", "Sign-in", "Google first, the emailed code as the fallback"), tile("more/away", "Cloudflare", "what it does by itself, and what waits for a machine"), + tile("more/device", "On this device", "what is kept here to send, and what it shows with no connection"), tile("more/releases", "Releases", "what is deployed, the Android app, and putting either out again"), ), ]; @@ -888,7 +1065,18 @@ function viewMore() { h("h2", {}, "This app"), h("p", { class: "meta" }, `Signed in as ${me.email || me.certName || me.via || "…"}`), me.androidApp ? h("a", { class: "link", href: "/console/pm-console.apk" }, "Android app", h("span", {}, "Download the signed build for this phone")) : null, - h("a", { class: "link", href: "/cdn-cgi/access/logout" }, "Sign out"), + h( + "a", + { + class: "link", + href: "/cdn-cgi/access/logout", + // Signing out: the device forgets what the app last saw. What + // was done here and not yet sent is kept, and goes when the + // owner signs in again. + onclick: () => navigator.serviceWorker?.controller?.postMessage({ type: "forget" }), + }, + "Sign out", + ), ); return out; } @@ -1736,6 +1924,174 @@ async function viewAway() { ]; } +/** What is kept on this device, in the groups the screen shows it in, + * newest first: `title`, the entries, and what can be done with each. */ +export function keptGroups(entries) { + const of = (state) => entries.filter((e) => e.state === state).sort((a, b) => b.at - a.at); + return [ + { state: "waiting", title: "Waiting to send", can: ["drop"], entries: of("waiting") }, + { state: "stale", title: "Kept back for you to look at", can: ["send", "drop"], entries: of("stale") }, + { state: "failed", title: "Could not be done", can: ["again", "drop"], entries: of("failed") }, + { state: "held", title: "With the platform, waiting for a machine", can: [], entries: of("held") }, + { state: "done", title: "Sent", can: [], entries: of("done") }, + ].filter((g) => g.entries.length > 0); +} + +/** Everything the app's screens read, by the address each asks for it + * under: what "keep a copy of every screen" fetches. What is read only + * for one item when it is opened (a question's background, a pull + * request's checks, a service's log) is not in it. */ +export function everyRead(caps, edge) { + return [ + "doc/core", + "doc/questions", + "doc/ops", + "me", + "roadmaps", + ...(caps || []).map((c) => `roadmap?area=${encodeURIComponent(c.id)}`), + "bugs", + "intake", + ...["blocked", "queued", "claimed", "parked"].map((status) => `queue?status=${status}&q=`), + "releases", + "messages?limit=15", + "push", + "devices", + "signin", + ...(edge ? ["android"] : []), + ]; +} + +/** On this device: what is kept here to send, what became of what was + * sent, and what the device keeps to show with no connection. */ +async function viewDevice() { + const entries = await readKept(); + const n = Outbox ? Outbox.summary(entries) : { waiting: 0 }; + const after = async (work) => { + await work(); + await readKept(); + draw(); + }; + const row = (group) => (e) => + card( + h("h3", {}, e.said), + h( + "p", + { class: group.state === "failed" || group.state === "stale" ? "why" : "meta" }, + [group.state === "done" ? `sent ${ago(new Date(e.endedAt ?? e.at).toISOString())}` : `${ago(new Date(e.at).toISOString())}`, e.note].filter(Boolean).join(" · "), + ), + group.can.length + ? h( + "div", + { class: "row end" }, + group.can.includes("drop") + ? h("button", { class: "small ghost", onclick: () => after(() => outbox.remove(e.id)) }, group.state === "waiting" ? "Do not send" : "Discard") + : null, + group.can.includes("send") + ? h( + "button", + { + class: "small", + // Looked at again, and still wanted: it goes as it is. + onclick: () => after(async () => { + await outbox.put({ ...e, state: "waiting", sure: true, note: "" }); + await flushOutbox(); + }), + }, + "Send it now", + ) + : null, + group.can.includes("again") + ? h( + "button", + { + class: "small", + // Under a new name: the platform answers the old one as it did. + onclick: () => after(async () => { + await outbox.remove(e.id); + await outbox.put({ ...Outbox.make(e.kind, e.args, Date.now(), e.said), sure: true }); + await flushOutbox(); + }), + }, + "Try again", + ) + : null, + ) + : null, + ); + const groups = keptGroups(entries); + const forget = async (e) => { + e.target.disabled = true; + const worker = (await navigator.serviceWorker?.ready.catch(() => null))?.active; + if (!worker) return toast("Nothing is kept: this browser has not set the app up to work offline.", true); + worker.postMessage({ type: "forget" }); + toast("Forgotten. It keeps again from the next thing you look at."); + e.target.disabled = false; + }; + // Before a flight: read every screen once, so the device has a copy + // of each. One at a time, and unhurried: some of it is searched for. + const keepAll = async (e) => { + const button = e.target; + button.disabled = true; + const caps = await api("roadmaps").catch(() => []); + const reads = everyRead(caps, me.edge); + let failed = 0; + for (const [i, path] of reads.entries()) { + button.textContent = `${i + 1} of ${reads.length}…`; + await api(path).catch(() => failed++); + if (offline) break; + await new Promise((resolve) => setTimeout(resolve, path.startsWith("roadmap?") ? 1200 : 150)); + } + await fetch("/console/health", { cache: "no-store" }).catch(() => failed++); + button.textContent = "Keep a copy of every screen now"; + button.disabled = false; + toast( + offline + ? "There is no connection: nothing new could be read." + : failed + ? `Kept what could be read; ${failed} screen${failed === 1 ? "" : "s"} could not.` + : `This device has a copy of every screen, as of now.`, + offline || failed > 0, + ); + }; + return [ + card( + h("h3", {}, signedOut ? "Signed out" : offline ? "No connection" : "Connected"), + h( + "p", + { class: "meta" }, + signedOut + ? "The sign-in has run out. What you see is what this device last saw; what you do is kept here until you sign in again." + : offline + ? "What you see is what this device last saw. What you do is kept here and sent by itself when the connection is back, whether or not the app is open." + : "What you do is sent at once. With no connection it is kept here, and sent by itself when the connection is back.", + ), + !outbox ? h("p", { class: "why" }, "This browser will not let the app keep anything: with no connection, what you do here cannot be kept.") : null, + signedOut + ? h("div", { class: "row end" }, h("button", { onclick: () => location.reload() }, "Sign in again")) + : n.waiting > 0 && !offline + ? h("div", { class: "row end" }, h("button", { onclick: (e) => ((e.target.disabled = true), after(flushOutbox)) }, "Send now")) + : null, + ), + ...groups.flatMap((g) => [h("h2", {}, `${g.title} (${g.entries.length})`), ...g.entries.map(row(g))]), + groups.length === 0 ? empty("Nothing is kept here to send.") : null, + h("h2", {}, "What this device keeps"), + card( + h( + "p", + { class: "meta" }, + "The app's own files and the last answer to everything it showed, so that it opens and reads with no connection; and what you did that has not been sent. A merge, a deploy, a cancel, an unblock or a service action is sent by itself only within ten minutes of when you did it: after that it waits here for you to look again.", + ), + h("p", { class: "meta" }, "What sets the connection up or carries a secret (notifications, phones, sign-in, the Cloudflare switch) is never kept: it needs a connection."), + h( + "div", + { class: "row end" }, + h("button", { class: "ghost", onclick: forget }, "Forget what it last saw"), + offline || signedOut ? null : h("button", { onclick: keepAll }, "Keep a copy of every screen now"), + ), + ), + ]; +} + async function viewSignin() { let s; try { @@ -2035,7 +2391,8 @@ function viewPrs() { class: "small", onclick: async (e) => { const yes = await ask({ title: `Merge #${p.number}?`, text: p.title, okLabel: "Merge" }); - if (yes !== null) act("pr.merge", { pr: p.number }, `#${p.number} merged`, e.target); + // As it stood when this list was read: not what was pushed since. + if (yes !== null) act("pr.merge", { pr: p.number, head: p.head }, `#${p.number} merged`, e.target); }, }, "Merge", @@ -2184,6 +2541,7 @@ const VIEWS = { "more/phone": ["Phones", viewPhone], "more/signin": ["Sign-in", viewSignin], "more/away": ["Cloudflare", viewAway], + "more/device": ["On this device", viewDevice], "more/releases": ["Releases", viewReleases], "more/roadmap": ["Roadmap", viewRoadmap], "more/bugs": ["Bugs", viewBugs], @@ -2243,15 +2601,59 @@ function drawTabs() { ); } +/** What the corner of the header says: live, how old, offline, or signed out. */ +export function freshSaid(state, now = Date.now()) { + const age = state.asOf ? (now - state.asOf) / 1000 : null; + const since = age === null ? "" : ago(new Date(state.asOf).toISOString(), now); + if (state.signedOut) return { text: "signed out", tone: "down" }; + if (state.offline) return { text: since ? `offline · ${since}` : "offline", tone: "stale" }; + if (age === null) return { text: "", tone: "" }; + return age < 45 ? { text: "live", tone: "" } : { text: `as of ${since}`, tone: age > 180 ? "stale" : "" }; +} + function drawFresh() { - const t = asOf.core; - const age = t ? (Date.now() - t) / 1000 : null; - freshEl.className = `fresh${signedOut ? " down" : age !== null && age > 180 ? " stale" : ""}`; - freshEl.textContent = signedOut ? "signed out" : age === null ? "" : age < 45 ? "live" : `as of ${ago(new Date(t).toISOString())}`; + const said = freshSaid({ asOf: asOf.core, offline, signedOut }); + freshEl.className = `fresh${said.tone ? ` ${said.tone}` : ""}`; + freshEl.textContent = said.text; +} + +/** The line under the header: that there is no connection or no + * sign-in, and what is kept on this device to send. Nothing to say, + * nothing shown. `to` is where a tap goes. */ +export function keptSaid(state) { + const n = state.summary || {}; + const things = (count) => `${count} thing${count === 1 ? "" : "s"}`; + const parts = []; + if (state.signedOut) parts.push("Signed out: tap to sign in again"); + else if (state.offline) parts.push("No connection: this is what the device last saw"); + if (n.waiting) parts.push(`${things(n.waiting)} kept to send`); + if (n.stale) parts.push(`${things(n.stale)} kept back for you to look at`); + if (n.failed) parts.push(`${things(n.failed)} could not be done`); + if (parts.length === 0) return null; + const urgent = Boolean(state.signedOut || n.stale || n.failed); + return { text: `${parts.join(" · ")}.`, tone: urgent ? "warn" : "", to: state.signedOut && !n.stale && !n.failed ? "reload" : "more/device" }; +} + +function drawKept() { + if (!keptEl) return; + const said = keptSaid({ offline, signedOut, summary: Outbox ? Outbox.summary(kept) : {} }); + keptEl.hidden = said === null; + if (!said) return; + keptEl.className = `kept${said.tone ? ` ${said.tone}` : ""}`; + keptEl.textContent = said.text; + keptEl.onclick = () => (said.to === "reload" ? location.reload() : go(said.to)); } /** How many quick looks have been taken since the state was last fresh. */ let catchUp = 0; +/** Why the state could not be read, while there is none to show. */ +let loadError = ""; +const couldNotLoad = (why) => + card( + h("h3", {}, "Could not load"), + h("p", { class: "why" }, why), + h("div", { class: "row end" }, h("button", { onclick: () => (signedOut ? location.reload() : refresh(true)) }, signedOut ? "Sign in again" : "Try again")), + ); /** Draw the current section from what is already loaded. Only the latest * call may draw, so a slow section never lands on top of a newer one. */ @@ -2264,7 +2666,8 @@ async function draw() { $("back").hidden = !name.includes("/"); drawTabs(); drawFresh(); - if (!docs.core) return view.replaceChildren(empty("Loading…")); + // Nothing to draw from yet: say so, or say why there will not be. + if (!docs.core) return view.replaceChildren(loadError ? couldNotLoad(loadError) : empty("Loading…")); if (extra && !docs[extra]) loadDoc(extra).then(() => seq === drawSeq && draw()).catch(() => {}); // Moving to another screen: what the last one showed must not sit // under this one's name while this one is fetched. A screen that has @@ -2305,10 +2708,17 @@ async function refresh(force) { let changed = false; try { changed = await loadDoc("core"); + loadError = ""; if (extra) changed = (await loadDoc(extra)) || changed; // An old copy means the laptop has just been told someone is // looking: look again shortly, a few times, instead of waiting out // the full interval. + // What the platform took for a machine: how it came out is on its + // record. And with an answer from the network, what waits is sent. + if (Outbox && outbox && kept.some((e) => e.state === "held")) { + Outbox.settle(outbox, docs.core?.acts).then((done) => done.length && readKept()); + } + if (!offline && kept.some((e) => e.state === "waiting")) flushOutbox(); const old = asOf.core && Date.now() - asOf.core > 60_000; if (!old) catchUp = 0; else if (catchUp < 4) { @@ -2316,8 +2726,11 @@ async function refresh(force) { setTimeout(() => document.visibilityState === "visible" && refresh(false), 4_000); } } catch (error) { - if (!docs.core) view.replaceChildren(card(h("h3", {}, "Could not load"), h("p", { class: "why" }, error.message), h("div", { class: "row end" }, h("button", { onclick: () => location.reload() }, "Reload")))); + // With nothing to show, this is what the screen says until a read + // works (drawing again must not put "Loading" back over it). + if (!docs.core) loadError = error.message; } + drawKept(); // An open dialog or a half-typed answer is not redrawn from under the reader. const busy = $("ask").open || pending.size > 0 || (document.activeElement && ["TEXTAREA", "INPUT", "SELECT"].includes(document.activeElement.tagName)); if (force || (changed && !busy)) draw(); @@ -2353,8 +2766,43 @@ if (typeof document !== "undefined" && view) { me = m; }) .catch(() => {}); - // The worker shows notifications and opens the right screen when one is tapped. - if ("serviceWorker" in navigator) navigator.serviceWorker.register("/console/sw.js", { scope: "/console/" }).catch(() => {}); + // The worker shows notifications, keeps the app and what it last saw + // for when there is no connection, and sends what was kept meanwhile. + if ("serviceWorker" in navigator) { + // The worker and the file it loads are always asked of the network, + // so a fix to either is not held back by a copy the browser kept. + navigator.serviceWorker.register("/console/sw.js", { scope: "/console/", updateViaCache: "none" }).catch(() => {}); + navigator.serviceWorker.addEventListener("message", (event) => { + // The worker sent what was waiting (it was woken for it, and got + // there before this page did): say what became of it, as this + // page would have. + if (event.data?.type !== "outbox") return; + const changed = Array.isArray(event.data.changed) ? event.data.changed : []; + const said = flushSaid(changed); + if (said) toast(said, changed.some((e) => e.state === "failed")); + readKept().then(() => changed.length && refresh(true)); + }); + // The worker has just taken this page over. What the page read + // before then went past it and was not kept: read it again, whole, + // so that the device has a copy from the first visit on. + navigator.serviceWorker.addEventListener("controllerchange", () => { + for (const name of Object.keys(etags)) delete etags[name]; + refresh(true); + for (const name of ["questions", "ops"]) loadDoc(name).catch(() => {}); + }); + } + // What the owner did is kept in the browser's own database; where + // there is none, for as long as the page lives. + if (Outbox) { + try { + outbox = typeof indexedDB === "undefined" ? null : Outbox.idbStore(); + } catch { + outbox = null; + } + readKept().then(flushOutbox); + addEventListener("online", () => refresh(false).then(flushOutbox)); + addEventListener("offline", () => refresh(false)); + } // And a device that has notifications on keeps getting them when the // sender changed or lost track of it. keepSubscribed().catch(() => {}); diff --git a/pm-stack/console/public/index.html b/pm-stack/console/public/index.html index f8bac08f82..0d4320309c 100644 --- a/pm-stack/console/public/index.html +++ b/pm-stack/console/public/index.html @@ -21,6 +21,7 @@

Now

+
@@ -36,6 +37,7 @@

+ diff --git a/pm-stack/console/public/outbox.js b/pm-stack/console/public/outbox.js new file mode 100644 index 0000000000..2f6cca99ce --- /dev/null +++ b/pm-stack/console/public/outbox.js @@ -0,0 +1,341 @@ +// What the owner did, kept on this device until the platform has it. +// +// Every action the app takes is given a name here (a UUID) and written +// down before it is sent. With a connection it is sent at once, as +// before. Without one it waits, and is sent when the connection is +// back: by the page if it is open, by the service worker if it is not. +// The platform does an action once under its name however often it +// arrives, so sending again after an answer that never came is safe. +// +// One file for the page and the service worker alike, so there is one +// rule for what is sent when. It is a plain script, not a module: the +// worker takes it with importScripts, the page with a script tag, and +// both find it as PMOutbox. +((root) => { + /** Actions that may be done late: what the owner says or decides does + * not go stale. (The same list the platform holds for a machine.) */ + const LATE = new Set([ + "ask.send", + "ask.reply", + "ask.close", + "question.answer", + "question.defer", + "questions.accept", + "hands.done", + "need.comment", + "issue.comment", + "issue.rank", + "task.move", + "message.send", + "intake.send", + ]); + /** Actions on something that may have changed by the time they are + * sent: a merge, a deploy, a task's or a unit's state. They are kept + * too, and sent by themselves only while they are fresh; after that + * they wait for the owner to look again and say so. */ + const TIMELY = new Set(["pr.merge", "deploy.start", "task.cancel", "task.unblock", "unit.act"]); + /** How long a timely action stays fresh: a tunnel, a lift, a bad patch. */ + const TIMELY_MS = 10 * 60_000; + /** Finished entries are shown for a day, and no more than this many. */ + const DONE_FOR_MS = 24 * 60 * 60_000; + const DONE_KEPT = 30; + /** The platform keeps what it holds for a machine for a day, and its + * record of what was done is short. An entry it took that long ago + * has its outcome there, not here. */ + const HELD_FOR_MS = 26 * 60 * 60_000; + + /** How an action is treated when it cannot be sent: "late" (kept and + * sent whenever), "timely" (kept, sent by itself only while fresh), + * or "now" (needs a connection: it sets the connection up, or carries + * a secret that is not written down). What is not known is "now". */ + const rule = (kind) => (LATE.has(kind) ? "late" : TIMELY.has(kind) ? "timely" : "now"); + + const short = (text, n = 60) => { + const t = String(text ?? "") + .replace(/\s+/g, " ") + .trim(); + return t.length > n ? `${t.slice(0, n - 1)}…` : t; + }; + + /** One line saying what an action is, for the list of what is kept. */ + function sayOf(kind, args = {}) { + const a = args ?? {}; + const quoted = (text) => (short(text) ? `: “${short(text)}”` : ""); + switch (kind) { + case "ask.send": + return `Prompt${quoted(a.text)}`; + case "ask.reply": + return `Reply on #${a.issue}${quoted(a.text)}`; + case "ask.close": + return `Mark prompt #${a.issue} done`; + case "issue.comment": + return `Comment on #${a.issue}${quoted(a.text)}`; + case "issue.rank": + return `Rank #${a.issue} ${a.rank}`; + case "need.comment": + return `Reply on ${a.ref}${quoted(a.text)}`; + case "hands.done": + return `Mark ${a.ref} done`; + case "task.move": + return `Move task ${a.task} ${a.to === "first" ? "to the top" : a.to}`; + case "task.cancel": + return `Cancel task ${a.task}`; + case "task.unblock": + return `Unblock task ${a.task}`; + case "pr.merge": + return `Merge #${a.pr}`; + case "deploy.start": + return a.what === "app" ? "Start the app's build" : "Start the site's deploy"; + case "intake.send": { + const what = a.session ? "Session" : a.kind === "bug" ? "Bug" : a.kind === "change" ? "Change" : "Note"; + return `${what}${quoted(a.text)}`; + } + case "question.answer": + return `Answer${quoted(Array.isArray(a.answer) ? a.answer.join(", ") : a.answer)}`; + case "question.defer": + return "Put a question off"; + case "questions.accept": + return "Accept the recommended answers"; + case "message.send": + return `Message to ${Array.isArray(a.to) ? a.to.join(", ") : a.to}${quoted(a.text)}`; + case "unit.act": + return `${a.action} ${a.unit}`; + default: + return String(kind); + } + } + + const uuid = () => root.crypto.randomUUID(); + + /** A new entry: an action, named, as it stood when the owner did it. */ + function make(kind, args, now, said, id = uuid()) { + return { id, kind, args: args ?? {}, said: said || sayOf(kind, args), at: now, state: "waiting", note: "", tries: 0 }; + } + + /** What became of one try at sending. `answer` is what came back: + * `{ network: true }` when nothing did, else the status, whether the + * body was JSON, and the body. Returns the entry's new state and what + * to say of it; `stop` means the rest will fare no better just now. */ + function classify(answer) { + if (answer.network) return { state: "waiting", note: "", stop: true }; + const { status, body } = answer; + // Not the platform's own answer: a sign-in page, or something in + // between. The action was not taken; it waits for a sign-in. + if (answer.signin || body === null || typeof body !== "object") { + return { state: "waiting", note: "Sign in again to send this.", stop: true, signin: true }; + } + if (status === 200 && body.ok === true) { + return body.held === true + ? { state: "held", note: "Kept for the laptop, which will do it when it is back.", result: null } + : { state: "done", note: "", result: body.result ?? null }; + } + const why = typeof body.error === "string" && body.error !== "" ? body.error : `http ${status}`; + // Being done right now under this name: ask again shortly. + if (status === 409 && body.running === true) return { state: "waiting", note: "Being done now." }; + // Nothing could take it just now (no machine in reach, too much + // waiting). Under its name it is safe to offer again, and it is: + // said in this device's own words, because the platform's are + // written for a caller that cannot ("check before trying again"). + if (status === 503) return { state: "waiting", note: "Nothing could take it just now. It is offered again." }; + return { state: "failed", note: why }; + } + + /** Whether an entry is sent by itself now. A timely one that has gone + * stale is not: it is marked, and waits for the owner. */ + function due(entry, now) { + if (entry.state !== "waiting") return false; + if (rule(entry.kind) !== "timely" || entry.sure === true) return true; + return now - entry.at <= TIMELY_MS; + } + + /** Counts for the line that says what is kept. */ + function summary(entries) { + const count = (state) => entries.filter((e) => e.state === state).length; + return { + waiting: count("waiting"), + stale: count("stale"), + held: count("held"), + failed: count("failed"), + done: count("done"), + // What still needs something: a connection, a look, or a decision. + open: count("waiting") + count("stale") + count("failed"), + }; + } + + /** The entries no longer worth keeping: done ones older than a day, + * the oldest done ones past a count, and ones the platform took for a + * machine so long ago that their outcome is only on its own record. + * Nothing the platform has not taken is ever dropped by this. */ + function expired(entries, now) { + const done = entries.filter((e) => e.state === "done").sort((a, b) => (b.endedAt ?? b.at) - (a.endedAt ?? a.at)); + return [ + ...done.filter((e, i) => i >= DONE_KEPT || now - (e.endedAt ?? e.at) > DONE_FOR_MS), + ...entries.filter((e) => e.state === "held" && now - (e.endedAt ?? e.at) > HELD_FOR_MS), + ].map((e) => e.id); + } + + /** Send what is due, oldest first. `store` keeps the entries (all, + * put, remove); `send(entry)` makes one try and says what came back. + * Returns what changed. One flush at a time per store: a second call + * while one runs joins it. */ + const running = new WeakMap(); + function flush(store, send, now = () => Date.now()) { + const already = running.get(store); + if (already) return already; + const work = (async () => { + const changed = []; + let signin = false; + let offline = false; + const entries = (await store.all()).sort((a, b) => a.at - b.at); + for (const entry of entries) { + if (entry.state !== "waiting") continue; + if (!due(entry, now())) { + // Too old to send unasked: kept, and said to be. + const stale = { ...entry, state: "stale", note: "Not sent: it was a while ago, and this may have changed." }; + await store.put(stale); + changed.push(stale); + continue; + } + let answer; + try { + answer = await send(entry); + } catch { + answer = { network: true }; + } + const { state, note, result, stop, signin: needs } = classify(answer); + const next = { + ...entry, + state, + note, + tries: entry.tries + 1, + triedAt: now(), + ...(state === "done" || state === "failed" || state === "held" ? { endedAt: now() } : {}), + ...(result !== undefined ? { result } : {}), + }; + // A try that changed nothing worth writing is not written. + if (next.state !== entry.state || next.note !== entry.note) { + await store.put(next); + changed.push(next); + } + if (needs) signin = true; + if (answer.network) offline = true; + if (stop) break; + } + for (const id of expired(await store.all(), now())) await store.remove(id); + return { changed, signin, offline }; + })(); + running.set(store, work); + const clear = () => running.delete(store); + work.then(clear, clear); + return work; + } + + /** Entries held for a machine learn how they came out from the + * platform's own record of what was done, which carries their names. */ + async function settle(store, acts, now = () => Date.now()) { + const byId = new Map((Array.isArray(acts) ? acts : []).map((a) => [a.id, a])); + const changed = []; + for (const entry of await store.all()) { + if (entry.state !== "held") continue; + const act = byId.get(entry.id); + if (!act || act.status === "running") continue; + const next = + act.status === "done" + ? { ...entry, state: "done", note: "", endedAt: now() } + : { ...entry, state: "failed", note: act.note || "It could not be done.", endedAt: now() }; + await store.put(next); + changed.push(next); + } + return changed; + } + + /** One try at sending an entry to the platform. */ + async function httpSend(entry, fetchImpl = root.fetch.bind(root)) { + let res; + try { + res = await fetchImpl("/console/api/act", { + method: "POST", + headers: { "Content-Type": "application/json", "X-PM-Console": "1" }, + body: JSON.stringify({ kind: entry.kind, args: entry.args, id: entry.id }), + // A sign-in that has run out answers with a way to another + // site. It is not followed: it is how this is told from no + // connection at all. + redirect: "manual", + }); + } catch { + return { network: true }; + } + if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) return { signin: true, status: 0, body: null }; + let body = null; + try { + body = await res.json(); + } catch { + body = null; + } + // No sign-in, whoever says so; or refused by something in between + // that is not the platform (it answers in its own words). + if (res.status === 401 || (res.status === 403 && !(body && typeof body.error === "string"))) { + return { signin: true, status: res.status, body: null }; + } + return { status: res.status, body }; + } + + /** The entries, kept in the browser's own database so that the page + * and the service worker see the same ones. */ + function idbStore(name = "pm-console") { + const open = () => + new Promise((resolve, reject) => { + const req = root.indexedDB.open(name, 1); + req.onupgradeneeded = () => req.result.createObjectStore("outbox", { keyPath: "id" }); + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + const run = async (mode, work) => { + const db = await open(); + try { + return await new Promise((resolve, reject) => { + const tx = db.transaction("outbox", mode); + const req = work(tx.objectStore("outbox")); + tx.oncomplete = () => resolve(req?.result); + tx.onerror = () => reject(tx.error); + tx.onabort = () => reject(tx.error); + }); + } finally { + db.close(); + } + }; + return { + all: async () => (await run("readonly", (s) => s.getAll())) ?? [], + put: (entry) => run("readwrite", (s) => s.put(entry)), + remove: (id) => run("readwrite", (s) => s.delete(id)), + }; + } + + /** A store that lives only as long as the page: for a browser that + * will not give this page a database. Nothing is kept across a + * reload, and the app says so. */ + function memoryStore() { + const entries = new Map(); + return { + all: async () => [...entries.values()].map((e) => ({ ...e })), + put: async (entry) => void entries.set(entry.id, { ...entry }), + remove: async (id) => void entries.delete(id), + }; + } + + root.PMOutbox = { + TIMELY_MS, + rule, + sayOf, + make, + classify, + due, + summary, + expired, + flush, + settle, + httpSend, + idbStore, + memoryStore, + }; +})(typeof self !== "undefined" ? self : globalThis); diff --git a/pm-stack/console/public/sw.js b/pm-stack/console/public/sw.js index cb7f646694..c16d1a4ec7 100644 --- a/pm-stack/console/public/sw.js +++ b/pm-stack/console/public/sw.js @@ -1,7 +1,239 @@ -// The app's service worker: it shows a notification when one is pushed, -// and opens the right screen when it is tapped. -self.addEventListener("install", () => self.skipWaiting()); -self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim())); +// The app's service worker. Three jobs: +// +// 1. It shows a notification when one is pushed, and opens the right +// screen when it is tapped. +// 2. It keeps a copy of the app's own files and of the last answer to +// everything the app reads, so the app opens and shows what it +// last saw with no connection. The network is always asked first: +// a copy is only shown when the network gives no answer. +// 3. It sends what the owner did while offline (outbox.js) when the +// connection is back, if the app is not open to do it itself. +// +// Nothing here is written with a secret in it: what is kept is what the +// app showed, and what the owner did. +self.importScripts("/console/outbox.js"); + +const KEPT = "pm-console-v1"; +/** The app's own files, fetched when the worker is installed so that + * the first visit is already enough to open it offline. */ +const FILES = ["/console/", "/console/app.js", "/console/outbox.js", "/console/app.css", "/console/icon.svg"]; +const EXTRAS = ["/manifest.webmanifest", "/icons/icon-192.png", "/icons/icon-512.png"]; +/** How long the network is waited for before a copy is shown instead. + * The network's answer still replaces the copy when it comes. */ +const PAGE_WAIT_MS = 4_000; +const READ_WAIT_MS = 8_000; + +self.addEventListener("install", (event) => { + event.waitUntil( + (async () => { + const cache = await self.caches.open(KEPT); + // Each by itself: one that cannot be fetched (not signed in, say) + // does not stop the others, or the worker. + await Promise.all([...FILES, ...EXTRAS].map((path) => keep(cache, path).catch(() => {}))); + await self.skipWaiting(); + })(), + ); +}); + +self.addEventListener("activate", (event) => { + event.waitUntil( + (async () => { + for (const name of await self.caches.keys()) { + if (name.startsWith("pm-console-") && name !== KEPT) await self.caches.delete(name); + } + await self.clients.claim(); + })(), + ); +}); + +/** Fetch one of the app's files and keep it. */ +async function keep(cache, path) { + const res = await self.fetch(path, { cache: "no-store", redirect: "manual" }); + if (res.ok) await cache.put(path, res); +} + +/** What a request is, to this worker: the app's page, one of its + * files, something it reads, or none of its business. */ +function kindOf(request, url) { + if (request.method !== "GET" || url.origin !== self.location.origin) return null; + // Asked on purpose past this worker: is there a sign-in, is there a network. + if (request.headers.get("x-pm-probe")) return null; + const path = url.pathname; + if (path.startsWith("/console/api/") || path === "/console/health") return "read"; + if (EXTRAS.includes(path) || path.startsWith("/icons/")) return "file"; + if (!path.startsWith("/console")) return null; + // The app is one page, at one address (its screens are after the #). + if (path === "/console/" || path === "/console") return "page"; + return FILES.includes(path) ? "file" : null; +} + +/** The address a copy is kept under: what was asked, without the mark + * that only says "ask the source again" (the answer is the same thing). */ +function keyOf(url, kind) { + if (kind === "page") return "/console/"; + const params = new URLSearchParams(url.search); + params.delete("fresh"); + const query = params.toString(); + return url.pathname + (query ? `?${query}` : ""); +} + +/** Where it is noted that a copy was said to be current still. Not an + * address the app ever asks for. */ +const seenKey = (key) => `/console/__seen__/${encodeURIComponent(key)}`; + +/** A copy of an answer, marked with when it was kept. */ +async function stamped(res, extra) { + const headers = new Headers(res.headers); + for (const [name, value] of Object.entries(extra)) headers.set(name, value); + return new Response(await res.blob(), { status: res.status, statusText: res.statusText, headers }); +} + +const after = (ms) => new Promise((resolve) => self.setTimeout(() => resolve(null), ms)); + +/** The network first; the copy when the network gives no answer, or is + * too slow to wait for. An answer that is not a plain success (a + * refusal, a way to the sign-in, an error) is passed on as it is and + * never replaced by a copy: the app has to see it. Gives what to show, + * and the keeping of the network's answer, which may come after. */ +function answer(request, kind) { + const key = keyOf(new URL(request.url), kind); + const opened = self.caches.open(KEPT); + const fromNetwork = (async () => { + const cache = await opened; + const res = await self.fetch(request); + if (res.status === 200) { + const copy = kind === "read" ? await stamped(res.clone(), { "x-pm-kept-at": String(Date.now()) }) : res.clone(); + await cache.put(key, copy); + } else if (res.status === 304 && kind === "read") { + // The app's own copy is current, and so is the one kept here: + // nothing new to keep but when that was, which is small. + const seen = { "x-pm-kept-at": String(Date.now()), "x-as-of": res.headers.get("x-as-of") ?? "" }; + await cache.put(seenKey(key), new Response("", { headers: seen })); + } + return res; + })(); + const kept = async () => { + const cache = await opened; + const copy = await cache.match(key); + if (!copy) return null; + if (kind !== "read") return copy; + // As current as it was last said to be, which may be later than + // when it was last sent whole. + const marks = { "x-pm-offline": "1" }; + const seen = await cache.match(seenKey(key)); + if (seen && Number(seen.headers.get("x-pm-kept-at")) > Number(copy.headers.get("x-pm-kept-at"))) { + marks["x-pm-kept-at"] = seen.headers.get("x-pm-kept-at"); + if (seen.headers.get("x-as-of")) marks["x-as-of"] = seen.headers.get("x-as-of"); + } + return stamped(copy, marks); + }; + const shown = (async () => { + const first = await Promise.race([ + fromNetwork.then( + (res) => ({ res }), + () => ({ failed: true }), + ), + after(kind === "read" ? READ_WAIT_MS : PAGE_WAIT_MS), + ]); + if (first?.res) return first.res; + const copy = await kept(); + if (copy) return copy; + // No copy to show: the network's answer, however long it takes, or its failure. + return fromNetwork; + })(); + return { + shown, + // Whatever becomes of the race above, the network's answer is kept when it comes. + keeping: fromNetwork.then( + () => {}, + () => {}, + ), + }; +} + +self.addEventListener("fetch", (event) => { + const kind = kindOf(event.request, new URL(event.request.url)); + if (!kind) return; + const { shown, keeping } = answer(event.request, kind); + event.respondWith(shown); + event.waitUntil(keeping); +}); + +// ---- what the owner did while offline ------------------------------------ + +/** Send what is waiting. Told to every open page, so each shows it. */ +async function send() { + const store = self.PMOutbox.idbStore(); + const flush = () => + self.PMOutbox.flush(store, (entry) => self.PMOutbox.httpSend(entry, (url, init) => self.fetch(url, init))); + // One sender at a time, the app's page included: if it is sending + // now, this has nothing to add. + const locks = self.navigator?.locks; + const out = locks?.request ? await locks.request("pm-outbox", { ifAvailable: true }, (lock) => (lock ? flush() : null)) : await flush(); + if (!out) return; + const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true }); + // What became of each, by state only: enough for a page to say it. + const became = out.changed.map((e) => ({ state: e.state })); + for (const client of windows) client.postMessage({ type: "outbox", changed: became }); + // With no page open to show it, say what became of it. + const open = windows.some((client) => new URL(client.url).pathname.startsWith("/console")); + const done = out.changed.filter((e) => e.state === "done" || e.state === "held").length; + const failed = out.changed.filter((e) => e.state === "failed").length; + const stale = out.changed.filter((e) => e.state === "stale").length; + if (!open && done + failed + stale > 0 && self.Notification?.permission === "granted") { + const parts = [ + done ? `${done} sent` : "", + failed ? `${failed} could not be done` : "", + stale ? `${stale} kept back for you to look at` : "", + ].filter(Boolean); + await self.registration.showNotification("What you did offline", { + body: `${parts.join(", ")}.`, + tag: "outbox", + icon: "/icons/icon-192.png", + badge: "/icons/icon-192.png", + data: { url: "/console/#more/device" }, + }); + } + // The sign-in has run out: nothing was sent, and nothing will be + // until the owner signs in. With no page open, that has to be said. + if (out.signin && !open && self.Notification?.permission === "granted") { + const waiting = (await store.all()).filter((e) => e.state === "waiting").length; + await self.registration.showNotification("Sign in to send what you did offline", { + body: `${waiting} thing${waiting === 1 ? " is" : "s are"} kept on this device until you do.`, + tag: "outbox", + icon: "/icons/icon-192.png", + badge: "/icons/icon-192.png", + data: { url: "/console/#more/device" }, + }); + } + // Still no connection: say so, and the browser will call again. + if (out.offline) throw new Error("still offline"); +} + +self.addEventListener("sync", (event) => { + if (event.tag === "pm-outbox") event.waitUntil(send()); +}); + +self.addEventListener("message", (event) => { + if (event.data?.type === "forget") { + // The owner asked this device to forget what it keeps of the app's + // answers. What they did and has not been sent is not touched. + event.waitUntil( + (async () => { + const cache = await self.caches.open(KEPT); + for (const request of await cache.keys()) { + const path = new URL(request.url).pathname; + if (path.startsWith("/console/api/") || path.startsWith("/console/__seen__/") || path === "/console/health") { + await cache.delete(request); + } + } + event.source?.postMessage({ type: "forgotten" }); + })(), + ); + } +}); + +// ---- notifications ------------------------------------------------------- self.addEventListener("push", (event) => { let data = {}; diff --git a/pm-stack/console/scripts/demo-state.ts b/pm-stack/console/scripts/demo-state.ts index f509edfd04..781d22a30a 100644 --- a/pm-stack/console/scripts/demo-state.ts +++ b/pm-stack/console/scripts/demo-state.ts @@ -7,10 +7,12 @@ import { readConfig } from "../src/config.ts"; import { Devices, Limiter } from "../src/devices.ts"; import { Docs } from "../src/docs.ts"; import { fileStore } from "../src/file-store.ts"; +import { Named } from "../src/named.ts"; import { type Fetch, Ops, type Run } from "../src/ops.ts"; import { Plan } from "../src/plan.ts"; import { Push } from "../src/push.ts"; import type { Deps } from "../src/server.ts"; +import { memoryStore } from "../src/store.ts"; import { Work } from "../src/work.ts"; const iso = (minutesAgo: number) => new Date(Date.now() - minutesAgo * 60_000).toISOString().slice(0, 19); @@ -257,6 +259,7 @@ const state = { created: iso(60 * 20), author: "dezren39", branch: "task/suite-registry", + head: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", }, { number: 12241, @@ -266,6 +269,7 @@ const state = { created: iso(60 * 19), author: "dezren39", branch: "task/f12-11-frames", + head: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", }, { number: 12390, @@ -275,6 +279,7 @@ const state = { created: iso(60 * 3), author: "dezren39", branch: "wip/talos", + head: "cccccccccccccccccccccccccccccccccccccccc", }, ], priorities: { @@ -660,6 +665,9 @@ export const demoDeps: Deps = { status: 201, })), actions: table, + // What was done under each name, as the real host keeps it: an action + // a device sends twice is done once here too. + named: new Named(memoryStore()), identify: async () => ({ via: "demo", email: "you@example.com" }), audit: async () => {}, }; diff --git a/pm-stack/console/scripts/edge-demo.ts b/pm-stack/console/scripts/edge-demo.ts index ea2d4c5937..f7867965b6 100644 --- a/pm-stack/console/scripts/edge-demo.ts +++ b/pm-stack/console/scripts/edge-demo.ts @@ -14,6 +14,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { Edge } from "../edge/src/edge.ts"; import { type Io, route } from "../edge/src/entry.ts"; +import type { Named } from "../src/named.ts"; import { heldRunner, handle, marked } from "../src/server.ts"; import { memoryStore } from "../src/store.ts"; import { EdgeLink } from "../src/sync.ts"; @@ -93,6 +94,8 @@ const link = new EdgeLink({ url: `http://${HOSTNAME}:${port}`, keys: memoryStore(), done: memoryStore(), + // One record with the host's own handler, as on the real host. + named: demoDeps.named as Named, docs: demoDocs, phones: demoDeps.phones!.devices, config: async () => ({ diff --git a/pm-stack/console/scripts/edge-smoke.ts b/pm-stack/console/scripts/edge-smoke.ts index 0c04036cbd..a2ddcdc938 100644 --- a/pm-stack/console/scripts/edge-smoke.ts +++ b/pm-stack/console/scripts/edge-smoke.ts @@ -119,7 +119,7 @@ const server = Bun.serve({ html_url: "https://github.com/developing-today/code/pull/7", created_at: "2026-11-23T08:00:00Z", user: { login: "smoke" }, - head: { ref: "smoke" }, + head: { ref: "smoke", sha: "0123456789abcdef0123456789abcdef01234567" }, }, ]); } diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts index dbcc27e54b..ce1a929f5f 100644 --- a/pm-stack/console/src/actions.ts +++ b/pm-stack/console/src/actions.ts @@ -181,7 +181,7 @@ export function actions( audit: ids("issue", "rank"), }, "issue.comment": { run: (a) => ops.comment(a.issue, a.text), touch: [], audit: ids("issue") }, - "pr.merge": { run: (a) => ops.mergePr(a.pr), touch: ["prs"], audit: ids("pr") }, + "pr.merge": { run: (a) => ops.mergePr(a.pr, a.head), touch: ["prs"], audit: ids("pr") }, // Start the site's deploy or the app's build again. Never held to // be done late: a deploy that starts hours after it was asked for // is a surprise. diff --git a/pm-stack/console/src/named.ts b/pm-stack/console/src/named.ts new file mode 100644 index 0000000000..aa0afe7a86 --- /dev/null +++ b/pm-stack/console/src/named.ts @@ -0,0 +1,88 @@ +// What became of each action that was sent under a name. +// +// A device that is offline keeps what the owner did and sends it when +// it is connected again; the edge relays an action to this host and, +// when no answer comes back, holds it and offers it again. Either way +// the same action can arrive twice. Each comes under a name (a UUID +// given by whoever first sent it), and this is where it is written +// down that a name was started and how it ended, so that the second +// arrival is answered from the record and not done again. +import type { Store } from "./store.ts"; + +/** How an action sent under a name came out: what it answered with + * when it worked (if that is small enough to keep), or why it did not + * and the status that went with it. */ +export interface Outcome { + ok: boolean; + error?: string; + status?: number; + result?: unknown; +} +type Fate = "started" | Outcome; + +/** How many names are remembered. A name older than that many actions + * is taken for new again. */ +const KEPT = 300; + +export class Named { + private fates: Map | null = null; + /** Names being done right now, in this process. */ + private running = new Set(); + + constructor(private store: Store) {} + + private async all(): Promise> { + if (this.fates) return this.fates; + try { + this.fates = new Map(Object.entries(JSON.parse((await this.store.read()) ?? "{}") as Record)); + } catch { + this.fates = new Map(); + } + return this.fates; + } + + /** Write down what is known of a name. */ + async record(id: string, fate: Fate): Promise { + const fates = await this.all(); + fates.delete(id); + fates.set(id, fate); + while (fates.size > KEPT) fates.delete(fates.keys().next().value as string); + await this.store.write(JSON.stringify(Object.fromEntries(fates))); + } + + /** What is written down for a name, if anything. */ + async get(id: string): Promise { + return (await this.all()).get(id); + } + + isRunning(id: string): boolean { + return this.running.has(id); + } + + /** An action is about to be done under this name. Written down + * first, so that if its answer is lost and it is offered again, it is + * not done twice. */ + async begin(id: string): Promise { + this.running.add(id); + await this.record(id, "started"); + } + + /** How it came out. */ + async end(id: string, fate: Outcome): Promise { + try { + await this.record(id, fate); + } finally { + this.running.delete(id); + } + } + + /** What is known of an action sent under this name: nothing; that it + * is being done now; how it came out; or ("lost") that it was started + * and this process stopped before it was known how it ended. */ + async seen(id: string): Promise<{ state: "running" | "lost" } | { state: "done"; fate: Outcome } | null> { + if (this.running.has(id)) return { state: "running" }; + const fate = await this.get(id); + if (fate === undefined) return null; + return fate === "started" ? { state: "lost" } : { state: "done", fate }; + } +} diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts index e5c2a797d6..6ae8775b86 100644 --- a/pm-stack/console/src/ops.ts +++ b/pm-stack/console/src/ops.ts @@ -647,7 +647,7 @@ export class Ops { html_url: string; created_at: string; user: { login: string }; - head: { ref: string }; + head: { ref: string; sha?: string }; }[]; return list.map((p) => ({ number: p.number, @@ -657,6 +657,9 @@ export class Ops { created: p.created_at.slice(0, 16), author: p.user.login, branch: p.head.ref, + // The commit it stood at when this was read: a merge asked for + // from this list is a merge of this, and of nothing pushed since. + ...(typeof p.head.sha === "string" ? { head: p.head.sha } : {}), })); } @@ -681,14 +684,22 @@ export class Ops { }; } - async mergePr(number: unknown) { + /** Merge a pull request. With `head`, the commit the owner was shown, + * GitHub merges only if that is still where it stands: a merge asked + * for a while ago (kept on a device that was offline) must not take + * in what was pushed since. */ + async mergePr(number: unknown, head?: unknown) { const n = id(number, "pull request"); + if (head !== undefined && head !== null && !(typeof head === "string" && /^[0-9a-f]{40}$/.test(head))) { + throw new OpError(400, "head: a commit's full name"); + } const done = (await this.gh([ "-X", "PUT", `repos/${this.cfg.repo}/pulls/${n}/merge`, "-f", "merge_method=merge", + ...(typeof head === "string" ? ["-f", `sha=${head}`] : []), ])) as { merged: boolean; sha: string }; return { number: n, merged: done.merged, sha: done.sha }; } diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 1efd994ab9..8257786af6 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -39,12 +39,14 @@ import { OpError, Ops } from "./ops.ts"; import { Plan } from "./plan.ts"; import { platformRead } from "./reads.ts"; import { contact, Push } from "./push.ts"; +import { Named } from "./named.ts"; import { EdgeLink } from "./sync.ts"; import { Work } from "./work.ts"; const PUBLIC_DIR = join(import.meta.dir, "..", "public"); const STATIC = new Map([ ["app.js", "text/javascript; charset=utf-8"], + ["outbox.js", "text/javascript; charset=utf-8"], ["app.css", "text/css; charset=utf-8"], ["icon.svg", "image/svg+xml"], ["sw.js", "text/javascript; charset=utf-8"], @@ -52,6 +54,17 @@ const STATIC = new Map([ const APK_NAME = "pm-console.apk"; const ACT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +/** An action's answer is kept with its name when it is no longer than + * this, so that the same name offered again is answered the same. */ +const RESULT_KEPT_CHARS = 2000; +/** The answer to keep, if it is small enough to. */ +const keptSmall = (result: unknown): { result?: unknown } => { + try { + return result !== undefined && JSON.stringify(result).length <= RESULT_KEPT_CHARS ? { result } : {}; + } catch { + return {}; + } +}; /** The dashboard's files that are public, matched against the parsed * path in full. They say nothing about the fleet. */ const PUBLIC_DASHBOARD = /^\/icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png$/; @@ -127,7 +140,11 @@ export interface Deps { * exist only when their limits do. */ phones?: Phones; /** This host's link to the edge, when the app is served from one. */ - link?: Pick & Partial>; + link?: Pick & Partial>; + /** What became of each action sent under a name, so that one is done + * once however often it arrives. The link keeps one; a host with no + * edge in front of it keeps its own. */ + named?: Pick; } /** Text that shrinks well. The dashboard's fragments run to a megabyte @@ -371,8 +388,16 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul Object.hasOwn(table, kind) && args !== null && typeof args === "object" ? table[kind].audit(args as Record) : {}; + // Sent under a name, by the edge that relayed it or by the device + // itself: the name is written down before the action starts and + // its outcome after. An action is done once under a name, however + // often it arrives: if the answer was lost and it is offered + // again, it is answered from what was written down. + const name = req.headers.get("x-pm-act") ?? (typeof body.id === "string" ? body.id : ""); const entry = { - id: crypto.randomUUID(), + // On the record of what was done under the name it was sent + // with, so the device that sent it can find how it came out. + id: ACT_ID.test(name) ? name : crypto.randomUUID(), kind, at: new Date().toISOString(), by: who.email ?? who.certName ?? who.sub ?? who.via, @@ -388,11 +413,26 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul acts: docs.recentActs(), }) : undefined; - // Relayed by the edge under a name: the name is written down before - // the action starts and its outcome after, so that if this answer - // is lost and the edge offers the action again, it is not repeated. - const name = req.headers.get("x-pm-act") ?? ""; - const link = ACT_ID.test(name) && deps.link?.begin && deps.link.end ? deps.link : null; + const record = deps.named ?? deps.link; + const link = ACT_ID.test(name) && record?.begin && record.end ? record : null; + const before = (await link?.seen?.(name)) ?? null; + if (before?.state === "running") return json({ error: "This is still being done.", running: true }, 409); + if (before?.state === "lost") { + // Started, and this host stopped before it ended. Whether it + // happened is not known, and doing it again could do it twice. + const fate = { + ok: false, + status: 502, + error: "the host restarted while doing this; check whether it happened", + }; + await link?.end?.(name, fate); + return json({ error: fate.error, again: true }, 502); + } + if (before?.state === "done") { + return before.fate.ok + ? json({ ok: true, result: before.fate.result ?? null, again: true, ...forEdge?.() }) + : json({ error: before.fate.error ?? "it could not be done", again: true }, before.fate.status ?? 502); + } return await act( kind || "unknown", kept, @@ -402,11 +442,15 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul try { const result = await perform(table, docs, kind, args); docs.logAct({ ...entry, status: "done" }); - await link?.end?.(name, { ok: true }); + await link?.end?.(name, { ok: true, ...keptSmall(result) }); return result; } catch (error) { docs.logAct({ ...entry, status: "failed", note: (error as Error).message.slice(0, 200) }); - await link?.end?.(name, { ok: false, error: (error as Error).message.slice(0, 300) }); + await link?.end?.(name, { + ok: false, + error: (error as Error).message.slice(0, 300), + status: error instanceof OpError ? error.status : 502, + }); throw error; } }, @@ -622,6 +666,11 @@ if (import.meta.main) { identify: (req, peer) => identify(req, cfg, { peer }), audit: (entry) => appendFile(cfg.auditFile, `${JSON.stringify(entry)}\n`, { mode: 0o600 }), }; + // What became of each action sent under a name. One record, whether + // the action came straight here, was relayed by the edge, or was held + // by it and offered late: a name is done once. + const named = new Named(fileStore(cfg.edgeDoneFile)); + deps.named = named; // Behind an edge: report to it, and run what it held for this host. const link = cfg.edgeUrl ? new EdgeLink({ @@ -630,6 +679,7 @@ if (import.meta.main) { apk: androidBuild(cfg.androidApk), keys: fileStore(cfg.edgeKeyFile), done: fileStore(cfg.edgeDoneFile), + named, docs, phones: devices, config: async () => ({ diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index 635b1ec04c..3f9e8357cd 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -27,6 +27,7 @@ import { type SyncResponse, sign, } from "./edge-proto.ts"; +import { Named, type Outcome } from "./named.ts"; import type { Store } from "./store.ts"; /** Sections kept fresh for notifications and a phone's widget when @@ -39,9 +40,6 @@ const SYNC_TIMEOUT_MS = 20_000; /** After a report that carried the Android build did not get through, * the build is left out of the reports that follow for this long. */ const APK_AGAIN_MS = 10 * 60_000; -const DONE_KEPT = 300; - -type Fate = "started" | { ok: boolean; error?: string }; export interface LinkOptions { /** The public address the edge answers on, e.g. https://pm.example. */ @@ -50,6 +48,10 @@ export interface LinkOptions { keys: Store; /** What became of each held action, so none is run twice. */ done: Store; + /** The same record, when something else keeps it too (the console's + * own handler, for actions sent straight to this host): one record, + * so a name means the same to both. Made over `done` if not given. */ + named?: Named; docs: Docs; phones: { links(): Promise; mergeLinks(value: unknown): Promise }; config: () => Promise; @@ -67,7 +69,6 @@ export interface LinkOptions { export class EdgeLink { private pair: { publicJwk: PublicKey; privateJwk: JsonWebKey; kid: string } | null = null; - private fates: Map | null = null; /** What the edge is known to have, by fingerprint. */ private sent = new Map(); private want = new Set(); @@ -82,8 +83,9 @@ export class EdgeLink { * once: the sections, when the build went alone, or everything but * the build, when a report carrying it did not get through. */ private more = false; - /** Actions being done right now, by the name the edge gave them. */ - private running = new Set(); + /** What became of each action done under a name: the edge's held + * ones and the ones relayed or sent straight here alike. */ + readonly named: Named; private now: () => number; private fetchImpl: typeof fetch; private log: (line: string) => void; @@ -94,6 +96,7 @@ export class EdgeLink { this.now = o.now ?? Date.now; this.fetchImpl = plain(o.fetchImpl ?? fetch); this.log = o.log ?? ((line) => console.error(`pm-console: edge: ${line}`)); + this.named = o.named ?? new Named(o.done); } private async keys() { @@ -121,52 +124,34 @@ export class EdgeLink { return (await this.keys()).publicJwk; } - private async fate(): Promise> { - if (this.fates) return this.fates; - try { - this.fates = new Map(Object.entries(JSON.parse((await this.o.done.read()) ?? "{}") as Record)); - } catch { - this.fates = new Map(); - } - return this.fates; - } - - private async record(id: string, fate: Fate): Promise { - const fates = await this.fate(); - fates.delete(id); - fates.set(id, fate); - while (fates.size > DONE_KEPT) fates.delete(fates.keys().next().value as string); - await this.o.done.write(JSON.stringify(Object.fromEntries(fates))); - } - /** The edge relayed an action under this name and it is about to be * done. Written down first, so that if the answer never reaches the * edge and the edge offers the action again, it is not done twice. */ - async begin(id: string): Promise { - this.running.add(id); - await this.record(id, "started"); + begin(id: string): Promise { + return this.named.begin(id); } /** How a relayed action came out. */ - async end(id: string, fate: { ok: boolean; error?: string }): Promise { - try { - await this.record(id, fate); - } finally { - this.running.delete(id); - } + end(id: string, fate: Outcome): Promise { + return this.named.end(id, fate); + } + + /** What is known of an action sent under this name. */ + seen(id: string) { + return this.named.seen(id); } /** A held action from the edge: run it unless it has been seen before. */ private async take(held: Held): Promise { if (this.acks.some((a) => a.id === held.id)) return; // Still being done (its answer was slow, not lost): say nothing yet. - if (this.running.has(held.id)) return; - const seen = (await this.fate()).get(held.id); + if (this.named.isRunning(held.id)) return; + const seen = await this.named.get(held.id); if (seen === "started") { // The host stopped while this was running. Whether it happened is // not known, and running it again could do it twice. const fate = { ok: false, error: "the host restarted while doing this; check whether it happened" }; - await this.record(held.id, fate); + await this.named.record(held.id, fate); this.acks.push({ id: held.id, ...fate }); return; } @@ -178,7 +163,7 @@ export class EdgeLink { if (!HOLDABLE.has(held.kind)) { fate = { ok: false, error: "this is not an action that may be done late" }; } else { - await this.record(held.id, "started"); + await this.named.record(held.id, "started"); try { await this.o.run(held); fate = { ok: true }; @@ -186,7 +171,7 @@ export class EdgeLink { fate = { ok: false, error: (error as Error).message.slice(0, 300) }; } } - await this.record(held.id, fate); + await this.named.record(held.id, fate); this.acks.push({ id: held.id, ...fate }); } diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index 5a8f5c41d8..c954502bbf 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -16,8 +16,13 @@ import { deviceLabel, deviceState, endpointMark, + everyRead, + flushSaid, + freshSaid, intakeArgs, intakeSaid, + keptGroups, + keptSaid, levelHeadings, phaseHeading, prCheck, @@ -537,4 +542,140 @@ test("text on a status colour can be read, on the dark page and the light one", const background = /background:\s*var\((--[a-z-]+)\)/.exec(body)?.[1]; expect(body).toContain(`color: var(${background}-ink)`); } + // A button on a toast (Undo) is written in the toast's ink, not the page's. + expect(block(css.indexOf("\n.toast button {"))).toContain("color: inherit"); +}); + +test("the corner of the header says live, how old, offline or signed out", () => { + const now = Date.parse("2026-11-23T12:00:00Z"); + const at = (secondsAgo: number) => now - secondsAgo * 1000; + expect(freshSaid({ asOf: at(10) }, now)).toEqual({ text: "live", tone: "" }); + expect(freshSaid({ asOf: at(120) }, now)).toEqual({ text: "as of 2 min ago", tone: "" }); + expect(freshSaid({ asOf: at(600) }, now)).toEqual({ text: "as of 10 min ago", tone: "stale" }); + // With no connection it never says "live", however recent the copy. + expect(freshSaid({ asOf: at(10), offline: true }, now)).toEqual({ text: "offline · just now", tone: "stale" }); + expect(freshSaid({ asOf: at(7200), offline: true }, now)).toEqual({ text: "offline · 2 h ago", tone: "stale" }); + expect(freshSaid({ offline: true }, now)).toEqual({ text: "offline", tone: "stale" }); + // Signed out is said before anything else: it is what to act on. + expect(freshSaid({ asOf: at(10), offline: true, signedOut: true }, now)).toEqual({ + text: "signed out", + tone: "down", + }); + expect(freshSaid({}, now)).toEqual({ text: "", tone: "" }); +}); + +test("the line under the header says there is no connection and what is kept, and nothing when there is nothing to say", () => { + expect(keptSaid({})).toBeNull(); + expect( + keptSaid({ offline: false, signedOut: false, summary: { waiting: 0, stale: 0, failed: 0, held: 2, done: 5 } }), + ).toBeNull(); + expect(keptSaid({ offline: true })).toEqual({ + text: "No connection: this is what the device last saw.", + tone: "", + to: "more/device", + }); + expect(keptSaid({ offline: true, summary: { waiting: 1 } })).toEqual({ + text: "No connection: this is what the device last saw · 1 thing kept to send.", + tone: "", + to: "more/device", + }); + // Connected, and something still waits (it is being sent, or waits for a machine). + expect(keptSaid({ summary: { waiting: 3 } })).toEqual({ + text: "3 things kept to send.", + tone: "", + to: "more/device", + }); + // What needs the owner is said as needing them. + expect(keptSaid({ summary: { waiting: 1, stale: 2, failed: 1 } })).toEqual({ + text: "1 thing kept to send · 2 things kept back for you to look at · 1 thing could not be done.", + tone: "warn", + to: "more/device", + }); + // Signed out: a tap signs in again, unless there is something to look at first. + expect(keptSaid({ signedOut: true, offline: true, summary: { waiting: 2 } })).toEqual({ + text: "Signed out: tap to sign in again · 2 things kept to send.", + tone: "warn", + to: "reload", + }); + expect(keptSaid({ signedOut: true, summary: { failed: 1 } })?.to).toBe("more/device"); +}); + +test("what a send did is said in one line, and nothing is said of nothing", () => { + const e = (state: string) => ({ state }); + expect(flushSaid([])).toBe(""); + expect(flushSaid([e("waiting")])).toBe(""); + expect(flushSaid([e("done")])).toBe("What you did offline: 1 sent."); + // Taken by the platform for a machine counts as sent: it has it. + expect(flushSaid([e("done"), e("held"), e("failed"), e("stale"), e("stale")])).toBe( + "What you did offline: 2 sent, 1 could not be done, 2 kept back for you to look at.", + ); +}); + +test("what is kept is listed by what it needs: waiting, kept back, failed, with the platform, sent", () => { + const e = (id: string, state: string, at: number) => ({ id, state, at }); + const groups = keptGroups([ + e("d1", "done", 1), + e("w1", "waiting", 2), + e("w2", "waiting", 5), + e("f1", "failed", 3), + e("s1", "stale", 4), + e("h1", "held", 6), + ]); + expect(groups.map((g) => [g.title, g.can, g.entries.map((x: { id: string }) => x.id)])).toEqual([ + ["Waiting to send", ["drop"], ["w2", "w1"]], + ["Kept back for you to look at", ["send", "drop"], ["s1"]], + ["Could not be done", ["again", "drop"], ["f1"]], + ["With the platform, waiting for a machine", [], ["h1"]], + ["Sent", [], ["d1"]], + ]); + // A group with nothing in it is not shown. + expect(keptGroups([e("w1", "waiting", 1)]).map((g) => g.state)).toEqual(["waiting"]); + expect(keptGroups([])).toEqual([]); +}); + +test("keeping a copy of every screen reads each under the address its screen asks for it by", () => { + const caps = [{ id: "id" }, { id: "pm-stack" }, { id: "repo-and-ci" }]; + expect(everyRead(caps, true)).toEqual([ + "doc/core", + "doc/questions", + "doc/ops", + "me", + "roadmaps", + "roadmap?area=id", + "roadmap?area=pm-stack", + "roadmap?area=repo-and-ci", + "bugs", + "intake", + "queue?status=blocked&q=", + "queue?status=queued&q=", + "queue?status=claimed&q=", + "queue?status=parked&q=", + "releases", + "messages?limit=15", + "push", + "devices", + "signin", + "android", + ]); + // Served straight from a machine there is no kept Android build to ask about. + expect(everyRead(caps, false)).not.toContain("android"); + // The list of capabilities could not be read: the rest still is. + expect(everyRead(undefined, false)).toEqual([ + "doc/core", + "doc/questions", + "doc/ops", + "me", + "roadmaps", + "bugs", + "intake", + "queue?status=blocked&q=", + "queue?status=queued&q=", + "queue?status=claimed&q=", + "queue?status=parked&q=", + "releases", + "messages?limit=15", + "push", + "devices", + "signin", + ]); }); diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts index e9920ecd24..43d0c65187 100644 --- a/pm-stack/console/test/console.test.ts +++ b/pm-stack/console/test/console.test.ts @@ -947,6 +947,19 @@ describe("operations", () => { ]); await expect(ops.pr("12240")).rejects.toThrow(/failed \(exit 1\).*Not Found/); await expect(ops.mergePr("12240/merge")).rejects.toThrow(OpError); + // With the commit the owner was shown, GitHub is told to merge that + // and nothing pushed since. + const head = "0123456789abcdef0123456789abcdef01234567"; + await ops.mergePr(12240, head); + expect(r.calls.at(-1)?.argv.slice(-4)).toEqual(["-f", "merge_method=merge", "-f", `sha=${head}`]); + // What is not a commit's full name is not passed on as one. + const before = r.calls.length; + await expect(ops.mergePr(12240, "main")).rejects.toThrow(/head: a commit/); + await expect(ops.mergePr(12240, 7)).rejects.toThrow(/head: a commit/); + expect(r.calls.length).toBe(before); + // And none given is none asked for. + await ops.mergePr(12240, null); + expect(r.calls.at(-1)?.argv.slice(-2)).toEqual(["-f", "merge_method=merge"]); }); }); @@ -1020,13 +1033,55 @@ describe("HTTP surface", () => { expect((await handle(get("/elsewhere"), alone)).status).toBe(404); }); + test("every file the page and the worker load is served here, served by the edge, and shipped in the edge's build", async () => { + // Three lists name the app's files: this service's, the edge's, and + // what the edge's build copies. A file missing from one of them + // works on the laptop and is a 404 behind Cloudflare, or the other + // way round; and the worker cannot open the app offline without + // every one of them. + const read = (path: string) => readFileSync(join(import.meta.dir, "..", path), "utf8"); + const page = [...read("public/index.html").matchAll(/(?:src|href)="\/console\/([^"]+)"/g)].map((m) => m[1]); + const worker = [ + ...(/const FILES = \[([^\]]+)\]/.exec(read("public/sw.js"))?.[1] ?? "").matchAll(/"\/console\/([^"]+)"/g), + ].map((m) => m[1]); + const loaded = [...new Set([...page, ...worker, "sw.js"])].sort(); + expect(loaded).toEqual(["app.css", "app.js", "icon.svg", "outbox.js", "sw.js"]); + // The worker keeps everything the page loads, or the page would not open offline. + expect([...new Set(worker)].sort()).toEqual(page.sort()); + const d = deps("owner"); + for (const name of loaded) expect([name, (await handle(get(`/console/${name}`), d)).status]).toEqual([name, 200]); + const edgeServes = [ + ...(/const STATIC: Record = \{([^}]+)\}/.exec(read("edge/src/edge.ts"))?.[1] ?? "").matchAll( + /"([^"]+)":/g, + ), + ].map((m) => m[1]); + expect(edgeServes.sort()).toEqual(loaded); + const built = [ + ...( + /for \(const name of \[([^\]]+)\]\) \{\s*cpSync\(join\(here, "\.\.", "public"/.exec( + read("edge/build.mjs"), + )?.[1] ?? "" + ).matchAll(/"([^"]+)"/g), + ].map((m) => m[1]); + expect(built.sort()).toEqual([...loaded, "index.html"].sort()); + }); + test("the page and its files are served to the owner with a strict policy", async () => { const d = deps("owner"); const page = await handle(get("/console/"), d); expect(page.headers.get("content-type")).toContain("text/html"); expect(page.headers.get("content-security-policy")).toContain("default-src 'self'"); - expect(await page.text()).toContain('src="/console/app.js"'); + const html = await page.text(); + expect(html).toContain('src="/console/app.js"'); expect((await handle(get("/console/app.css"), d)).headers.get("content-type")).toContain("text/css"); + // The file that keeps what the owner did with no connection comes + // before the app, which uses it; and the worker loads it by this address. + expect(html.indexOf('src="/console/outbox.js"')).toBeGreaterThan(0); + expect(html.indexOf('src="/console/outbox.js"')).toBeLessThan(html.indexOf('src="/console/app.js"')); + const outbox = await handle(get("/console/outbox.js"), d); + expect([outbox.status, outbox.headers.get("content-type")]).toEqual([200, "text/javascript; charset=utf-8"]); + expect(await outbox.text()).toContain("PMOutbox"); + expect(await (await handle(get("/console/sw.js"), d)).text()).toContain('importScripts("/console/outbox.js")'); // The site is only ever HTTPS, and says so. expect(page.headers.get("strict-transport-security")).toBe("max-age=31536000"); // A visit does not download the app again: each file says which diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index a3b4e5b513..6d07d12c1b 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -157,7 +157,7 @@ async function setup(options: { direct?: boolean } = {}) { html_url: "https://github.com/developing-today/code/pull/55", created_at: "2026-11-22T12:30:00Z", user: { login: "worker" }, - head: { ref: "queue/55" }, + head: { ref: "queue/55", sha: "5555555555555555555555555555555555555555" }, }, ]; const ghSearch = [ @@ -185,11 +185,13 @@ async function setup(options: { direct?: boolean } = {}) { /** Calls GitHub gives no answer to at all, and calls it is slow to * answer: held until the test lets them go. */ const ghDrops: ((method: string, url: string) => boolean)[] = []; + /** Calls GitHub answers in a way a test gives: a status and its words. */ + const ghSays: { match: (method: string, url: string) => boolean; status: number; message: string }[] = []; const ghHolds: { match: (method: string, url: string) => boolean; wait: Promise }[] = []; const ghBreaks: ((method: string, url: string) => boolean)[] = []; /** GitHub answering a new issue with no number on it: not something * it does, and exactly what must not be passed on as a task. */ - const ghOdd = { noNumber: false }; + const ghOdd = { noNumber: false, longAddress: false }; /** Pull requests merged and workflows started through GitHub's API. */ const ghMerged: { pr: number; body: unknown }[] = []; const ghStarted: { workflow: string; body: unknown }[] = []; @@ -388,6 +390,11 @@ async function setup(options: { direct?: boolean } = {}) { const pr = ghPrs.find((p) => p.number === Number(prMatch[1])); if (!pr) return fail(404, { message: "Not Found" }); if (method === "PUT" && prMatch[2]) { + // Asked to merge a commit it no longer stands at: GitHub's own words. + const asked = (JSON.parse(body ?? "{}") as { sha?: string }).sha; + if (asked !== undefined && asked !== pr.head.sha) { + return fail(409, { message: "Head branch was modified. Review and try the merge again." }); + } ghMerged.push({ pr: pr.number, body: JSON.parse(body ?? "{}") }); ghPrs.splice(ghPrs.indexOf(pr), 1); return ok({ merged: true, sha: "5a5a5a5a5a5a" }); @@ -469,7 +476,7 @@ async function setup(options: { direct?: boolean } = {}) { number: n, title: parsed.title ?? "", body: parsed.body ?? "", - html_url: `https://github.com/developing-today/code/issues/${n}`, + html_url: `https://github.com/developing-today/code/issues/${n}${ghOdd.longAddress ? `?${"x".repeat(5000)}` : ""}`, state: "open", created_at: new Date(now.t).toISOString(), updated_at: new Date(now.t).toISOString(), @@ -546,6 +553,8 @@ async function setup(options: { direct?: boolean } = {}) { if (ghBreaks.some((breaks) => breaks(method, u))) { return { ok: false, status: 500, json: async () => ({ message: "Server Error" }) }; } + const says = ghSays.find((say) => say.match(method, u)); + if (says) return { ok: false, status: says.status, json: async () => ({ message: says.message }) }; return githubAnswer(method, u, init?.body); } if (u === `${cfg.queueDbUrl}/v2/pipeline`) { @@ -792,6 +801,7 @@ async function setup(options: { direct?: boolean } = {}) { const files = new Map([ ["/console/index.html", "PM"], ["/console/app.js", "// app"], + ["/console/outbox.js", "// what is kept"], ["/icons/icon-192.png", "PNG"], ]); const io: Io = { @@ -873,6 +883,7 @@ async function setup(options: { direct?: boolean } = {}) { publicKey: () => link.now.publicKey(), begin: (id) => link.now.begin(id), end: (id, fate) => link.now.end(id, fate), + seen: (id) => link.now.seen(id), }; const token = (claims: Record = {}) => @@ -910,8 +921,9 @@ async function setup(options: { direct?: boolean } = {}) { }), io, ); - const act = (kind: string, args: Record = {}) => - browse("/console/api/act", { body: { kind, args } }); + /** With `id`, the action goes under the name a device gave it. */ + const act = (kind: string, args: Record = {}, id?: string) => + browse("/console/api/act", { body: id === undefined ? { kind, args } : { kind, args, id } }); const core = async () => { const res = await browse("/console/api/doc/core"); return { res, doc: (await res.json()) as Record }; @@ -957,6 +969,7 @@ async function setup(options: { direct?: boolean } = {}) { ghRefuses, ghLimits, ghDrops, + ghSays, ghHolds, queueReadOnly, ghBreaks, @@ -1099,6 +1112,14 @@ describe("the owner, at the edge", () => { expect(await page.text()).toContain("PM"); expect(page.headers.get("content-security-policy")).toContain("default-src 'self'"); expect((await w.browse("/console/app.js")).headers.get("content-type")).toBe("text/javascript; charset=utf-8"); + // The file that keeps what the owner did with no connection is one + // of the app's files here too: the page and the worker both load it. + const outbox = await w.browse("/console/outbox.js"); + expect([outbox.status, outbox.headers.get("content-type"), await outbox.text()]).toEqual([ + 200, + "text/javascript; charset=utf-8", + "// what is kept", + ]); // A visit does not download the app again. Each file says which // version of itself it is; a browser that names that version is told // "still that" and sent nothing, and any other is sent the file. @@ -1477,6 +1498,98 @@ describe("actions", () => { ).toEqual(["done"]); }); + test("an action a device sends twice under one name is done once by the laptop, and answered the same", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + const id = "0a000000-0000-4000-8000-000000000001"; + const first = await w.act("ask.send", { text: "once, please" }, id); + expect(await first.json()).toEqual({ ok: true, result: { issue: 101 } }); + // The device never heard, and sends it again. + const second = await w.act("ask.send", { text: "once, please" }, id); + expect(second.status).toBe(200); + expect(await second.json()).toEqual({ ok: true, result: { issue: 101 }, again: true }); + expect(w.ran).toHaveLength(1); + // It is on the record of what was done under the device's name for it. + const { doc } = await w.core(); + expect(doc.acts.filter((a: { id: string }) => a.id === id).map((a: { status: string }) => a.status)).toEqual([ + "done", + ]); + // One that failed is not tried again under the same name either: + // the device is told again why, with the status it had. + const bad = "0a000000-0000-4000-8000-000000000002"; + const failed = await w.act("issue.comment", { issue: 13, text: "no such issue" }, bad); + expect([failed.status, await failed.json()]).toEqual([404, { error: "no such issue" }]); + const again = await w.act("issue.comment", { issue: 13, text: "no such issue" }, bad); + expect([again.status, await again.json()]).toEqual([404, { error: "no such issue", again: true }]); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + // A name that is not one (not a UUID) is no name: done each time, as before. + await w.act("issue.comment", { issue: 7, text: "a" }, "not-a-name"); + await w.act("issue.comment", { issue: 7, text: "a" }, "not-a-name"); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(3); + }); + + test("sent again while the laptop is still doing it, the device is told to wait; sent again after the laptop restarted mid-way, that it is not known", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + const id = "0a000000-0000-4000-8000-000000000003"; + let done = () => {}; + w.gate.wait = new Promise((resolve) => { + done = resolve; + }); + const slow = w.act("need.comment", { ref: "developing-today/code#1", text: "slow" }, id); + await new Promise((r) => setTimeout(r, 5)); + const meanwhile = await w.act("need.comment", { ref: "developing-today/code#1", text: "slow" }, id); + expect([meanwhile.status, await meanwhile.json()]).toEqual([ + 409, + { error: "This is still being done.", running: true }, + ]); + done(); + expect((await slow).status).toBe(200); + w.gate.wait = null; + expect(w.ran.filter((r) => r.kind === "need.comment")).toHaveLength(1); + // Started, and the laptop's console restarted before it ended. + const lost = "0a000000-0000-4000-8000-000000000004"; + await w.link.now.begin(lost); + w.link.now = w.makeLink(); + const asked = await w.act("need.comment", { ref: "developing-today/code#2", text: "lost" }, lost); + expect(asked.status).toBe(502); + expect(((await asked.json()) as { error: string }).error).toContain("restarted while doing this"); + expect(w.ran.filter((r) => r.kind === "need.comment")).toHaveLength(1); + }); + + test("held twice under one name, an action waits once", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + w.net.hostUp = false; + const id = "0a000000-0000-4000-8000-000000000005"; + expect(await (await w.act("ask.send", { text: "kept once" }, id)).json()).toEqual({ + ok: true, + held: true, + result: null, + }); + expect(await (await w.act("ask.send", { text: "kept once" }, id)).json()).toEqual({ + ok: true, + held: true, + result: null, + again: true, + }); + expect((w.stored.get("held") as { id: string }[]).map((h) => h.id)).toEqual([id]); + // The laptop comes back and does it once; sent yet again, the device + // is told how it came out. + w.net.hostUp = true; + w.now.t += 1_000; + await w.link.now.once(); + w.now.t += 1_000; + await w.link.now.once(); + expect(w.ran).toHaveLength(1); + const after = await w.act("ask.send", { text: "kept once" }, id); + expect(await after.json()).toMatchObject({ ok: true, again: true }); + expect(w.ran).toHaveLength(1); + }); + test("an action the host is still doing when the edge stops waiting is neither repeated nor reported early", async () => { const w = await setup(); await w.hostReads(); @@ -2588,6 +2701,7 @@ describe("the edge does the core itself", () => { created: "2026-11-22T12:30", author: "worker", branch: "queue/55", + head: "5555555555555555555555555555555555555555", }, ]); expect(ops.priorities.issues.map((i) => [i.number, i.rank])).toEqual([[301, "now"]]); @@ -2932,6 +3046,165 @@ describe("the edge does the core itself", () => { expect(JSON.stringify(audit)).not.toContain("Thanks"); }); + test("an action a device sends twice under one name is done here once, and answered the same after a restart too", async () => { + const w = await primary(); + const id = "0b000000-0000-4000-8000-000000000001"; + const comments = () => + w.githubCalls.filter((c) => c.method === "POST" && c.url.includes("/issues/201/comments")).length; + const first = await w.act("ask.reply", { issue: 201, text: "Only once." }, id); + expect(await first.json()).toEqual({ ok: true, result: { issue: 201, queued: true } }); + const second = await w.act("ask.reply", { issue: 201, text: "Only once." }, id); + expect(await second.json()).toEqual({ ok: true, result: { issue: 201, queued: true }, again: true }); + w.edge.now = w.makeEdge(); + const third = await w.act("ask.reply", { issue: 201, text: "Only once." }, id); + expect(await third.json()).toEqual({ ok: true, result: { issue: 201, queued: true }, again: true }); + expect(comments()).toBe(1); + // Its queue task is waiting for a machine once, too. + expect((w.stored.get("held") as { kind: string }[]).map((h) => h.kind)).toEqual(["prompt.enqueue"]); + // On this side's record of what was done, under the device's name for it. + expect( + (await w.core()).doc.acts.filter((a: { id: string }) => a.id === id).map((a: { status: string }) => a.status), + ).toEqual(["done"]); + expect(w.ran).toEqual([]); + // One that failed is answered the same again, not tried again: the + // device asks under a new name if the owner wants it tried. + const bad = "0b000000-0000-4000-8000-000000000002"; + w.ghBreaks.push((method, url) => method === "PUT" && url.includes("/merge")); + const failed = await w.act("pr.merge", { pr: 55 }, bad); + expect(failed.status).toBe(502); + const said = (await failed.json()) as { error: string }; + w.ghBreaks.length = 0; + const again = await w.act("pr.merge", { pr: 55 }, bad); + expect([again.status, await again.json()]).toEqual([502, { ...said, again: true }]); + expect(w.ghMerged).toEqual([]); + expect((await w.act("pr.merge", { pr: 55 }, "0b000000-0000-4000-8000-000000000003")).status).toBe(200); + expect(w.ghMerged).toHaveLength(1); + // What this side does of its own (a test notification, a device) goes the same way. + const own = "0b000000-0000-4000-8000-000000000004"; + const tried = await w.act("edge.retry", {}, own); + expect(await tried.json()).toEqual({ ok: true, result: { tried: [] } }); + expect(await (await w.act("edge.retry", {}, own)).json()).toEqual({ ok: true, result: { tried: [] }, again: true }); + }); + + test("sent again while it is being done here, the device is told to wait; after this side restarted mid-way, that it is not known", async () => { + const w = await primary(); + const id = "0b000000-0000-4000-8000-000000000005"; + let letGo = () => {}; + const wait = new Promise((r) => { + letGo = r; + }); + const merge = (method: string, url: string) => method === "PUT" && url.includes("/merge"); + w.ghHolds.push({ match: merge, wait }); + const merging = w.act("pr.merge", { pr: 55 }, id); + await new Promise((r) => setTimeout(r, 5)); + const meanwhile = await w.act("pr.merge", { pr: 55 }, id); + expect([meanwhile.status, await meanwhile.json()]).toEqual([ + 409, + { error: "This is still being done.", running: true }, + ]); + // The object is put away while the merge is still out, and the + // device asks the one that starts in its place. + w.edge.now = w.makeEdge(); + const asked = await w.act("pr.merge", { pr: 55 }, id); + expect(asked.status).toBe(502); + expect(((await asked.json()) as { error: string }).error).toContain("Cloudflare restarted while doing this"); + letGo(); + await merging; + // GitHub was asked to merge once. + expect(w.githubCalls.filter((c) => merge(c.method, c.url))).toHaveLength(1); + }); + + test("handed on to the laptop, an action keeps the device's name for it: the laptop does it once", async () => { + const w = await primary(); + const id = "0b000000-0000-4000-8000-000000000006"; + w.ghRefuses.push((method, url) => method === "PUT" && url.includes("/merge")); + const first = await w.act("pr.merge", { pr: 55 }, id); + expect(await first.json()).toMatchObject({ ok: true, result: { merged: 55 } }); + // Nothing was done here, so nothing is written down here under the name ... + expect(w.stored.has(`a:${id}`)).toBe(false); + // ... and sent again, it goes to the laptop, which knows it did it. + const second = await w.act("pr.merge", { pr: 55 }, id); + expect(await second.json()).toMatchObject({ ok: true, result: { merged: 55 }, again: true }); + expect(w.ran).toEqual([{ kind: "pr.merge", args: { pr: 55 } }]); + }); + + test("the names remembered here are bounded: the oldest are forgotten, and an answer too long to keep is kept as how it went", async () => { + const w = await primary(); + const name = (n: number) => `0c000000-0000-4000-8000-${String(n).padStart(12, "0")}`; + for (let n = 1; n <= 302; n++) { + expect((await w.act("edge.retry", {}, name(n))).status).toBe(200); + } + expect(w.stored.has(`a:${name(1)}`)).toBe(false); + expect(w.stored.has(`a:${name(2)}`)).toBe(false); + expect(w.stored.has(`a:${name(3)}`)).toBe(true); + expect((w.stored.get("acted") as unknown[]).length).toBe(300); + // After a week a name is forgotten. + w.now.t += 7 * 24 * 3600_000 + 1; + await w.act("edge.retry", {}, name(999)); + expect(w.stored.has(`a:${name(302)}`)).toBe(false); + expect((w.stored.get("acted") as unknown[]).length).toBe(1); + // An answer too long to keep is kept as how it went, without what it said. + const long = name(1000); + w.ghOdd.longAddress = true; + const filed = await w.act("ask.send", { text: "With a long address" }, long); + expect(filed.status).toBe(200); + expect(((await filed.json()) as { result: { url: string } }).result.url.length).toBeGreaterThan(5000); + const again = await w.act("ask.send", { text: "With a long address" }, long); + expect([again.status, await again.json()]).toEqual([200, { ok: true, result: null, again: true }]); + expect(w.githubCalls.filter((c) => c.method === "POST" && c.url.endsWith("/issues"))).toHaveLength(1); + }); + + test("served straight from the laptop, an action sent twice under one name is done once", async () => { + const w = await setup(); + await w.hostReads(); + const id = "0d000000-0000-4000-8000-000000000001"; + const direct = async (body: unknown) => + handle( + new Request(`https://${HOST}/console/api/act`, { + method: "POST", + headers: { + "content-type": "application/json", + "x-pm-console": "1", + "cf-access-jwt-assertion": await w.token(), + }, + body: JSON.stringify(body), + }), + w.hostDeps, + "127.0.0.1", + ); + const first = await direct({ kind: "ask.send", args: { text: "no edge in between" }, id }); + expect(await first.json()).toEqual({ ok: true, result: { issue: 101 } }); + const second = await direct({ kind: "ask.send", args: { text: "no edge in between" }, id }); + expect(await second.json()).toEqual({ ok: true, result: { issue: 101 }, again: true }); + expect(w.ran).toHaveLength(1); + // Without a name it is done each time it is asked, as it always was. + await direct({ kind: "ask.send", args: { text: "no edge in between" } }); + expect(w.ran).toHaveLength(2); + }); + + test("a merge asked for from the list is a merge of what the list showed, not of what was pushed since", async () => { + const w = await primary(); + const shown = ( + (await (await w.browse("/console/api/doc/ops")).json()) as { prs: { number: number; head: string }[] } + ).prs[0]; + // Something is pushed to it after the owner looked (and, offline, + // asked for the merge). + w.ghPrs[0].head.sha = "6666666666666666666666666666666666666666"; + const late = await w.act("pr.merge", { pr: shown.number, head: shown.head }); + expect(late.status).toBe(502); + expect(((await late.json()) as { error: string }).error).toContain("Head branch was modified"); + expect(w.ghMerged).toEqual([]); + // That was GitHub's answer to the question asked, not a refusal of + // this side's token: it is not handed to the laptop to merge blind. + expect(w.ran).toEqual([]); + // Looked at again and asked again, it is merged as it now stands. + const now = await w.act("pr.merge", { pr: shown.number, head: "6666666666666666666666666666666666666666" }); + expect(now.status).toBe(200); + expect(w.ghMerged).toEqual([ + { pr: 55, body: { merge_method: "merge", sha: "6666666666666666666666666666666666666666" } }, + ]); + }); + test("a new prompt is filed here and only its queue task waits for a machine, which files it once", async () => { const w = await primary(); w.net.hostUp = false; diff --git a/pm-stack/console/test/outbox.test.ts b/pm-stack/console/test/outbox.test.ts new file mode 100644 index 0000000000..58c0c4ff09 --- /dev/null +++ b/pm-stack/console/test/outbox.test.ts @@ -0,0 +1,524 @@ +// What the owner did, kept on the device until the platform has it. +// +// Oracles: the rules are written out here by hand for each case: which +// actions wait, which are sent only while fresh, which are never kept; +// what each kind of answer does to an entry; in what order things are +// sent, and when sending stops. The store is the file's own in-memory +// one, and the sender is a stand-in that answers as a test says. That a +// real browser keeps these across a reload and a real platform takes +// each once is checked in a browser and in test/edge.test.ts. +import { expect, test } from "bun:test"; +import "../public/outbox.js"; + +interface Entry { + id: string; + kind: string; + args: Record; + said: string; + at: number; + state: string; + note: string; + tries: number; + sure?: boolean; + endedAt?: number; + triedAt?: number; + result?: unknown; +} +type Answer = { network?: boolean; signin?: boolean; status?: number; body?: unknown }; +interface Store { + all(): Promise; + put(entry: Entry): Promise; + remove(id: string): Promise; +} +const O = (globalThis as unknown as { PMOutbox: Record }).PMOutbox as { + TIMELY_MS: number; + rule(kind: string): "late" | "timely" | "now"; + sayOf(kind: string, args?: unknown): string; + make(kind: string, args: unknown, now: number, said?: string, id?: string): Entry; + classify(answer: Answer): { state: string; note: string; stop?: boolean; signin?: boolean; result?: unknown }; + due(entry: Entry, now: number): boolean; + summary(entries: Entry[]): Record; + expired(entries: Entry[], now: number): string[]; + flush( + store: Store, + send: (entry: Entry) => Promise, + now?: () => number, + ): Promise<{ changed: Entry[]; signin: boolean; offline: boolean }>; + settle(store: Store, acts: unknown, now?: () => number): Promise; + httpSend(entry: Entry, fetchImpl: (url: string, init: RequestInit) => Promise): Promise; + memoryStore(): Store; +}; + +const T0 = 1_800_000_000_000; +const MIN = 60_000; +const ok = (result: unknown = {}): Answer => ({ status: 200, body: { ok: true, result } }); + +test("what may wait, what is sent only while it is fresh, and what needs a connection", () => { + // What the owner says or decides does not go stale. + for (const kind of [ + "ask.send", + "ask.reply", + "ask.close", + "question.answer", + "question.defer", + "questions.accept", + "hands.done", + "need.comment", + "issue.comment", + "issue.rank", + "task.move", + "message.send", + "intake.send", + ]) { + expect([kind, O.rule(kind)]).toEqual([kind, "late"]); + } + // These act on something that may have changed by the time they go. + for (const kind of ["pr.merge", "deploy.start", "task.cancel", "task.unblock", "unit.act"]) { + expect([kind, O.rule(kind)]).toEqual([kind, "timely"]); + } + // These set the connection up or carry a secret, and anything this + // file has not heard of is not kept on a guess. + for (const kind of [ + "sso.google", + "push.on", + "push.off", + "push.class", + "push.test", + "device.approve", + "device.remove", + "edge.direct", + "edge.retry", + "something.new", + "", + ]) { + expect([kind, O.rule(kind)]).toEqual([kind, "now"]); + } + expect(O.TIMELY_MS).toBe(10 * MIN); +}); + +test("each action is said in a line the owner will know it by", () => { + const said = (kind: string, args: unknown) => O.sayOf(kind, args); + expect(said("ask.send", { text: "Ship the parser\nrework this week" })).toBe( + "Prompt: “Ship the parser rework this week”", + ); + expect(said("ask.send", { text: "x".repeat(200) })).toBe(`Prompt: “${"x".repeat(59)}…”`); + expect(said("ask.reply", { issue: 201, text: "Yes" })).toBe("Reply on #201: “Yes”"); + expect(said("ask.close", { issue: 202 })).toBe("Mark prompt #202 done"); + expect(said("issue.comment", { issue: 301, text: "" })).toBe("Comment on #301"); + expect(said("issue.rank", { issue: 301, rank: "next" })).toBe("Rank #301 next"); + expect(said("need.comment", { ref: "developing-today/code#9", text: "Done" })).toBe( + "Reply on developing-today/code#9: “Done”", + ); + expect(said("hands.done", { ref: "developing-today/code#9" })).toBe("Mark developing-today/code#9 done"); + expect(said("task.move", { task: 21048, to: "first" })).toBe("Move task 21048 to the top"); + expect(said("task.move", { task: 21048, to: "later" })).toBe("Move task 21048 later"); + expect(said("task.cancel", { task: 7 })).toBe("Cancel task 7"); + expect(said("task.unblock", { task: 7 })).toBe("Unblock task 7"); + expect(said("pr.merge", { pr: 55 })).toBe("Merge #55"); + expect(said("deploy.start", { what: "site" })).toBe("Start the site's deploy"); + expect(said("deploy.start", { what: "app" })).toBe("Start the app's build"); + expect(said("intake.send", { kind: "bug", text: "It crashes" })).toBe("Bug: “It crashes”"); + expect(said("intake.send", { kind: "note", text: "Think about X" })).toBe("Note: “Think about X”"); + expect(said("intake.send", { kind: "change", text: "Move it" })).toBe("Change: “Move it”"); + expect(said("intake.send", { kind: "note", session: true, text: "Do it now" })).toBe("Session: “Do it now”"); + expect(said("question.answer", { answer: "yes" })).toBe("Answer: “yes”"); + expect(said("question.answer", { answer: ["a", "b"] })).toBe("Answer: “a, b”"); + expect(said("question.defer", {})).toBe("Put a question off"); + expect(said("questions.accept", { set: "s" })).toBe("Accept the recommended answers"); + expect(said("message.send", { to: ["xaltha"], text: "hello" })).toBe("Message to xaltha: “hello”"); + expect(said("unit.act", { unit: "pm-console.service", action: "restart" })).toBe("restart pm-console.service"); + // One it does not know is still said, as it came; and no arguments are no reason to fail. + expect(said("something.new", { a: 1 })).toBe("something.new"); + expect(O.sayOf("ask.close")).toBe("Mark prompt #undefined done"); +}); + +test("an entry is the action as it stood, under a name of its own", () => { + const a = O.make("pr.merge", { pr: 55 }, T0); + const b = O.make("pr.merge", { pr: 55 }, T0); + expect(a).toEqual({ + id: a.id, + kind: "pr.merge", + args: { pr: 55 }, + said: "Merge #55", + at: T0, + state: "waiting", + note: "", + tries: 0, + }); + // The name is the kind the platform takes: a UUID in lower case. + expect(a.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/); + expect(a.id).not.toBe(b.id); + expect( + O.make("ask.send", { text: "x" }, T0, "Said by the caller", "0a000000-0000-4000-8000-000000000001"), + ).toMatchObject({ + said: "Said by the caller", + id: "0a000000-0000-4000-8000-000000000001", + }); + expect(O.make("ask.close", undefined, T0).args).toEqual({}); +}); + +test("what each kind of answer does to an entry", () => { + // No answer at all: it waits, and so will the rest. + expect(O.classify({ network: true })).toEqual({ state: "waiting", note: "", stop: true }); + // Done, with what it answered. + expect(O.classify(ok({ issue: 500 }))).toEqual({ state: "done", note: "", result: { issue: 500 } }); + expect(O.classify({ status: 200, body: { ok: true } })).toEqual({ state: "done", note: "", result: null }); + // Taken, and kept by the platform for a machine. + expect(O.classify({ status: 200, body: { ok: true, held: true, result: null } })).toEqual({ + state: "held", + note: "Kept for the laptop, which will do it when it is back.", + result: null, + }); + // Refused or failed, in the platform's own words: not tried again by itself. + expect(O.classify({ status: 404, body: { error: "no such issue" } })).toEqual({ + state: "failed", + note: "no such issue", + }); + expect(O.classify({ status: 502, body: { error: "GitHub said no" } })).toEqual({ + state: "failed", + note: "GitHub said no", + }); + expect(O.classify({ status: 400, body: {} })).toEqual({ state: "failed", note: "http 400" }); + // A 200 that does not say it worked did not work. + expect(O.classify({ status: 200, body: { error: "odd" } })).toEqual({ state: "failed", note: "odd" }); + // Being done now under this name, or nothing to take it just now: it + // waits, and the others are still tried. + expect(O.classify({ status: 409, body: { error: "This is still being done.", running: true } })).toEqual({ + state: "waiting", + note: "Being done now.", + }); + expect(O.classify({ status: 409, body: { error: "conflict" } })).toEqual({ state: "failed", note: "conflict" }); + expect( + O.classify({ + status: 503, + body: { + error: + "The laptop did not answer, and this is not something to do late, so it is not kept. Check whether it happened before trying again.", + }, + }), + ).toEqual({ state: "waiting", note: "Nothing could take it just now. It is offered again." }); + // Not the platform's answer (a sign-in page, something in between): + // it waits for a sign-in, and so will the rest. + for (const answer of [ + { signin: true, status: 0, body: null }, + { status: 200, body: null }, + { status: 200, body: "html" }, + ]) { + expect(O.classify(answer)).toEqual({ + state: "waiting", + note: "Sign in again to send this.", + stop: true, + signin: true, + }); + } +}); + +test("a timely action is sent by itself only while it is fresh, or once the owner has looked again", () => { + const merge = O.make("pr.merge", { pr: 55 }, T0); + expect(O.due(merge, T0)).toBe(true); + expect(O.due(merge, T0 + 10 * MIN)).toBe(true); + expect(O.due(merge, T0 + 10 * MIN + 1)).toBe(false); + expect(O.due({ ...merge, sure: true }, T0 + 24 * 60 * MIN)).toBe(true); + // What may wait is due however old it is. + expect(O.due(O.make("ask.send", { text: "x" }, T0), T0 + 30 * 24 * 60 * MIN)).toBe(true); + // What is not waiting is not due. + for (const state of ["done", "failed", "held", "stale"]) { + expect(O.due({ ...O.make("ask.send", {}, T0), state }, T0)).toBe(false); + } +}); + +test("what is waiting is sent oldest first, each once, and the list says what became of each", async () => { + const store = O.memoryStore(); + const first = O.make("ask.send", { text: "first" }, T0); + const second = O.make("issue.rank", { issue: 301, rank: "next" }, T0 + 1_000); + const third = O.make("issue.comment", { issue: 13, text: "x" }, T0 + 2_000); + const fourth = O.make("ask.reply", { issue: 201, text: "held" }, T0 + 3_000); + // Put out of order: the order is when they were done. + for (const e of [third, first, fourth, second]) await store.put(e); + const sent: string[] = []; + const send = async (e: Entry): Promise => { + sent.push(e.kind); + if (e.kind === "issue.comment") return { status: 404, body: { error: "no such issue" } }; + if (e.kind === "ask.reply") return { status: 200, body: { ok: true, held: true, result: null } }; + return ok({ n: sent.length }); + }; + const now = T0 + 60_000; + const out = await O.flush(store, send, () => now); + expect(sent).toEqual(["ask.send", "issue.rank", "issue.comment", "ask.reply"]); + expect(out.changed.map((e) => [e.kind, e.state, e.note])).toEqual([ + ["ask.send", "done", ""], + ["issue.rank", "done", ""], + ["issue.comment", "failed", "no such issue"], + ["ask.reply", "held", "Kept for the laptop, which will do it when it is back."], + ]); + expect([out.signin, out.offline]).toEqual([false, false]); + const kept = (await store.all()).sort((a, b) => a.at - b.at); + expect(kept.map((e) => [e.state, e.tries, e.triedAt, e.endedAt])).toEqual([ + ["done", 1, now, now], + ["done", 1, now, now], + ["failed", 1, now, now], + ["held", 1, now, now], + ]); + expect(kept[0].result).toEqual({ n: 1 }); + // Nothing is waiting now: a second flush sends nothing. + expect((await O.flush(store, send, () => now)).changed).toEqual([]); + expect(sent).toHaveLength(4); + expect(O.summary(kept)).toEqual({ waiting: 0, stale: 0, held: 1, failed: 1, done: 2, open: 1 }); +}); + +test("with no connection nothing is lost and nothing is tried twice in a row; with one, it goes", async () => { + const store = O.memoryStore(); + await store.put(O.make("ask.send", { text: "one" }, T0)); + await store.put(O.make("ask.send", { text: "two" }, T0 + 1)); + let tries = 0; + const down = async (): Promise => { + tries++; + throw new TypeError("Failed to fetch"); + }; + const out = await O.flush(store, down, () => T0 + 5); + // The first got no answer: the second is not tried, it would fare no better. + expect(tries).toBe(1); + expect([out.changed, out.offline, out.signin]).toEqual([[], true, false]); + expect((await store.all()).map((e) => [e.state, e.tries])).toEqual([ + ["waiting", 0], + ["waiting", 0], + ]); + // The sign-in ran out: the same, and it is said why. + const page = await O.flush( + store, + async () => ({ signin: true, status: 0, body: null }), + () => T0 + 6, + ); + expect([page.signin, page.offline, page.changed.map((e) => [e.state, e.note])]).toEqual([ + true, + false, + [["waiting", "Sign in again to send this."]], + ]); + // Back: both go, in order. + const texts: unknown[] = []; + const up = await O.flush( + store, + async (e) => { + texts.push(e.args.text); + return ok(); + }, + () => T0 + 7, + ); + expect(texts).toEqual(["one", "two"]); + expect(up.changed.map((e) => e.state)).toEqual(["done", "done"]); +}); + +test("one that nothing can take just now does not hold up the ones behind it", async () => { + const store = O.memoryStore(); + await store.put(O.make("message.send", { to: ["a"], text: "needs the laptop" }, T0)); + await store.put(O.make("ask.send", { text: "needs nobody" }, T0 + 1)); + const out = await O.flush( + store, + async (e) => + e.kind === "message.send" + ? { status: 503, body: { error: "The laptop cannot be reached, and too much is already waiting for it." } } + : ok(), + () => T0 + 2, + ); + expect(out.changed.map((e) => [e.kind, e.state, e.note])).toEqual([ + ["message.send", "waiting", "Nothing could take it just now. It is offered again."], + ["ask.send", "done", ""], + ]); + // Tried again and told the same, nothing is written again. + const again = await O.flush( + store, + async () => ({ + status: 503, + body: { error: "The laptop cannot be reached, and too much is already waiting for it." }, + }), + () => T0 + 3, + ); + expect(again.changed).toEqual([]); +}); + +test("a merge asked for a while ago is kept back, not sent, until the owner says it still stands", async () => { + const store = O.memoryStore(); + const merge = O.make("pr.merge", { pr: 55 }, T0); + const cancel = O.make("task.cancel", { task: 7, reason: "dup" }, T0 + 9 * MIN); + await store.put(merge); + await store.put(cancel); + const sent: string[] = []; + const send = async (e: Entry) => { + sent.push(e.kind); + return ok(); + }; + // Eleven minutes after the merge was asked for, two after the cancel. + const out = await O.flush(store, send, () => T0 + 11 * MIN); + expect(sent).toEqual(["task.cancel"]); + expect(out.changed.map((e) => [e.kind, e.state, e.note])).toEqual([ + ["pr.merge", "stale", "Not sent: it was a while ago, and this may have changed."], + ["task.cancel", "done", ""], + ]); + // Kept back is not waiting: it is not sent by a later flush either. + await O.flush(store, send, () => T0 + 12 * MIN); + expect(sent).toEqual(["task.cancel"]); + // The owner looks again and says it still stands. + const stale = (await store.all()).find((e) => e.kind === "pr.merge") as Entry; + await store.put({ ...stale, state: "waiting", sure: true, note: "" }); + await O.flush(store, send, () => T0 + 5 * 60 * MIN); + expect(sent).toEqual(["task.cancel", "pr.merge"]); +}); + +test("two flushes at once are one flush: nothing is sent twice", async () => { + const store = O.memoryStore(); + await store.put(O.make("ask.send", { text: "once" }, T0)); + let open: () => void = () => {}; + const gate = new Promise((r) => { + open = r; + }); + let sends = 0; + const send = async () => { + sends++; + await gate; + return ok(); + }; + const a = O.flush(store, send, () => T0 + 1); + const b = O.flush(store, send, () => T0 + 1); + open(); + expect(await a).toBe(await b); + expect(sends).toBe(1); + // And when it is over, the next is a flush of its own. + await store.put(O.make("ask.send", { text: "again" }, T0 + 2)); + await O.flush(store, send, () => T0 + 3); + expect(sends).toBe(2); + // Another store is another matter. + const other = O.memoryStore(); + await other.put(O.make("ask.send", { text: "elsewhere" }, T0)); + await O.flush(other, send, () => T0 + 3); + expect(sends).toBe(3); +}); + +test("what is finished is shown for a day and then dropped; what is not finished is never dropped", async () => { + const done = (n: number, endedAt: number): Entry => ({ ...O.make("ask.send", { n }, T0), state: "done", endedAt }); + const day = 24 * 60 * MIN; + const entries = [ + done(1, T0), + done(2, T0 + day), + { ...O.make("ask.send", {}, T0 - 30 * day), state: "waiting" }, + { ...O.make("pr.merge", {}, T0 - 30 * day), state: "stale" }, + { ...O.make("ask.send", {}, T0 - 30 * day), state: "failed" }, + { ...O.make("ask.reply", {}, T0), state: "held", endedAt: T0 }, + { ...O.make("ask.reply", {}, T0), state: "held", endedAt: T0 + 3 * 60 * MIN }, + ]; + // A day and a bit after the first was done: it goes, the rest stay. + expect(O.expired(entries, T0 + day + 1)).toEqual([entries[0].id]); + // What the platform took for a machine more than 26 hours ago has its outcome on the platform's record. + expect(O.expired(entries, T0 + 26 * 60 * MIN + 1)).toEqual([entries[0].id, entries[5].id]); + // No more than thirty finished ones, newest kept. + const many = Array.from({ length: 33 }, (_, i) => done(i, T0 + i)); + expect(O.expired(many, T0 + 100)).toEqual([many[2].id, many[1].id, many[0].id]); + // A flush does the dropping. + const store = O.memoryStore(); + for (const e of entries) await store.put(e); + await O.flush( + store, + async () => ({ network: true }), + () => T0 + 26 * 60 * MIN + 1, + ); + expect((await store.all()).map((e) => e.state).sort()).toEqual(["done", "failed", "held", "stale", "waiting"]); +}); + +test("what the platform kept for a machine learns how it came out from the platform's own record", async () => { + const store = O.memoryStore(); + const a = { ...O.make("ask.send", { text: "a" }, T0), state: "held" }; + const b = { ...O.make("ask.reply", { issue: 1, text: "b" }, T0 + 1), state: "held" }; + const c = { ...O.make("issue.rank", { issue: 2, rank: "now" }, T0 + 2), state: "held" }; + const d = { ...O.make("ask.send", { text: "d" }, T0 + 3), state: "waiting" }; + for (const e of [a, b, c, d]) await store.put(e); + const acts = [ + { id: a.id, kind: "ask.send", status: "done" }, + { id: b.id, kind: "ask.reply", status: "failed", note: "Sent late, and the laptop could not do it: no such issue" }, + { id: c.id, kind: "issue.rank", status: "running", note: "Held" }, + // Its name is on the record, and it was never taken: not this function's to touch. + { id: d.id, kind: "ask.send", status: "done" }, + { id: "someone-else", kind: "pr.merge", status: "done" }, + ]; + const changed = await O.settle(store, acts, () => T0 + 99); + expect(changed.map((e) => [e.kind, e.state, e.note, e.endedAt])).toEqual([ + ["ask.send", "done", "", T0 + 99], + ["ask.reply", "failed", "Sent late, and the laptop could not do it: no such issue", T0 + 99], + ]); + expect((await store.all()).map((e) => e.state).sort()).toEqual(["done", "failed", "held", "waiting"]); + // A record that cannot be read changes nothing. + expect(await O.settle(store, undefined)).toEqual([]); + expect(await O.settle(store, "nonsense")).toEqual([]); +}); + +test("one try at sending: what goes out, and how each kind of answer is read", async () => { + const entry = O.make("ask.send", { text: "hello" }, T0, undefined, "0a000000-0000-4000-8000-000000000009"); + const calls: { url: string; init: RequestInit }[] = []; + const answering = + (res: unknown) => + async (url: string, init: RequestInit): Promise => { + calls.push({ url, init }); + return res; + }; + const res = (status: number, body: unknown, type = "basic") => ({ + status, + type, + json: async () => { + if (body === undefined) throw new Error("not json"); + return body; + }, + }); + expect(await O.httpSend(entry, answering(res(200, { ok: true, result: { issue: 5 } })))).toEqual({ + status: 200, + body: { ok: true, result: { issue: 5 } }, + }); + // It goes as the app's own writes do, under its name, and the way to + // a sign-in page is not followed. + expect(calls[0].url).toBe("/console/api/act"); + expect(calls[0].init).toEqual({ + method: "POST", + headers: { "Content-Type": "application/json", "X-PM-Console": "1" }, + body: JSON.stringify({ kind: "ask.send", args: { text: "hello" }, id: entry.id }), + redirect: "manual", + }); + // No answer. + expect( + await O.httpSend(entry, async () => { + throw new TypeError("Failed to fetch"); + }), + ).toEqual({ network: true }); + // Sent towards a sign-in page, in either of the ways a browser shows it. + expect(await O.httpSend(entry, answering(res(0, undefined, "opaqueredirect")))).toEqual({ + signin: true, + status: 0, + body: null, + }); + expect(await O.httpSend(entry, answering(res(302, undefined)))).toEqual({ signin: true, status: 0, body: null }); + // No sign-in, whoever says so. + expect(await O.httpSend(entry, answering(res(401, { error: "sign in" })))).toEqual({ + signin: true, + status: 401, + body: null, + }); + expect(await O.httpSend(entry, answering(res(403, undefined)))).toEqual({ signin: true, status: 403, body: null }); + // Refused by the platform in its own words: that is an answer. + expect(await O.httpSend(entry, answering(res(403, { error: "this request did not come from the console" })))).toEqual( + { + status: 403, + body: { error: "this request did not come from the console" }, + }, + ); + // An answer that is not JSON is passed on as none, for classify to read. + expect(await O.httpSend(entry, answering(res(200, undefined)))).toEqual({ status: 200, body: null }); +}); + +test("the store that lives with the page keeps copies, not the caller's own objects", async () => { + const store = O.memoryStore(); + const entry = O.make("ask.send", { text: "x" }, T0); + await store.put(entry); + entry.state = "changed by the caller"; + expect((await store.all())[0].state).toBe("waiting"); + (await store.all())[0].state = "changed by a reader"; + expect((await store.all())[0].state).toBe("waiting"); + await store.remove(entry.id); + await store.remove("not there"); + expect(await store.all()).toEqual([]); +}); diff --git a/pm-stack/console/test/sw.test.ts b/pm-stack/console/test/sw.test.ts index 568c5502ae..3a8425c61c 100644 --- a/pm-stack/console/test/sw.test.ts +++ b/pm-stack/console/test/sw.test.ts @@ -13,21 +13,79 @@ import { join } from "node:path"; interface Shown { title: string; - options: { body: string; tag?: string; renotify: boolean; icon: string; badge: string; data: { url: string } }; + options: { body: string; tag?: string; renotify?: boolean; icon: string; badge: string; data: { url: string } }; } -function worker(windows: { url: string; canNavigate?: boolean }[] = []) { +const ORIGIN = "https://pm.example"; +const PUBLIC = join(import.meta.dir, "../public"); + +/** The browser's cache, as far as the worker uses it. */ +function fakeCaches() { + const stores = new Map>(); + const keyOf = (key: string | Request) => { + const url = new URL(typeof key === "string" ? key : key.url, ORIGIN); + return url.pathname + url.search; + }; + const open = async (name: string) => { + if (!stores.has(name)) stores.set(name, new Map()); + const store = stores.get(name) as Map; + return { + put: async (key: string | Request, res: Response) => void store.set(keyOf(key), res), + match: async (key: string | Request) => store.get(keyOf(key))?.clone(), + keys: async () => [...store.keys()].map((k) => new Request(ORIGIN + k)), + delete: async (key: string | Request) => store.delete(keyOf(key)), + }; + }; + return { + open, + keys: async () => [...stores.keys()], + delete: async (name: string) => stores.delete(name), + /** For the tests: what is kept under a name. */ + kept: (name = "pm-console-v1") => [...(stores.get(name)?.keys() ?? [])].sort(), + stores, + }; +} + +type Net = (url: URL, init?: RequestInit) => Response | Promise; + +function worker( + windows: { url: string; canNavigate?: boolean }[] = [], + options: { net?: Net; permission?: string } = {}, +) { const listeners: Record void> = {}; const shown: Shown[] = []; const did: string[] = []; - const scope = { + const posted: unknown[] = []; + const asked: string[] = []; + const caches = fakeCaches(); + /** Waits the worker asked for, run when a test says so. */ + const timers: (() => void)[] = []; + const state = { net: options.net ?? (() => new Response("not found", { status: 404 })) }; + const scope: Record = { addEventListener: (name: string, fn: (event: unknown) => void) => { listeners[name] = fn; }, - skipWaiting: () => did.push("skipWaiting"), + skipWaiting: async () => void did.push("skipWaiting"), + location: { origin: ORIGIN }, + navigator: { onLine: true }, + Notification: { permission: options.permission ?? "default" }, + crypto, + caches, + setTimeout: (fn: () => void) => { + timers.push(fn); + return timers.length; + }, + fetch: async (input: string | Request, init?: RequestInit) => { + const url = new URL(typeof input === "string" ? input : input.url, ORIGIN); + asked.push(`${(typeof input === "string" ? init?.method : input.method) ?? "GET"} ${url.pathname}${url.search}`); + return state.net(url, typeof input === "string" ? init : { method: input.method, headers: input.headers }); + }, + importScripts: (path: string) => { + new Function("self", readFileSync(join(PUBLIC, path.replace("/console/", "")), "utf8"))(scope); + }, registration: { - showNotification: async (title: string, options: Shown["options"]) => { - shown.push({ title, options }); + showNotification: async (title: string, opts: Shown["options"]) => { + shown.push({ title, options: opts }); }, }, clients: { @@ -36,19 +94,44 @@ function worker(windows: { url: string; canNavigate?: boolean }[] = []) { windows.map((w) => ({ url: w.url, focus: async () => did.push(`focus ${w.url}`), + postMessage: (message: unknown) => posted.push(message), ...(w.canNavigate === false ? {} : { navigate: async (to: string) => did.push(`navigate ${to}`) }), })), openWindow: async (to: string) => did.push(`open ${to}`), }, }; - new Function("self", readFileSync(join(import.meta.dir, "../public/sw.js"), "utf8"))(scope); + new Function("self", readFileSync(join(PUBLIC, "sw.js"), "utf8"))(scope); /** Deliver an event and wait for everything it asked the browser to wait for. */ const fire = async (name: string, event: Record) => { const waits: Promise[] = []; listeners[name]({ ...event, waitUntil: (p: Promise) => waits.push(p) }); await Promise.all(waits); }; - return { shown, did, fire, listeners }; + /** Ask for something the way a page does. Answers with what the + * worker gave, or undefined when it left the request alone. */ + const get = (path: string, init: { mode?: string; headers?: Record; method?: string } = {}) => { + const waits: Promise[] = []; + let given: Promise | undefined; + const request = new Request(ORIGIN + path, { method: init.method ?? "GET", headers: init.headers }); + // A request's mode cannot be set to "navigate" from a script: said beside it. + const event = { + request: new Proxy(request, { + get: (target, prop) => (prop === "mode" ? (init.mode ?? "cors") : Reflect.get(target, prop, target)), + }), + waitUntil: (p: Promise) => waits.push(p), + respondWith: (p: Promise) => { + given = p; + }, + }; + listeners.fetch(event); + return { given, settled: () => Promise.all(waits) }; + }; + /** Let the waits the worker is in run out. */ + const tick = async () => { + for (const fn of timers.splice(0)) fn(); + await new Promise((r) => setTimeout(r, 0)); + }; + return { shown, did, fire, listeners, caches, asked, posted, state, scope, get, tick }; } const pushed = (text: string | null) => ({ @@ -129,3 +212,376 @@ test("a new worker takes over at once, so a fix to it does not wait for every ta await w.fire("activate", {}); expect(w.did).toEqual(["skipWaiting", "claim"]); }); + +// ---- the app with no connection ------------------------------------------ +// +// Oracles: the worker file is run against a stand-in cache and network +// that record what is kept and what is asked. What the app must see in +// each case is written out by hand. That a real Chrome, taken offline, +// opens the app from these copies is checked in a browser (see the +// design record); here it is the rules. + +const json = (body: unknown, headers: Record = {}, status = 200) => + new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } }); +const down: Net = () => { + throw new TypeError("Failed to fetch"); +}; + +test("installed, the worker has the app's own files, and one it cannot fetch does not stop it", async () => { + const w = worker([], { + net: (url) => { + // One is refused, and one gets no answer at all. + if (url.pathname === "/console/app.css") return new Response("no", { status: 503 }); + if (url.pathname === "/icons/icon-512.png") throw new TypeError("Failed to fetch"); + return new Response(`the file ${url.pathname}`, { status: 200 }); + }, + }); + await w.fire("install", {}); + expect(w.caches.kept()).toEqual([ + "/console/", + "/console/app.js", + "/console/icon.svg", + "/console/outbox.js", + "/icons/icon-192.png", + "/manifest.webmanifest", + ]); + expect(w.did).toEqual(["skipWaiting"]); + // An older worker's copies are dropped when this one takes over; nobody else's are. + await w.caches.open("pm-console-v0"); + await w.caches.open("someone-elses"); + await w.fire("activate", {}); + expect(await w.caches.keys()).toEqual(["pm-console-v1", "someone-elses"]); +}); + +test("the app opens with no connection, from the page as it was last fetched", async () => { + const w = worker([], { net: () => new Response("the app, today", { status: 200 }) }); + // Any address of the app that is navigated to is the one page. + const first = w.get("/console/", { mode: "navigate" }); + expect(await (await first.given)?.text()).toBe("the app, today"); + await first.settled(); + w.state.net = down; + for (const path of ["/console/", "/console"]) { + const offline = w.get(path, { mode: "navigate" }); + expect(await (await offline.given)?.text()).toBe("the app, today"); + } + // Its files, the same. + w.state.net = () => new Response("code", { status: 200 }); + await w.get("/console/app.js").settled(); + w.state.net = down; + expect(await (await w.get("/console/app.js").given)?.text()).toBe("code"); + // With nothing kept, no connection is no answer: the browser says so. + const bare = worker([], { net: down }); + await expect(bare.get("/console/", { mode: "navigate" }).given).rejects.toThrow("Failed to fetch"); + // A way to the sign-in page is passed on, not answered from the copy: + // the owner has to be able to sign in. + w.state.net = () => new Response(null, { status: 302, headers: { location: "https://login.example/" } }); + expect((await w.get("/console/", { mode: "navigate" }).given)?.status).toBe(302); +}); + +test("what the app read is kept, and shown with no connection, marked as the device's own copy", async () => { + let n = 0; + const w = worker([], { net: () => json({ n: ++n }, { etag: '"a"', "x-as-of": "1000" }) }); + const live = await w.get("/console/api/doc/core").given; + expect(await live?.json()).toEqual({ n: 1 }); + // The network's answer goes to the app as it came: not marked. + expect(live?.headers.get("x-pm-offline")).toBeNull(); + w.state.net = down; + const kept = await w.get("/console/api/doc/core").given; + expect(await kept?.json()).toEqual({ n: 1 }); + expect(kept?.headers.get("x-pm-offline")).toBe("1"); + expect(Number(kept?.headers.get("x-pm-kept-at"))).toBeGreaterThan(0); + // What the app needs of the answer is still on it. + expect([kept?.headers.get("etag"), kept?.headers.get("x-as-of")]).toEqual(['"a"', "1000"]); + // Asked with "only if it changed", the copy is still given whole: the + // app may have nothing (it was reloaded). + const again = await w.get("/console/api/doc/core", { headers: { "if-none-match": '"a"' } }).given; + expect(await again?.json()).toEqual({ n: 1 }); + // Every read goes the same way: a screen's own, with its question, and health. + w.state.net = (url) => json({ path: url.pathname + url.search }); + for (const path of ["/console/api/roadmap?area=id", "/console/api/queue?status=blocked", "/console/health"]) { + await w.get(path).settled(); + } + w.state.net = down; + expect(await (await w.get("/console/api/roadmap?area=id").given)?.json()).toEqual({ + path: "/console/api/roadmap?area=id", + }); + expect(await (await w.get("/console/health").given)?.json()).toEqual({ path: "/console/health" }); + // Asked afresh, with no connection: the same copy, not "none". + expect(await (await w.get("/console/api/roadmap?area=id&fresh=1").given)?.json()).toEqual({ + path: "/console/api/roadmap?area=id", + }); + // One area's copy is not another's. + await expect(w.get("/console/api/roadmap?area=fleet").given).rejects.toThrow("Failed to fetch"); +}); + +test("an answer that says no is passed on as it is, never papered over with a copy", async () => { + const w = worker([], { net: () => json({ ok: 1 }) }); + await w.get("/console/api/agents").settled(); + for (const status of [401, 403, 404, 500, 503]) { + w.state.net = () => json({ error: "no" }, {}, status); + const res = await w.get("/console/api/agents").given; + expect([res?.status, res?.headers.get("x-pm-offline")]).toEqual([status, null]); + } + // And a refusal is not kept in place of the good copy. + w.state.net = down; + expect(await (await w.get("/console/api/agents").given)?.json()).toEqual({ ok: 1 }); +}); + +test("told its copy is still current, the worker notes when, so the copy is as fresh as it was last said to be", async () => { + const realNow = Date.now; + let now = 1_000_000; + Date.now = () => now; + try { + const w = worker([], { net: () => json({ v: 1 }, { "x-as-of": "900000" }) }); + await w.get("/console/api/doc/core").settled(); + now += 60_000; + w.state.net = () => new Response(null, { status: 304, headers: { "x-as-of": "1050000" } }); + const unchanged = w.get("/console/api/doc/core", { headers: { "if-none-match": '"a"' } }); + expect((await unchanged.given)?.status).toBe(304); + await unchanged.settled(); + w.state.net = down; + const kept = await w.get("/console/api/doc/core").given; + expect(await kept?.json()).toEqual({ v: 1 }); + expect([kept?.headers.get("x-pm-kept-at"), kept?.headers.get("x-as-of")]).toEqual(["1060000", "1050000"]); + } finally { + Date.now = realNow; + } +}); + +test("a network too slow to wait for is answered from the copy, and its answer kept when it comes", async () => { + const w = worker([], { net: () => json({ v: "old" }) }); + await w.get("/console/api/doc/ops").settled(); + let arrive: (res: Response) => void = () => {}; + w.state.net = () => + new Promise((resolve) => { + arrive = resolve; + }); + const slow = w.get("/console/api/doc/ops"); + await new Promise((r) => setTimeout(r, 0)); + await w.tick(); + const shown = await slow.given; + expect([await shown?.json(), shown?.headers.get("x-pm-offline")]).toEqual([{ v: "old" }, "1"]); + arrive(json({ v: "new" })); + await slow.settled(); + w.state.net = down; + expect(await (await w.get("/console/api/doc/ops").given)?.json()).toEqual({ v: "new" }); + // With no copy, the network is waited for however long it takes. + let late: (res: Response) => void = () => {}; + w.state.net = () => + new Promise((resolve) => { + late = resolve; + }); + const first = w.get("/console/api/bugs"); + await new Promise((r) => setTimeout(r, 0)); + await w.tick(); + late(json({ bugs: [] })); + expect(await (await first.given)?.json()).toEqual({ bugs: [] }); +}); + +test("what is not the app's reading is left alone", async () => { + const w = worker([], { net: () => json({}) }); + // Anything that changes something goes straight out. + expect(w.get("/console/api/act", { method: "POST" }).given).toBeUndefined(); + // Asked on purpose past the worker: is there a sign-in, is there a network. + expect(w.get("/console/api/me", { headers: { "x-pm-probe": "1" } }).given).toBeUndefined(); + // A download, the phone's own address, and other parts of the site. + for (const path of ["/console/pm-console.apk", "/console/device/summary", "/dashboard", "/cdn-cgi/access/logout"]) { + expect(w.get(path, { mode: "navigate" }).given).toBeUndefined(); + } + // Another site altogether. + const waits: Promise[] = []; + let given: unknown; + w.listeners.fetch({ + request: new Request("https://elsewhere.example/console/api/doc/core"), + waitUntil: (p: Promise) => waits.push(p), + respondWith: (p: unknown) => { + given = p; + }, + }); + expect(given).toBeUndefined(); + expect(w.asked).toEqual([]); +}); + +test("asked to forget, the worker drops what the app read and keeps the app itself", async () => { + const w = worker([], { net: (url) => json({ path: url.pathname }) }); + await w.fire("install", {}); + for (const path of ["/console/api/doc/core", "/console/api/roadmap?area=id", "/console/health"]) { + await w.get(path).settled(); + } + w.state.net = () => new Response(null, { status: 304 }); + await w.get("/console/api/doc/core").settled(); + expect(w.caches.kept().some((k) => k.startsWith("/console/__seen__/"))).toBe(true); + const told: unknown[] = []; + await w.fire("message", { data: { type: "forget" }, source: { postMessage: (m: unknown) => told.push(m) } }); + expect(w.caches.kept()).toEqual([ + "/console/", + "/console/app.css", + "/console/app.js", + "/console/icon.svg", + "/console/outbox.js", + "/icons/icon-192.png", + "/icons/icon-512.png", + "/manifest.webmanifest", + ]); + expect(told).toEqual([{ type: "forgotten" }]); + // Any other message is nothing to it. + await w.fire("message", { data: { type: "other" } }); + await w.fire("message", {}); +}); + +test("with the app closed, the worker sends what was kept when the connection is back, and says what became of it", async () => { + type Entry = { id: string; kind: string; args: Record; state: string; at: number; said: string }; + const acts: { kind: string; id: string }[] = []; + const net: Net = (url, init) => { + if (url.pathname !== "/console/api/act") return json({}, {}, 404); + const body = JSON.parse(String((init as { body?: string }).body)) as { kind: string; id: string }; + acts.push({ kind: body.kind, id: body.id }); + return body.kind === "issue.comment" ? json({ error: "no such issue" }, {}, 404) : json({ ok: true, result: {} }); + }; + const w = worker([], { net, permission: "granted" }); + const outbox = w.scope.PMOutbox as { + memoryStore: () => { all: () => Promise; put: (e: Entry) => Promise }; + make: (kind: string, args: unknown, now: number) => Entry; + idbStore: unknown; + }; + const store = outbox.memoryStore(); + outbox.idbStore = () => store; + const now = Date.now(); + await store.put(outbox.make("ask.send", { text: "Typed in a tunnel" }, now - 3_000)); + await store.put(outbox.make("issue.comment", { issue: 13, text: "x" }, now - 2_000)); + // A merge asked for an hour ago is not sent unasked. + await store.put(outbox.make("pr.merge", { pr: 55 }, now - 3_600_000)); + await w.fire("sync", { tag: "pm-outbox" }); + expect(acts.map((a) => a.kind)).toEqual(["ask.send", "issue.comment"]); + expect((await store.all()).map((e) => [e.kind, e.state]).sort()).toEqual([ + ["ask.send", "done"], + ["issue.comment", "failed"], + ["pr.merge", "stale"], + ]); + // Nobody is looking: it says so, and a tap opens the list. + expect(w.shown).toEqual([ + { + title: "What you did offline", + options: { + body: "1 sent, 1 could not be done, 1 kept back for you to look at.", + tag: "outbox", + icon: "/icons/icon-192.png", + badge: "/icons/icon-192.png", + data: { url: "/console/#more/device" }, + }, + }, + ]); + // With the app open, the app is told and shows it itself. + const open = worker([{ url: `${ORIGIN}/console/#now` }], { net, permission: "granted" }); + const opened = open.scope.PMOutbox as typeof outbox; + const second = opened.memoryStore(); + opened.idbStore = () => second; + await second.put(opened.make("ask.send", { text: "Another" }, Date.now())); + await open.fire("sync", { tag: "pm-outbox" }); + expect(open.shown).toEqual([]); + expect(open.posted).toEqual([{ type: "outbox", changed: [{ state: "done" }] }]); + // Without leave to notify, nothing is shown; nothing is lost either. + const quiet = worker([], { net }); + const third = (quiet.scope.PMOutbox as typeof outbox).memoryStore(); + (quiet.scope.PMOutbox as typeof outbox).idbStore = () => third; + await third.put((quiet.scope.PMOutbox as typeof outbox).make("ask.send", { text: "Quiet" }, Date.now())); + await quiet.fire("sync", { tag: "pm-outbox" }); + expect(quiet.shown).toEqual([]); + expect((await third.all()).map((e) => e.state)).toEqual(["done"]); + // A wake under another name is not for this: what waits stays waiting. + await store.put(outbox.make("ask.send", { text: "Not for that wake" }, Date.now())); + const before = acts.length; + await w.fire("sync", { tag: "something-else" }); + expect(acts.length).toBe(before); + expect((await store.all()).filter((e) => e.state === "waiting")).toHaveLength(1); +}); + +test("still no connection when the browser wakes the worker: it says so, and the browser tries again later", async () => { + const w = worker([], { net: down }); + const outbox = w.scope.PMOutbox as { + memoryStore: () => { all: () => Promise<{ state: string }[]>; put: (e: unknown) => Promise }; + make: (kind: string, args: unknown, now: number) => unknown; + idbStore: unknown; + }; + const store = outbox.memoryStore(); + outbox.idbStore = () => store; + await store.put(outbox.make("ask.send", { text: "Still in the tunnel" }, Date.now())); + await expect(w.fire("sync", { tag: "pm-outbox" })).rejects.toThrow("still offline"); + expect((await store.all()).map((e) => e.state)).toEqual(["waiting"]); + expect(w.shown).toEqual([]); +}); + +test("the sign-in ran out while the app was closed: nothing is sent, and the owner is told to sign in", async () => { + // What a browser gives a worker that was sent towards a sign-in page. + const towardsSignIn = () => ({ type: "opaqueredirect", status: 0, json: async () => null }) as unknown as Response; + const w = worker([], { net: towardsSignIn, permission: "granted" }); + const outbox = w.scope.PMOutbox as { + memoryStore: () => { all: () => Promise<{ state: string; note: string }[]>; put: (e: unknown) => Promise }; + make: (kind: string, args: unknown, now: number) => unknown; + idbStore: unknown; + }; + const store = outbox.memoryStore(); + outbox.idbStore = () => store; + await store.put(outbox.make("ask.send", { text: "one" }, Date.now() - 2)); + await store.put(outbox.make("ask.send", { text: "two" }, Date.now() - 1)); + // It is not a failure of the connection: the browser is not asked to call again. + await w.fire("sync", { tag: "pm-outbox" }); + expect((await store.all()).map((e) => [e.state, e.note])).toEqual([ + ["waiting", "Sign in again to send this."], + ["waiting", ""], + ]); + expect(w.shown).toEqual([ + { + title: "Sign in to send what you did offline", + options: { + body: "2 things are kept on this device until you do.", + tag: "outbox", + icon: "/icons/icon-192.png", + badge: "/icons/icon-192.png", + data: { url: "/console/#more/device" }, + }, + }, + ]); + // With the app open it says so itself. + const open = worker([{ url: `${ORIGIN}/console/` }], { net: towardsSignIn, permission: "granted" }); + const other = (open.scope.PMOutbox as typeof outbox).memoryStore(); + (open.scope.PMOutbox as typeof outbox).idbStore = () => other; + await other.put((open.scope.PMOutbox as typeof outbox).make("ask.send", { text: "one" }, Date.now())); + await open.fire("sync", { tag: "pm-outbox" }); + expect(open.shown).toEqual([]); +}); + +test("the app's page is already sending: the worker leaves it to the page", async () => { + const sent: string[] = []; + const w = worker([], { + net: (url) => { + sent.push(url.pathname); + return json({ ok: true, result: {} }); + }, + }); + const outbox = w.scope.PMOutbox as { + memoryStore: () => { all: () => Promise<{ state: string }[]>; put: (e: unknown) => Promise }; + make: (kind: string, args: unknown, now: number) => unknown; + idbStore: unknown; + }; + const store = outbox.memoryStore(); + outbox.idbStore = () => store; + await store.put(outbox.make("ask.send", { text: "the page has this" }, Date.now())); + // The browser's lock, as it answers when someone else holds it, and when nobody does. + const asked: unknown[] = []; + const lock = { held: true }; + (w.scope.navigator as Record).locks = { + request: async (name: string, options: unknown, work: (lock: unknown) => unknown) => { + asked.push([name, options]); + return work(lock.held ? null : { name }); + }, + }; + await w.fire("sync", { tag: "pm-outbox" }); + expect(sent).toEqual([]); + expect((await store.all()).map((e) => e.state)).toEqual(["waiting"]); + expect(asked).toEqual([["pm-outbox", { ifAvailable: true }]]); + lock.held = false; + await w.fire("sync", { tag: "pm-outbox" }); + expect(sent).toEqual(["/console/api/act"]); + expect((await store.all()).map((e) => e.state)).toEqual(["done"]); +}); diff --git a/pm-stack/console/test/work.test.ts b/pm-stack/console/test/work.test.ts index 48d4853670..c1e59df215 100644 --- a/pm-stack/console/test/work.test.ts +++ b/pm-stack/console/test/work.test.ts @@ -12,8 +12,10 @@ import { gunzipSync } from "node:zlib"; import { actions, perform } from "../src/actions.ts"; import { readConfig } from "../src/config.ts"; import { Docs, Stamped } from "../src/docs.ts"; +import { Named } from "../src/named.ts"; import { type Fetch, OpError, Ops, type Run } from "../src/ops.ts"; import { type Deps, handle, loaders } from "../src/server.ts"; +import { memoryStore } from "../src/store.ts"; import { promptPacket, Work } from "../src/work.ts"; import { asThePlatformFetch } from "./support.ts"; @@ -1007,6 +1009,76 @@ describe("the interface's endpoints", () => { expect((await handle(get("/console/api/doc/core"), deps(401).d)).status).toBe(401); }); + test("with no edge in front of it, a host does an action once under the name a device gave it", async () => { + const { d, w } = deps(); + d.named = new Named(memoryStore()); + const id = "0e000000-0000-4000-8000-000000000001"; + const moves = () => w.sqls.flat().filter((s) => s.sql.startsWith("UPDATE tasks SET priority")).length; + const first = await handle( + post("/console/api/act", { kind: "task.move", args: { task: 21016, to: "first" }, id }), + d, + ); + expect(await first.json()).toEqual({ ok: true, result: { task: 21016, priority: 10 } }); + const second = await handle( + post("/console/api/act", { kind: "task.move", args: { task: 21016, to: "first" }, id }), + d, + ); + expect(await second.json()).toEqual({ ok: true, result: { task: 21016, priority: 10 }, again: true }); + expect(moves()).toBe(1); + // Its record of what was done carries the name, once. + const core = await (await handle(get("/console/api/doc/core"), d)).json(); + expect(core.acts.map((a: { id: string; status: string }) => [a.id, a.status])).toEqual([[id, "done"]]); + // With nowhere to write names down, an action is done as often as it is asked: as it always was. + const bare = deps(); + await handle(post("/console/api/act", { kind: "task.move", args: { task: 21016, to: "first" }, id }), bare.d); + await handle(post("/console/api/act", { kind: "task.move", args: { task: 21016, to: "first" }, id }), bare.d); + expect(bare.w.sqls.flat().filter((s) => s.sql.startsWith("UPDATE tasks SET priority")).length).toBe(2); + }); + + test("the record of names: what each state means, how many are kept, and a record that cannot be read", async () => { + const store = memoryStore(); + const named = new Named(store); + expect(await named.seen("a")).toBeNull(); + await named.begin("a"); + expect(await named.seen("a")).toEqual({ state: "running" }); + await named.end("a", { ok: true, result: { n: 1 } }); + expect(await named.seen("a")).toEqual({ state: "done", fate: { ok: true, result: { n: 1 } } }); + await named.begin("b"); + await named.end("b", { ok: false, error: "no", status: 404 }); + expect(await named.seen("b")).toEqual({ state: "done", fate: { ok: false, error: "no", status: 404 } }); + // Started, and the process stopped: another one, reading the same + // record, knows it was started and not how it ended. + await named.begin("c"); + const after = new Named(store); + expect(await after.seen("c")).toEqual({ state: "lost" }); + expect(await after.seen("a")).toEqual({ state: "done", fate: { ok: true, result: { n: 1 } } }); + expect([named.isRunning("c"), after.isRunning("c")]).toEqual([true, false]); + // An outcome that cannot be written still frees the name in this process. + const failing = new Named({ + read: async () => null, + write: async (text) => { + if (text.includes('"ok"')) throw new Error("disk full"); + }, + }); + await failing.begin("d"); + await expect(failing.end("d", { ok: true })).rejects.toThrow("disk full"); + expect(failing.isRunning("d")).toBe(false); + // Three hundred names are kept: the oldest is forgotten first, and + // one seen again counts as new. + const many = new Named(memoryStore()); + for (let i = 0; i < 300; i++) await many.record(`n${i}`, { ok: true }); + await many.record("n0", { ok: true }); + await many.record("n300", { ok: true }); + expect([await many.get("n1"), await many.get("n0"), await many.get("n2")]).toEqual([ + undefined, + { ok: true }, + { ok: true }, + ]); + // A record that cannot be read is an empty one, not a crash. + const broken = new Named({ read: async () => "not json", write: async () => {} }); + expect(await broken.seen("x")).toBeNull(); + }); + test("an action runs, is recorded without the owner's words, and shows in the state", async () => { const { d, w, audited } = deps(); // What an action changes is read again before the answer goes back, From a0b740f5baca4f058601cf3c75a7ee7038e2c29e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 06:57:35 -0600 Subject: [PATCH 2/6] fix(pm-console): send each action under the lock a flush takes While an action was written down and not yet answered, a send of what is waiting (the page's own, every twenty seconds, or the service worker's) could take it for something left waiting and send it too. The platform would still have done it once, under its name; the owner would have been told twice. An action is now sent under the same lock. Also: "Forget what it last saw" left its button disabled in a browser with no worker. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- pm-stack/console/public/app.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 7b048ef720..63900ab0a5 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -331,6 +331,17 @@ function flushOutbox() { async function submit(kind, args) { if (!Outbox) return { state: "refused", note: "This page cannot send that." }; const entry = Outbox.make(kind, args, Date.now()); + // Under the lock a send of what is waiting takes (here or in the + // service worker): while this is written down and not yet answered, + // nothing else may take it for something left waiting and send it too. + // (If one did, the platform would still do it once; the owner would + // be told twice.) + const work = () => submitNow(entry); + return navigator.locks?.request ? navigator.locks.request("pm-outbox", work) : work(); +} + +async function submitNow(entry) { + const { kind } = entry; // What needs a connection by its nature is not written down. let keeps = Outbox.rule(kind) !== "now" && outbox !== null; if (keeps) { @@ -2022,10 +2033,10 @@ async function viewDevice() { const forget = async (e) => { e.target.disabled = true; const worker = (await navigator.serviceWorker?.ready.catch(() => null))?.active; + e.target.disabled = false; if (!worker) return toast("Nothing is kept: this browser has not set the app up to work offline.", true); worker.postMessage({ type: "forget" }); toast("Forgotten. It keeps again from the next thing you look at."); - e.target.disabled = false; }; // Before a flight: read every screen once, so the device has a copy // of each. One at a time, and unhurried: some of it is searched for. From e4ab229e64dc2d8db256612a83502b8eb77cf193 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:36:58 -0600 Subject: [PATCH 3/6] fix(pm-console): one arrival per name, actions in the order done, a worker that asks again Review of the offline work found six faults; looking at them found more of the same kinds. Once under a name: - A name is taken first, with no waiting in between, and what is known of it is read after (Named.take, known), on the laptop and at the edge. Two arrivals under one name at the same moment used to both look, both find nothing, and both do it. - A held action being done on the laptop is marked as being done, so a device sending it again meanwhile is told to wait, not that the laptop restarted. - The laptop's link had two methods called take; the second silently replaced the first. Renamed (the console is not type-checked yet). - The record of names is read once however many ask together, and written one write at a time. In the order it was done: - Something done now is written down and sent through the same oldest-first pass as what is waiting (sendInOrder), not ahead of it. - Two about the same thing keep their order: while the earlier one has not been taken, the later one waits, on the device and in what the edge holds for a machine (subject, subjectOf). - Each entry is read again just before it is sent, so "do not send" during a send is honoured. The worker: - Asks to be woken again while anything still waits to be sent, and on the browser's last call says what is left. - Keeps copies on a best effort: a full device, or a browser with no cache at all, still gets the network's answer, and the worker still installs. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- ...rchitecture_pm_platform_cloudflare_core.md | 65 ++++ pm-stack/console/README.md | 16 +- pm-stack/console/edge/README.md | 12 +- pm-stack/console/edge/src/edge.ts | 54 ++- pm-stack/console/public/app.js | 85 +++-- pm-stack/console/public/outbox.js | 104 +++++- pm-stack/console/public/sw.js | 102 ++++-- pm-stack/console/src/edge-proto.ts | 38 +++ pm-stack/console/src/named.ts | 70 +++- pm-stack/console/src/server.ts | 98 +++--- pm-stack/console/src/sync.ts | 77 +++-- pm-stack/console/test/app.test.ts | 50 +++ pm-stack/console/test/edge.test.ts | 121 ++++++- pm-stack/console/test/outbox.test.ts | 317 +++++++++++++++++- pm-stack/console/test/sw.test.ts | 181 +++++++++- pm-stack/console/test/work.test.ts | 106 ++++++ 16 files changed, 1314 insertions(+), 182 deletions(-) diff --git a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md index 4b344626d2..60ef6fc600 100644 --- a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md +++ b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md @@ -435,3 +435,68 @@ this site in Chrome, so nothing in it changed). Not done: copies are not encrypted on the device beyond what the device does itself; a screen never visited has no copy until it is visited or "keep a copy of every screen" is pressed. + +## 2026-11-23T15:40Z Update: step 4 after review + +Review of the offline work found six real faults, and looking at them +found three more of the same kinds. All are fixed in the same change. + +- **A name could be done twice by two arrivals at the same moment.** + The laptop looked a name up, then waited for the audit's write, and + only then marked it as being done: two arrivals could both look and + both do it. A name is now taken first, with no waiting in between + (`Named.take`), and what is known of it is read after, on the laptop + and at the edge alike; the second arrival is told it is being done, + and asks again. The laptop's record of names is read once however + many ask together, and written one write at a time. +- **A held action being done on the laptop looked "lost" to a retry.** + Doing a held action wrote "started" without marking the name as being + done, so a device sending it again meanwhile was told the laptop had + restarted, and offered a retry under a new name. Held actions now go + through the same taking and giving back as any other. +- **Something done now could overtake something older.** A new action + was sent by itself, ahead of what was waiting on the device; the + older one, sent later, undid it (a rank changed twice ended as the + first). A new action is now written down and sent through the same + oldest-first pass as everything else (`sendInOrder`). +- **Order is kept per thing, to the end.** Found while fixing the last: + an older change that nothing could take just now (503) or that was + still being done (409) let a newer change about the same thing go + first. Each action says what it is about (`subject` on the device, + `subjectOf` on the platform; a test holds them together); a later one + about the same thing waits behind an earlier one that has not been + taken, on the device and in what the edge holds for a machine. What + is about something else is not held up. +- **"Do not send" during a send was ignored**, and so was an entry + another tab or the worker had dealt with meanwhile: each entry is now + read again just before it is sent. +- **The worker gave up with things still waiting.** A 503 or a + "being done" left an entry waiting but ended the browser's wake as a + success, so nothing called again. The worker now asks to be woken + again while anything waits to be sent, and on the browser's last call + says what still waits. +- **A full device broke reads.** A refused write to the cache failed + the read it belonged to. Keeping copies is now on a best effort; and + with no cache at all (a browser that gives the site no storage) the + worker installs and answers as if it kept nothing. + +Checked: 339 tests under bun, the keeper's 25. 40 planted faults in +the new code, all caught (two more were planted and found to change +nothing: each is behind a second guard). In a real Chrome against both +demos: the offline flow, light +and dark; the worker woken with the app closed; an older waiting rank +and a new one leave the device in order and are done in order (and with +the old direct send planted, that check fails); axe-core over 20 +screens, the dialogs and the toasts: no violations. The Worker in its +real runtime passes its own checks. + +Found on the way: the console's TypeScript is never type-checked. A +method added to the laptop's link had the name of one already there, +and the second silently replaced the first; the tests passed for the +wrong reason until a later change exposed it. A type check finds it at +once, and 53 smaller complaints across the console, none of them a +fault. Adding the check to CI is the next change. + +Not done, and filed as #13398: an older action held for a machine is +not ordered against a newer one about the same thing that the edge +does itself. diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index cebdbc2247..6326d5c762 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -190,6 +190,8 @@ the Android app alike (which is the same site in Chrome). screen's own read, each under the address it was asked for. The network is always asked first; a copy is shown only when the network gives no answer (or is too slow to wait for), and is marked as a copy. + Keeping copies is on a best effort: a device with no room, or a + browser that gives the site no cache, still gets the network's answer. An answer that says no (a refusal, a way to the sign-in page, an error) is passed on as it is and never papered over. The corner of the header then says `offline` and how old the state is, and a line @@ -204,7 +206,19 @@ the Android app alike (which is the same site in Chrome). where the browser has it). The platform does an action once under its name however often it arrives, so sending again after an answer that never came is safe: Cloudflare keeps the names it did (a week, three - hundred), and a machine keeps its own (`src/named.ts`). + hundred), and a machine keeps its own (`src/named.ts`). A name is + taken by one arrival at a time: a second one while the first is still + being done is told so, and asks again. +- **In the order it was done.** Something done now goes behind whatever + is already waiting, oldest first, and is not sent ahead of it. Two + about the same thing (an issue ranked twice, a task moved twice) keep + their order to the end: while the earlier one has not been taken, the + later one waits, on the device and, for what a machine does late, on + the platform too. What is about something else is not held up by it. +- **Nothing waits unseen.** Where the browser wakes the worker with the + app closed and something still could not be taken, the worker asks to + be woken again; on the browser's last call it says what still waits, + and opening the app sends it. - **Not everything is sent unasked.** What the owner says or decides (a prompt, a reply, a rank, a note, a bug, an answer) does not go stale and goes whenever it can. A merge, a deploy, a cancel, an diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index c54333f353..78c10bb2a3 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -341,6 +341,16 @@ open nothing. that was put away before it ended is said to be unknown, once, and not retried. What goes to the laptop goes under the same name, and the laptop keeps the record. Held twice under one name, an action - waits once. + waits once. A name is taken by one arrival at a time, here and on the + laptop, before anything else is waited for: of two that arrive + together one does it and the other is told it is being done. +- What is done late is done in the order the owner did it. An action + that may be held goes behind an earlier one about the same thing (the + same issue, task, reference or set of questions) that a machine has + not taken yet, even when the machine can be reached again: sent + straight on it would be done first, and the older one would undo it. + What is about something else goes straight on. Not covered (#13398): + an older action held for a machine and a newer one about the same + thing that the edge does itself. - The storage is one Durable Object. A section larger than one stored value is kept in pieces. diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index dd551c7ec7..0405811513 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -49,6 +49,7 @@ import { keyId, type PublicKey, publicKey, + subjectOf, SYNC_SKEW_MS, type SyncRequest, type SyncResponse, @@ -1546,6 +1547,16 @@ export class Edge { if (!(error instanceof HandOver)) throw error; } } + // What may be done late goes behind anything already waiting + // for a machine that is about the same thing. Sent straight to + // a machine that has just come back, it would be done before + // the older one, which would undo it when its turn came. + if (HOLDABLE.has(kind)) { + const about = subjectOf(kind, args as Record); + if (about !== null && (await this.heldList()).some((h) => subjectOf(h.kind, h.args) === about)) { + return this.keep({ id: id ?? crypto.randomUUID(), kind, args, who: by }); + } + } // The host's to do. The stateless part relays it, and if the // host cannot be reached comes back to have it held. // It goes under the device's name for it, or one given here, @@ -1585,19 +1596,22 @@ export class Edge { * same name. */ private async once(id: string | null, kind: string, work: () => Promise): Promise { if (id === null) return work(); - const key = `a:${id}`; - const before = ((await this.kv.get(key)) as Acted | undefined) ?? null; - if (before?.state === "done") return json({ ...before.body, again: true }, before.status ?? 200); - if (before?.state === "running") { - if (this.doing.has(id)) return json({ error: "This is still being done.", running: true }, 409); - // Started, and this object was put away before it ended. Whether - // it happened is not known, and doing it again could do it twice. - const body = { error: "Cloudflare restarted while doing this; check whether it happened before trying again." }; - await this.kv.put(key, { at: this.now(), kind, state: "done", status: 502, body } satisfies Acted); - return json({ ...body, again: true }, 502); - } + // Taken for doing here and now, before anything is waited for: of + // two arrivals under one name, only one can take it. + if (this.doing.has(id)) return json({ error: "This is still being done.", running: true }, 409); this.doing.add(id); + const key = `a:${id}`; try { + const before = ((await this.kv.get(key)) as Acted | undefined) ?? null; + if (before?.state === "done") return json({ ...before.body, again: true }, before.status ?? 200); + if (before?.state === "running") { + // Started, and not by this object (it would hold the name): + // one that was put away before it ended. Whether it happened + // is not known, and doing it again could do it twice. + const body = { error: "Cloudflare restarted while doing this; check whether it happened before trying again." }; + await this.kv.put(key, { at: this.now(), kind, state: "done", status: 502, body } satisfies Acted); + return json({ ...body, again: true }, 502); + } await this.kv.put(key, { at: this.now(), kind, state: "running" } satisfies Acted); await this.actedIndex(id); let res: Response; @@ -1674,12 +1688,18 @@ export class Edge { /** The host could not be reached: keep the action for it, if it is one * that may be done late. */ private async hold(req: Request): Promise { - const body = (await req.json().catch(() => null)) as { - id?: unknown; - kind?: unknown; - args?: unknown; - who?: unknown; - } | null; + return this.keep( + (await req.json().catch(() => null)) as { + id?: unknown; + kind?: unknown; + args?: unknown; + who?: unknown; + } | null, + ); + } + + /** Keep an action for a machine, at the back of what already waits. */ + private async keep(body: { id?: unknown; kind?: unknown; args?: unknown; who?: unknown } | null): Promise { const kind = typeof body?.kind === "string" ? body.kind : ""; const args = body?.args; if (!HOLDABLE.has(kind) || args === null || typeof args !== "object" || Array.isArray(args)) { diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 63900ab0a5..a40c1480d4 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -341,43 +341,55 @@ async function submit(kind, args) { } async function submitNow(entry) { - const { kind } = entry; - // What needs a connection by its nature is not written down. - let keeps = Outbox.rule(kind) !== "now" && outbox !== null; - if (keeps) { - try { - await outbox.put(entry); - } catch { - keeps = false; - } - } - const answer = await Outbox.httpSend(entry); - const out = Outbox.classify(answer); - const end = async (state, more = {}) => { - if (keeps) await outbox.put({ ...entry, ...more, state, tries: 1, triedAt: Date.now(), endedAt: Date.now() }).catch(() => {}); + // Sent by itself, behind nothing: what needs a connection by its + // nature (it is not written down), or everything, in a browser that + // will not let this page keep anything. + const direct = async () => { + const answer = await Outbox.httpSend(entry); + const out = Outbox.classify(answer); + if (out.state === "done") return { state: "done", result: out.result }; + if (out.state === "held") return { state: "held" }; + if (out.state === "failed") return { state: "failed", note: out.note }; + if (out.signin) signedOut = true; + return { state: "refused", note: answer.network ? "This needs a connection." : out.signin ? NO_SIGNIN : out.note }; }; - if (out.state === "done") { - await end("done", { result: out.result }); - return { state: "done", result: out.result }; - } - if (out.state === "held") { - await end("held", { note: out.note }); - return { state: "held" }; + if (Outbox.rule(entry.kind) === "now" || outbox === null) return direct(); + try { + await outbox.put(entry); + } catch { + return direct(); } - if (out.state === "failed") { - // Said at once, to the owner's face: nothing to keep of it. - if (keeps) await outbox.remove(entry.id).catch(() => {}); - return { state: "failed", note: out.note }; + // It goes behind whatever is already waiting, in the order things + // were done (outbox.js says why). + let did; + try { + did = await Outbox.sendInOrder(outbox, entry.id, (e) => Outbox.httpSend(e)); + } catch { + // It is written down, and what became of it could not be read back: + // it is treated as waiting, which it is at worst, and sent again + // under its name. + did = { entry: { state: "waiting", note: "" }, others: [], signin: false, offline: false }; } + if (did.signin) signedOut = true; + const out = sentSaid(did, entry.id); // Not taken: no connection, no sign-in, or nothing to take it just now. - if (out.signin) signedOut = true; - if (!keeps) { - const note = answer.network ? "This needs a connection." : out.signin ? NO_SIGNIN : out.note; - return { state: "refused", note }; - } - if (out.note) await outbox.put({ ...entry, note: out.note, tries: 1, triedAt: Date.now() }).catch(() => {}); - sendWhenConnected(); - return { state: "kept", id: entry.id, note: out.signin ? "Kept on this device. Sign in again to send it." : out.note ? `Kept on this device: ${out.note}` : KEPT_NOTE }; + if (out.state === "kept") sendWhenConnected(); + return out; +} + +/** What to tell whoever did something, from what became of it when it + * was sent in its turn. `did.entry` is the entry as it now stands. */ +export function sentSaid(did, id) { + const now = did.entry; + if (!now) return { state: "refused", note: "It was taken back before it was sent." }; + if (now.state === "done") return { state: "done", result: now.result ?? null, others: did.others }; + if (now.state === "held") return { state: "held", others: did.others }; + if (now.state === "failed") return { state: "failed", note: now.note }; + return { + state: "kept", + id, + note: did.signin ? "Kept on this device. Sign in again to send it." : now.note ? `Kept on this device: ${now.note}` : KEPT_NOTE, + }; } /** Take back something kept that has not been sent. */ @@ -398,13 +410,16 @@ async function act(kind, args, done, button) { if (button) button.disabled = true; const out = await submit(kind, args); await readKept(); + // Older things that went in the same pass are said with it. + const older = out.others?.length ? flushSaid(out.others) : ""; + const also = older ? ` ${older}` : ""; if (out.state === "done") { - toast(typeof done === "function" ? done(out.result) : done); + toast((typeof done === "function" ? done(out.result) : done) + also); await refresh(true); return out.result ?? { done: true }; } if (out.state === "held") { - toast(HELD_NOTE); + toast(HELD_NOTE + also); await refresh(true); return { held: true }; } diff --git a/pm-stack/console/public/outbox.js b/pm-stack/console/public/outbox.js index 2f6cca99ce..4f01ab80dc 100644 --- a/pm-stack/console/public/outbox.js +++ b/pm-stack/console/public/outbox.js @@ -50,6 +50,47 @@ * a secret that is not written down). What is not known is "now". */ const rule = (kind) => (LATE.has(kind) ? "late" : TIMELY.has(kind) ? "timely" : "now"); + /** What an action is about, where the order of two matters: a rank + * set twice, a task moved twice. Two about one thing are sent in the + * order they were done, and a later one is not sent while an earlier + * one still waits. Null: it stands alone (a new prompt, a message). + * (The platform keeps the same order for what it holds for a + * machine: subjectOf in src/edge-proto.ts says the same.) */ + function subject(kind, args = {}) { + const a = args ?? {}; + const of = (what, value) => { + const said = typeof value === "string" || typeof value === "number" ? String(value) : ""; + return said === "" ? null : `${what}:${said}`; + }; + switch (kind) { + case "ask.reply": + case "ask.close": + case "issue.comment": + case "issue.rank": + return of("issue", a.issue); + case "task.move": + case "task.cancel": + case "task.unblock": + return of("task", a.task); + case "hands.done": + case "need.comment": + return of("ref", a.ref); + case "question.answer": + case "question.defer": + case "questions.accept": + return of("questions", a.set); + case "pr.merge": + return of("pr", a.pr); + case "unit.act": + return of("unit", a.unit); + default: + return null; + } + } + /** Said of an entry that was not sent because an earlier one about + * the same thing has not been taken yet. */ + const BEHIND_NOTE = "It goes after an earlier one about the same thing, which has not been taken yet."; + const short = (text, n = 60) => { const t = String(text ?? "") .replace(/\s+/g, " ") @@ -176,8 +217,8 @@ /** Send what is due, oldest first. `store` keeps the entries (all, * put, remove); `send(entry)` makes one try and says what came back. - * Returns what changed. One flush at a time per store: a second call - * while one runs joins it. */ + * Returns what changed, and which entries this pass looked at. One + * flush at a time per store: a second call while one runs joins it. */ const running = new WeakMap(); function flush(store, send, now = () => Date.now()) { const already = running.get(store); @@ -187,8 +228,17 @@ let signin = false; let offline = false; const entries = (await store.all()).sort((a, b) => a.at - b.at); - for (const entry of entries) { - if (entry.state !== "waiting") continue; + // What an earlier entry in this pass is about, when it still + // waits after its try: a later one about the same thing is not + // sent ahead of it. + const stillWaits = new Set(); + for (const listed of entries) { + if (listed.state !== "waiting") continue; + // As it stands now, not as it stood when this began: one taken + // back meanwhile ("do not send") is not sent, and one already + // dealt with is not dealt with again. + const entry = (await store.all()).find((e) => e.id === listed.id); + if (!entry || entry.state !== "waiting") continue; if (!due(entry, now())) { // Too old to send unasked: kept, and said to be. const stale = { ...entry, state: "stale", note: "Not sent: it was a while ago, and this may have changed." }; @@ -196,6 +246,15 @@ changed.push(stale); continue; } + const about = subject(entry.kind, entry.args); + if (about !== null && stillWaits.has(about)) { + if (entry.note !== BEHIND_NOTE) { + const behind = { ...entry, note: BEHIND_NOTE }; + await store.put(behind); + changed.push(behind); + } + continue; + } let answer; try { answer = await send(entry); @@ -203,6 +262,7 @@ answer = { network: true }; } const { state, note, result, stop, signin: needs } = classify(answer); + if (state === "waiting" && about !== null) stillWaits.add(about); const next = { ...entry, state, @@ -221,8 +281,17 @@ if (answer.network) offline = true; if (stop) break; } - for (const id of expired(await store.all(), now())) await store.remove(id); - return { changed, signin, offline }; + const left = await store.all(); + for (const id of expired(left, now())) await store.remove(id); + // How many still wait to be sent: by their own doing (no answer, + // nothing to take them just now), not for the owner to look at. + return { + changed, + signin, + offline, + waiting: left.filter((e) => e.state === "waiting").length, + looked: entries.map((e) => e.id), + }; })(); running.set(store, work); const clear = () => running.delete(store); @@ -230,6 +299,27 @@ return work; } + /** Send an entry that has just been written down, behind whatever is + * already waiting, in the order things were done. Sent ahead of an + * older one, the older would undo it when its turn came: a rank + * changed twice would end as the first. Says what became of it (the + * entry as it now stands, or null if it was taken back meanwhile), + * and what else went in the same pass. One that failed is not kept: + * the caller says so to the owner's face. */ + async function sendInOrder(store, id, send, now = () => Date.now()) { + const mine = async () => (await store.all()).find((e) => e.id === id) ?? null; + let out = await flush(store, send, now); + let entry = await mine(); + // A send already under way was joined, and it began before this + // was written down: once more, for this one. + if (entry?.state === "waiting" && !out.looked.includes(id) && !out.offline && !out.signin) { + out = await flush(store, send, now); + entry = await mine(); + } + if (entry?.state === "failed") await store.remove(id); + return { entry, others: out.changed.filter((e) => e.id !== id), signin: out.signin, offline: out.offline }; + } + /** Entries held for a machine learn how they came out from the * platform's own record of what was done, which carries their names. */ async function settle(store, acts, now = () => Date.now()) { @@ -326,6 +416,7 @@ root.PMOutbox = { TIMELY_MS, rule, + subject, sayOf, make, classify, @@ -333,6 +424,7 @@ summary, expired, flush, + sendInOrder, settle, httpSend, idbStore, diff --git a/pm-stack/console/public/sw.js b/pm-stack/console/public/sw.js index c16d1a4ec7..b74261f0a2 100644 --- a/pm-stack/console/public/sw.js +++ b/pm-stack/console/public/sw.js @@ -26,10 +26,17 @@ const READ_WAIT_MS = 8_000; self.addEventListener("install", (event) => { event.waitUntil( (async () => { - const cache = await self.caches.open(KEPT); - // Each by itself: one that cannot be fetched (not signed in, say) - // does not stop the others, or the worker. - await Promise.all([...FILES, ...EXTRAS].map((path) => keep(cache, path).catch(() => {}))); + // Keeping the files is on a best effort. With no cache to be had + // the worker is installed all the same, for what else it does: + // notifications, and sending what was done offline. + try { + const cache = await self.caches.open(KEPT); + // Each by itself: one that cannot be fetched (not signed in, + // say) does not stop the others, or the worker. + await Promise.all([...FILES, ...EXTRAS].map((path) => keep(cache, path).catch(() => {}))); + } catch { + // Nothing is kept this time. + } await self.skipWaiting(); })(), ); @@ -38,8 +45,12 @@ self.addEventListener("install", (event) => { self.addEventListener("activate", (event) => { event.waitUntil( (async () => { - for (const name of await self.caches.keys()) { - if (name.startsWith("pm-console-") && name !== KEPT) await self.caches.delete(name); + try { + for (const name of await self.caches.keys()) { + if (name.startsWith("pm-console-") && name !== KEPT) await self.caches.delete(name); + } + } catch { + // An older copy that cannot be cleared is only space. } await self.clients.claim(); })(), @@ -97,35 +108,50 @@ const after = (ms) => new Promise((resolve) => self.setTimeout(() => resolve(nul * and the keeping of the network's answer, which may come after. */ function answer(request, kind) { const key = keyOf(new URL(request.url), kind); - const opened = self.caches.open(KEPT); + // With no cache to be had (a browser that refuses this site any + // storage) nothing is kept and nothing kept is shown: the network + // answers as if this worker were not here. + const opened = self.caches.open(KEPT).catch(() => null); const fromNetwork = (async () => { - const cache = await opened; const res = await self.fetch(request); - if (res.status === 200) { - const copy = kind === "read" ? await stamped(res.clone(), { "x-pm-kept-at": String(Date.now()) }) : res.clone(); - await cache.put(key, copy); - } else if (res.status === 304 && kind === "read") { - // The app's own copy is current, and so is the one kept here: - // nothing new to keep but when that was, which is small. - const seen = { "x-pm-kept-at": String(Date.now()), "x-as-of": res.headers.get("x-as-of") ?? "" }; - await cache.put(seenKey(key), new Response("", { headers: seen })); + // Keeping it is on a best effort: an answer the network gave is + // the answer, whether or not this device had room to keep a copy. + try { + const cache = await opened; + if (!cache) return res; + if (res.status === 200) { + const copy = kind === "read" ? await stamped(res.clone(), { "x-pm-kept-at": String(Date.now()) }) : res.clone(); + await cache.put(key, copy); + } else if (res.status === 304 && kind === "read") { + // The app's own copy is current, and so is the one kept here: + // nothing new to keep but when that was, which is small. + const seen = { "x-pm-kept-at": String(Date.now()), "x-as-of": res.headers.get("x-as-of") ?? "" }; + await cache.put(seenKey(key), new Response("", { headers: seen })); + } + } catch { + // No room: nothing is kept this time. } return res; })(); const kept = async () => { - const cache = await opened; - const copy = await cache.match(key); - if (!copy) return null; - if (kind !== "read") return copy; - // As current as it was last said to be, which may be later than - // when it was last sent whole. - const marks = { "x-pm-offline": "1" }; - const seen = await cache.match(seenKey(key)); - if (seen && Number(seen.headers.get("x-pm-kept-at")) > Number(copy.headers.get("x-pm-kept-at"))) { - marks["x-pm-kept-at"] = seen.headers.get("x-pm-kept-at"); - if (seen.headers.get("x-as-of")) marks["x-as-of"] = seen.headers.get("x-as-of"); + try { + const cache = await opened; + const copy = await cache?.match(key); + if (!copy) return null; + if (kind !== "read") return copy; + // As current as it was last said to be, which may be later than + // when it was last sent whole. + const marks = { "x-pm-offline": "1" }; + const seen = await cache.match(seenKey(key)); + if (seen && Number(seen.headers.get("x-pm-kept-at")) > Number(copy.headers.get("x-pm-kept-at"))) { + marks["x-pm-kept-at"] = seen.headers.get("x-pm-kept-at"); + if (seen.headers.get("x-as-of")) marks["x-as-of"] = seen.headers.get("x-as-of"); + } + return await stamped(copy, marks); + } catch { + // A copy that cannot be read is no copy. + return null; } - return stamped(copy, marks); }; const shown = (async () => { const first = await Promise.race([ @@ -161,8 +187,9 @@ self.addEventListener("fetch", (event) => { // ---- what the owner did while offline ------------------------------------ -/** Send what is waiting. Told to every open page, so each shows it. */ -async function send() { +/** Send what is waiting. Told to every open page, so each shows it. + * `last`: the browser will not call again for this by itself. */ +async function send(last = false) { const store = self.PMOutbox.idbStore(); const flush = () => self.PMOutbox.flush(store, (entry) => self.PMOutbox.httpSend(entry, (url, init) => self.fetch(url, init))); @@ -180,11 +207,16 @@ async function send() { const done = out.changed.filter((e) => e.state === "done" || e.state === "held").length; const failed = out.changed.filter((e) => e.state === "failed").length; const stale = out.changed.filter((e) => e.state === "stale").length; - if (!open && done + failed + stale > 0 && self.Notification?.permission === "granted") { + // On the browser's last call for this, what still waits is not sent + // until the app is next opened: that is said too, or it would wait + // unseen. (What waits for a sign-in is said below.) + const left = last && !out.signin ? out.waiting : 0; + if (!open && done + failed + stale + left > 0 && self.Notification?.permission === "granted") { const parts = [ done ? `${done} sent` : "", failed ? `${failed} could not be done` : "", stale ? `${stale} kept back for you to look at` : "", + left ? `${left} still waiting (open the app to send ${left === 1 ? "it" : "them"})` : "", ].filter(Boolean); await self.registration.showNotification("What you did offline", { body: `${parts.join(", ")}.`, @@ -206,12 +238,16 @@ async function send() { data: { url: "/console/#more/device" }, }); } - // Still no connection: say so, and the browser will call again. + // Still no connection, or something is still waiting for the + // platform to be able to take it: say so, and the browser will call + // again. (Not when it waits for a sign-in: calling again would not + // help, and the owner has been told.) if (out.offline) throw new Error("still offline"); + if (out.waiting > 0 && !out.signin) throw new Error("not all sent yet"); } self.addEventListener("sync", (event) => { - if (event.tag === "pm-outbox") event.waitUntil(send()); + if (event.tag === "pm-outbox") event.waitUntil(send(event.lastChance === true)); }); self.addEventListener("message", (event) => { diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index 4c4d20f3d0..5367830c41 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -200,6 +200,44 @@ export const HOLDABLE = new Set([ "intake.send", "triage.enqueue", ]); +/** What an action is about, where the order of two matters: a rank set + * twice, a task moved twice. Two about one thing are done in the order + * the owner did them: one that may be done late goes behind an earlier + * one about the same thing that is still held for a machine. Null: it + * stands alone. (The device keeps the same order for what it has not + * sent yet: `subject` in public/outbox.js says the same, and a test + * holds the two together.) */ +export function subjectOf(kind: string, args: Record | null | undefined): string | null { + const a = args ?? {}; + const of = (what: string, value: unknown) => { + const said = typeof value === "string" || typeof value === "number" ? String(value) : ""; + return said === "" ? null : `${what}:${said}`; + }; + switch (kind) { + case "ask.reply": + case "ask.close": + case "issue.comment": + case "issue.rank": + return of("issue", a.issue); + case "task.move": + case "task.cancel": + case "task.unblock": + return of("task", a.task); + case "hands.done": + case "need.comment": + return of("ref", a.ref); + case "question.answer": + case "question.defer": + case "questions.accept": + return of("questions", a.set); + case "pr.merge": + return of("pr", a.pr); + case "unit.act": + return of("unit", a.unit); + default: + return null; + } +} /** A held action older than this is dropped, and said to have been. */ export const HELD_FOR_MS = 24 * 60 * 60_000; /** A sync whose time is further than this from the edge's clock is refused. */ diff --git a/pm-stack/console/src/named.ts b/pm-stack/console/src/named.ts index aa0afe7a86..9a572a9a01 100644 --- a/pm-stack/console/src/named.ts +++ b/pm-stack/console/src/named.ts @@ -25,19 +25,25 @@ type Fate = "started" | Outcome; const KEPT = 300; export class Named { - private fates: Map | null = null; + /** The record, read once. Everyone who asks while it is being read + * gets the same one: two readers with a record each would each write + * theirs back without what the other had written down. */ + private fates: Promise> | null = null; /** Names being done right now, in this process. */ private running = new Set(); + /** The write under way, if any: the next one waits for it. */ + private writing: Promise = Promise.resolve(); constructor(private store: Store) {} - private async all(): Promise> { - if (this.fates) return this.fates; - try { - this.fates = new Map(Object.entries(JSON.parse((await this.store.read()) ?? "{}") as Record)); - } catch { - this.fates = new Map(); - } + private all(): Promise> { + this.fates ??= (async () => { + try { + return new Map(Object.entries(JSON.parse((await this.store.read()) ?? "{}") as Record)); + } catch { + return new Map(); + } + })(); return this.fates; } @@ -47,7 +53,19 @@ export class Named { fates.delete(id); fates.set(id, fate); while (fates.size > KEPT) fates.delete(fates.keys().next().value as string); - await this.store.write(JSON.stringify(Object.fromEntries(fates))); + await this.save(); + } + + /** One write at a time, each of the record as it stands when its turn + * comes: an earlier write that was slow cannot land over a later one + * and take a name out of the record. */ + private save(): Promise { + const mine = this.writing.then(async () => { + await this.store.write(JSON.stringify(Object.fromEntries(await this.all()))); + }); + // A write that failed is its own caller's to hear of, not the next one's. + this.writing = mine.catch(() => {}); + return mine; } /** What is written down for a name, if anything. */ @@ -59,6 +77,22 @@ export class Named { return this.running.has(id); } + /** Take a name for doing, now. False when it is already being done + * in this process. There is no waiting in this, so of two arrivals + * under one name only one can take it, whatever each has yet to + * write down. Whoever takes it gives it back with release() or end(). */ + take(id: string): boolean { + if (this.running.has(id)) return false; + this.running.add(id); + return true; + } + + /** Give back a name that was taken and, in the end, not done under + * (it was refused before it began). */ + release(id: string): void { + this.running.delete(id); + } + /** An action is about to be done under this name. Written down * first, so that if its answer is lost and it is offered again, it is * not done twice. */ @@ -76,13 +110,21 @@ export class Named { } } - /** What is known of an action sent under this name: nothing; that it - * is being done now; how it came out; or ("lost") that it was started - * and this process stopped before it was known how it ended. */ - async seen(id: string): Promise<{ state: "running" | "lost" } | { state: "done"; fate: Outcome } | null> { - if (this.running.has(id)) return { state: "running" }; + /** What is written down for a name, whoever holds it now: nothing; + * how it came out; or ("lost") that it was started and this process + * stopped before it was known how it ended. For whoever has just + * taken the name: read after taking, this cannot miss what another + * wrote down before giving the name back. */ + async known(id: string): Promise<{ state: "lost" } | { state: "done"; fate: Outcome } | null> { const fate = await this.get(id); if (fate === undefined) return null; return fate === "started" ? { state: "lost" } : { state: "done", fate }; } + + /** What is known of an action sent under this name: that it is being + * done now, or what is written down for it. */ + async seen(id: string): Promise<{ state: "running" | "lost" } | { state: "done"; fate: Outcome } | null> { + if (this.running.has(id)) return { state: "running" }; + return this.known(id); + } } diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 8257786af6..6ef681654f 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -140,11 +140,11 @@ export interface Deps { * exist only when their limits do. */ phones?: Phones; /** This host's link to the edge, when the app is served from one. */ - link?: Pick & Partial>; + link?: Pick & Partial>; /** What became of each action sent under a name, so that one is done * once however often it arrives. The link keeps one; a host with no * edge in front of it keeps its own. */ - named?: Pick; + named?: Pick & Partial>; } /** Text that shrinks well. The dashboard's fragments run to a megabyte @@ -415,47 +415,61 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul : undefined; const record = deps.named ?? deps.link; const link = ACT_ID.test(name) && record?.begin && record.end ? record : null; - const before = (await link?.seen?.(name)) ?? null; - if (before?.state === "running") return json({ error: "This is still being done.", running: true }, 409); - if (before?.state === "lost") { - // Started, and this host stopped before it ended. Whether it - // happened is not known, and doing it again could do it twice. - const fate = { - ok: false, - status: 502, - error: "the host restarted while doing this; check whether it happened", - }; - await link?.end?.(name, fate); - return json({ error: fate.error, again: true }, 502); - } - if (before?.state === "done") { - return before.fate.ok - ? json({ ok: true, result: before.fate.result ?? null, again: true, ...forEdge?.() }) - : json({ error: before.fate.error ?? "it could not be done", again: true }, before.fate.status ?? 502); + // The name is taken for doing here and now, before anything is + // waited for (what is known of it is read, and the audit written, + // after): of two arrivals under one name only one can take it, + // and the other is told it is being done. + const taken = link?.take && link.known ? link.take(name) : null; + if (taken === false) return json({ error: "This is still being done.", running: true }, 409); + try { + // What was written down for it before. (A record that cannot be + // taken is asked the older way, which also says "being done".) + const before = (await (taken ? link?.known?.(name) : link?.seen?.(name))) ?? null; + if (before?.state === "running") return json({ error: "This is still being done.", running: true }, 409); + if (before?.state === "lost") { + // Started, and this host stopped before it ended. Whether it + // happened is not known, and doing it again could do it twice. + const fate = { + ok: false, + status: 502, + error: "the host restarted while doing this; check whether it happened", + }; + await link?.end?.(name, fate); + return json({ error: fate.error, again: true }, 502); + } + if (before?.state === "done") { + return before.fate.ok + ? json({ ok: true, result: before.fate.result ?? null, again: true, ...forEdge?.() }) + : json({ error: before.fate.error ?? "it could not be done", again: true }, before.fate.status ?? 502); + } + return await act( + kind || "unknown", + kept, + async () => { + await link?.begin?.(name); + docs.logAct({ ...entry, status: "running" }); + try { + const result = await perform(table, docs, kind, args); + docs.logAct({ ...entry, status: "done" }); + await link?.end?.(name, { ok: true, ...keptSmall(result) }); + return result; + } catch (error) { + docs.logAct({ ...entry, status: "failed", note: (error as Error).message.slice(0, 200) }); + await link?.end?.(name, { + ok: false, + error: (error as Error).message.slice(0, 300), + status: error instanceof OpError ? error.status : 502, + }); + throw error; + } + }, + forEdge, + ); + } finally { + // Given back, whatever became of it: answered from the record, + // refused before it began, or done (when it is given back already). + if (taken) link?.release?.(name); } - return await act( - kind || "unknown", - kept, - async () => { - await link?.begin?.(name); - docs.logAct({ ...entry, status: "running" }); - try { - const result = await perform(table, docs, kind, args); - docs.logAct({ ...entry, status: "done" }); - await link?.end?.(name, { ok: true, ...keptSmall(result) }); - return result; - } catch (error) { - docs.logAct({ ...entry, status: "failed", note: (error as Error).message.slice(0, 200) }); - await link?.end?.(name, { - ok: false, - error: (error as Error).message.slice(0, 300), - status: error instanceof OpError ? error.status : 502, - }); - throw error; - } - }, - forEdge, - ); } if (seg.length === 3 && seg[0] === "queue") { return await act(`queue.${seg[2]}`, { task: seg[1], reason: body.reason }, () => diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index 3f9e8357cd..a12fcd8e75 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -141,38 +141,57 @@ export class EdgeLink { return this.named.seen(id); } + /** What is written down for a name, whoever holds it now. */ + known(id: string) { + return this.named.known(id); + } + + /** Take a name for doing, now, or learn that it is being done. */ + take(id: string): boolean { + return this.named.take(id); + } + + /** Give back a name that was taken and not done under. */ + release(id: string): void { + this.named.release(id); + } + /** A held action from the edge: run it unless it has been seen before. */ - private async take(held: Held): Promise { + private async doHeld(held: Held): Promise { if (this.acks.some((a) => a.id === held.id)) return; - // Still being done (its answer was slow, not lost): say nothing yet. - if (this.named.isRunning(held.id)) return; - const seen = await this.named.get(held.id); - if (seen === "started") { - // The host stopped while this was running. Whether it happened is - // not known, and running it again could do it twice. - const fate = { ok: false, error: "the host restarted while doing this; check whether it happened" }; - await this.named.record(held.id, fate); - this.acks.push({ id: held.id, ...fate }); - return; - } - if (seen) { - this.acks.push({ id: held.id, ...seen }); // the edge missed the first answer - return; - } - let fate: { ok: boolean; error?: string }; - if (!HOLDABLE.has(held.kind)) { - fate = { ok: false, error: "this is not an action that may be done late" }; - } else { - await this.named.record(held.id, "started"); - try { - await this.o.run(held); - fate = { ok: true }; - } catch (error) { - fate = { ok: false, error: (error as Error).message.slice(0, 300) }; + // Taken for doing, here and now, before anything is read: the same + // name arriving by another way while this runs is told it is being + // done, not that it was lost. Not taken: it is still being done + // (its answer was slow, not lost; or the device that sent it is + // sending it again this moment), and nothing is said yet. + if (!this.named.take(held.id)) return; + try { + const seen = await this.named.get(held.id); + let fate: Outcome; + if (seen === "started") { + // The host stopped while this was running. Whether it happened + // is not known, and running it again could do it twice. + fate = { ok: false, error: "the host restarted while doing this; check whether it happened" }; + } else if (seen) { + // The edge missed the first answer. + this.acks.push({ id: held.id, ok: seen.ok, ...(seen.error ? { error: seen.error } : {}) }); + return; + } else if (!HOLDABLE.has(held.kind)) { + fate = { ok: false, error: "this is not an action that may be done late" }; + } else { + await this.named.record(held.id, "started"); + try { + await this.o.run(held); + fate = { ok: true }; + } catch (error) { + fate = { ok: false, error: (error as Error).message.slice(0, 300) }; + } } + await this.named.record(held.id, fate); + this.acks.push({ id: held.id, ok: fate.ok, ...(fate.error ? { error: fate.error } : {}) }); + } finally { + this.named.release(held.id); } - await this.named.record(held.id, fate); - this.acks.push({ id: held.id, ...fate }); } /** The build could not be sent. It is left out of the reports that @@ -289,7 +308,7 @@ export class EdgeLink { this.want = new Set(answer.want ?? []); this.last = answer; await this.o.phones.mergeLinks(answer.phones); - for (const held of answer.commands ?? []) await this.take(held); + for (const held of answer.commands ?? []) await this.doHeld(held); return answer; } finally { this.busy = false; diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index c954502bbf..53eb9312f4 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -27,6 +27,7 @@ import { phaseHeading, prCheck, runSaid, + sentSaid, servingSaid, subscriptionState, testSaid, @@ -679,3 +680,52 @@ test("keeping a copy of every screen reads each under the address its screen ask "signin", ]); }); + +test("what the owner is told of something just done, from what became of it when it was sent in its turn", () => { + const id = "0c000000-0000-4000-8000-000000000001"; + const older = [{ id: "x", state: "done" }]; + const quiet = { others: [], signin: false, offline: false }; + // Done: its result, and what else went with it. + expect(sentSaid({ ...quiet, entry: { state: "done", result: { rank: "next" } }, others: older }, id)).toEqual({ + state: "done", + result: { rank: "next" }, + others: older, + }); + expect(sentSaid({ ...quiet, entry: { state: "done" } }, id)).toEqual({ state: "done", result: null, others: [] }); + // Taken by the platform for a machine. + expect(sentSaid({ ...quiet, entry: { state: "held" }, others: older }, id)).toEqual({ state: "held", others: older }); + // Refused: said, and nothing more. + expect(sentSaid({ ...quiet, entry: { state: "failed", note: "no such issue" } }, id)).toEqual({ + state: "failed", + note: "no such issue", + }); + // Kept on the device: with no connection, with no sign-in, and when + // nothing could take it or it goes behind another, each said as itself. + expect(sentSaid({ ...quiet, offline: true, entry: { state: "waiting", note: "" } }, id)).toEqual({ + state: "kept", + id, + note: "Kept on this device. It is sent when you are connected.", + }); + expect( + sentSaid({ ...quiet, signin: true, entry: { state: "waiting", note: "Sign in again to send this." } }, id), + ).toEqual({ + state: "kept", + id, + note: "Kept on this device. Sign in again to send it.", + }); + expect( + sentSaid( + { ...quiet, entry: { state: "waiting", note: "Nothing could take it just now. It is offered again." } }, + id, + ), + ).toEqual({ + state: "kept", + id, + note: "Kept on this device: Nothing could take it just now. It is offered again.", + }); + // Taken back by the owner while it was out. + expect(sentSaid({ ...quiet, entry: null }, id)).toEqual({ + state: "refused", + note: "It was taken back before it was sent.", + }); +}); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 6d07d12c1b..66cdbba33a 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -590,8 +590,13 @@ async function setup(options: { direct?: boolean } = {}) { const puts: string[] = []; /** Keys the edge's storage refuses to write, as a store in trouble would. */ const storeFails = new Set(); + /** Keys the edge's storage is slow to read: a read waits for its promise. */ + const storeSlow = new Map>(); const kv: KV = { - get: async (key) => structuredClone(stored.get(key)), + get: async (key) => { + await storeSlow.get(key); + return structuredClone(stored.get(key)); + }, put: async (key, value) => { if (storeFails.has(key)) throw new Error(`storage: could not write ${key}`); puts.push(key); @@ -743,6 +748,16 @@ async function setup(options: { direct?: boolean } = {}) { touch: [], audit: (a) => ({ ref: a.ref }), }, + // Something said to an agent: about nothing else, so nothing orders it. + "message.send": { + run: async (a) => { + ran.push({ kind: "message.send", args: a }); + await gate.wait; + return { sent: a.to }; + }, + touch: [], + audit: (a) => ({ to: a.to }), + }, }; const audited: Record[] = []; const hostDeps: Deps = { @@ -884,6 +899,9 @@ async function setup(options: { direct?: boolean } = {}) { begin: (id) => link.now.begin(id), end: (id, fate) => link.now.end(id, fate), seen: (id) => link.now.seen(id), + known: (id) => link.now.known(id), + take: (id) => link.now.take(id), + release: (id) => link.now.release(id), }; const token = (claims: Record = {}) => @@ -971,6 +989,7 @@ async function setup(options: { direct?: boolean } = {}) { ghDrops, ghSays, ghHolds, + storeSlow, queueReadOnly, ghBreaks, queueRefuses, @@ -1559,6 +1578,76 @@ describe("actions", () => { expect(w.ran.filter((r) => r.kind === "need.comment")).toHaveLength(1); }); + test("sent again while the laptop is doing the copy that was held for it, the device is told to wait, not that it was lost", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + const id = "0a000000-0000-4000-8000-000000000006"; + const args = { to: ["lane-1"], text: "held, then slow" }; + w.net.hostUp = false; + expect(await (await w.act("message.send", args, id)).json()).toMatchObject({ ok: true, held: true }); + // The laptop is back, takes the held action, and is slow doing it. + w.net.hostUp = true; + let done: () => void = () => {}; + w.gate.wait = new Promise((resolve) => { + done = resolve; + }); + w.now.t += 1_000; + const taking = w.link.now.once(); + await new Promise((r) => setTimeout(r, 5)); + expect(w.ran.map((r) => r.kind)).toEqual(["message.send"]); + // The device, which never heard, sends it again meanwhile, and it + // reaches the laptop a second way. + const meanwhile = await w.act("message.send", args, id); + expect([meanwhile.status, await meanwhile.json()]).toEqual([ + 409, + { error: "This is still being done.", running: true }, + ]); + done(); + await taking; + w.gate.wait = null; + // Done once; and asked once more, the device hears how it came out. + expect(w.ran).toHaveLength(1); + const after = await w.act("message.send", args, id); + expect(await after.json()).toMatchObject({ ok: true, again: true }); + expect(w.ran).toHaveLength(1); + }); + + test("done late in the order it was done: what may wait goes behind an earlier one about the same thing that a machine has not taken yet", async () => { + const w = await setup(); + await w.hostReads(); + await w.link.now.once(); + // With the laptop out of reach, the owner moves a task to the top. + w.net.hostUp = false; + const first = await w.act("task.move", { task: 21016, to: "first" }); + expect(await first.json()).toMatchObject({ ok: true, held: true }); + // The laptop is in reach again, and before it has taken that, the + // owner moves the same task to the bottom. Sent straight on, it + // would be done first, and the older move would undo it. + w.net.hostUp = true; + const second = await w.act("task.move", { task: 21016, to: "last" }); + expect(await second.json()).toEqual({ ok: true, held: true, result: null }); + expect(w.ran.filter((r) => r.kind === "task.move")).toEqual([]); + // Another task is nothing to do with it: it is done at once. + const other = await w.act("task.move", { task: 21017, to: "first" }); + expect(await other.json()).toEqual({ ok: true, result: { task: 21017, priority: 10 } }); + // So is something about nothing in particular. + expect((await w.act("message.send", { to: ["lane-1"], text: "hello" })).status).toBe(200); + // The laptop takes what waited, in the order the owner did it. + w.now.t += 1_000; + await w.link.now.once(); + expect(w.ran.filter((r) => r.kind === "task.move").map((r) => [r.args.task, r.args.to])).toEqual([ + [21017, "first"], + [21016, "first"], + [21016, "last"], + ]); + // Nothing waits any more, so the next one about that task goes straight on. + w.now.t += 1_000; + await w.link.now.once(); + const third = await w.act("task.move", { task: 21016, to: "first" }); + expect(await third.json()).toEqual({ ok: true, result: { task: 21016, priority: 10 } }); + }); + test("held twice under one name, an action waits once", async () => { const w = await setup(); await w.hostReads(); @@ -3114,6 +3203,36 @@ describe("the edge does the core itself", () => { expect(w.githubCalls.filter((c) => merge(c.method, c.url))).toHaveLength(1); }); + test("two arrivals under one name at the same moment are one doing, here", async () => { + const w = await primary(); + const id = "0b000000-0000-4000-8000-000000000007"; + // The first is still reading what is known of the name when the + // second arrives: neither has written anything down. + let open: () => void = () => {}; + w.storeSlow.set( + `a:${id}`, + new Promise((r) => { + open = r; + }), + ); + const first = w.act("pr.merge", { pr: 55 }, id); + await new Promise((r) => setTimeout(r, 5)); + const second = w.act("pr.merge", { pr: 55 }, id); + await new Promise((r) => setTimeout(r, 5)); + w.storeSlow.clear(); + open(); + const both = await Promise.all([first, second]); + expect(both.map((r) => r.status).sort()).toEqual([200, 409]); + expect(await (both.find((r) => r.status === 409) as Response).json()).toEqual({ + error: "This is still being done.", + running: true, + }); + expect(w.ghMerged).toHaveLength(1); + // The name is free again afterwards: asked once more, it is answered from what was written down. + expect(await (await w.act("pr.merge", { pr: 55 }, id)).json()).toMatchObject({ ok: true, again: true }); + expect(w.ghMerged).toHaveLength(1); + }); + test("handed on to the laptop, an action keeps the device's name for it: the laptop does it once", async () => { const w = await primary(); const id = "0b000000-0000-4000-8000-000000000006"; diff --git a/pm-stack/console/test/outbox.test.ts b/pm-stack/console/test/outbox.test.ts index 58c0c4ff09..d7ecd6d32b 100644 --- a/pm-stack/console/test/outbox.test.ts +++ b/pm-stack/console/test/outbox.test.ts @@ -9,6 +9,7 @@ // each once is checked in a browser and in test/edge.test.ts. import { expect, test } from "bun:test"; import "../public/outbox.js"; +import { HOLDABLE, subjectOf } from "../src/edge-proto.ts"; interface Entry { id: string; @@ -33,6 +34,7 @@ interface Store { const O = (globalThis as unknown as { PMOutbox: Record }).PMOutbox as { TIMELY_MS: number; rule(kind: string): "late" | "timely" | "now"; + subject(kind: string, args?: unknown): string | null; sayOf(kind: string, args?: unknown): string; make(kind: string, args: unknown, now: number, said?: string, id?: string): Entry; classify(answer: Answer): { state: string; note: string; stop?: boolean; signin?: boolean; result?: unknown }; @@ -43,7 +45,13 @@ const O = (globalThis as unknown as { PMOutbox: Record }).PMOut store: Store, send: (entry: Entry) => Promise, now?: () => number, - ): Promise<{ changed: Entry[]; signin: boolean; offline: boolean }>; + ): Promise<{ changed: Entry[]; signin: boolean; offline: boolean; waiting: number; looked: string[] }>; + sendInOrder( + store: Store, + id: string, + send: (entry: Entry) => Promise, + now?: () => number, + ): Promise<{ entry: Entry | null; others: Entry[]; signin: boolean; offline: boolean }>; settle(store: Store, acts: unknown, now?: () => number): Promise; httpSend(entry: Entry, fetchImpl: (url: string, init: RequestInit) => Promise): Promise; memoryStore(): Store; @@ -364,6 +372,313 @@ test("a merge asked for a while ago is kept back, not sent, until the owner says expect(sent).toEqual(["task.cancel", "pr.merge"]); }); +test("one taken back while another is being sent is not sent, and one dealt with meanwhile is not dealt with again", async () => { + const store = O.memoryStore(); + const first = O.make("ask.send", { text: "slow" }, T0); + const second = O.make("pr.merge", { pr: 55 }, T0 + 1); + const third = O.make("issue.rank", { issue: 301, rank: "next" }, T0 + 2); + const fourth = O.make("ask.reply", { issue: 201, text: "still wanted" }, T0 + 3); + for (const e of [first, second, third, fourth]) await store.put(e); + let open: () => void = () => {}; + const gate = new Promise((r) => { + open = r; + }); + const sent: string[] = []; + const flushing = O.flush( + store, + async (e) => { + sent.push(e.kind); + if (e.kind === "ask.send") await gate; + return ok(); + }, + () => T0 + 10, + ); + await new Promise((r) => setTimeout(r, 5)); + // While the first is out: the owner says "do not send" on the merge, + // and something else (the service worker, another tab) deals with the rank. + await store.remove(second.id); + await store.put({ ...third, state: "done", endedAt: T0 + 9 }); + open(); + const out = await flushing; + expect(sent).toEqual(["ask.send", "ask.reply"]); + expect(out.changed.map((e) => e.kind)).toEqual(["ask.send", "ask.reply"]); + expect((await store.all()).map((e) => [e.kind, e.state]).sort()).toEqual([ + ["ask.reply", "done"], + ["ask.send", "done"], + ["issue.rank", "done"], + ]); + // Nothing is left waiting, and the flush says so. + expect(out.waiting).toBe(0); +}); + +test("a flush says how many are still waiting to be sent, not counting what waits for the owner", async () => { + const store = O.memoryStore(); + await store.put(O.make("message.send", { to: ["a"], text: "x" }, T0)); + await store.put(O.make("pr.merge", { pr: 55 }, T0 - 60 * MIN)); + await store.put({ ...O.make("ask.send", {}, T0), state: "failed" }); + const out = await O.flush( + store, + async () => ({ status: 503, body: { error: "no machine" } }), + () => T0 + 1, + ); + expect([out.waiting, out.offline, out.signin]).toEqual([1, false, false]); + expect( + ( + await O.flush( + store, + async () => ({ network: true }), + () => T0 + 2, + ) + ).waiting, + ).toBe(1); + expect( + ( + await O.flush( + store, + async () => ok(), + () => T0 + 3, + ) + ).waiting, + ).toBe(0); +}); + +test("what an action is about: two about one thing keep their order, on the device and on the platform alike", () => { + const cases: [string, Record, string | null][] = [ + ["issue.rank", { issue: 301, rank: "now" }, "issue:301"], + ["issue.comment", { issue: 301, text: "x" }, "issue:301"], + ["ask.reply", { issue: 201, text: "x" }, "issue:201"], + ["ask.close", { issue: 201 }, "issue:201"], + ["task.move", { task: 21016, to: "first" }, "task:21016"], + ["task.cancel", { task: 21016, reason: "x" }, "task:21016"], + ["task.unblock", { task: "21016" }, "task:21016"], + ["need.comment", { ref: "developing-today/code#3", text: "x" }, "ref:developing-today/code#3"], + ["hands.done", { ref: "developing-today/code#3" }, "ref:developing-today/code#3"], + ["question.answer", { set: "s1", qid: "q1", option: "a" }, "questions:s1"], + ["question.defer", { set: "s1", qid: "q2" }, "questions:s1"], + ["questions.accept", { set: "s1" }, "questions:s1"], + ["pr.merge", { pr: 55 }, "pr:55"], + ["unit.act", { unit: "fleet-queue.service", action: "restart" }, "unit:fleet-queue.service"], + // About nothing else: nothing orders them. + ["ask.send", { text: "x" }, null], + ["intake.send", { text: "x", kind: "bug" }, null], + ["message.send", { to: ["a"], text: "x" }, null], + ["deploy.start", { what: "site" }, null], + ["prompt.enqueue", { issue: 201, text: "x" }, null], + ["something.new", { issue: 1 }, null], + // Said without the thing it is about, it is about nothing. + ["issue.rank", {}, null], + ["issue.rank", { issue: "" }, null], + ["task.move", { task: null }, null], + ["task.move", { task: { toString: () => "21016" } }, null], + ]; + for (const [kind, args, about] of cases) { + expect([kind, args, O.subject(kind, args)]).toEqual([kind, args, about]); + expect([kind, args, subjectOf(kind, args)]).toEqual([kind, args, about]); + } + expect([O.subject("issue.rank"), O.subject("issue.rank", null), subjectOf("issue.rank", null)]).toEqual([ + null, + null, + null, + ]); + // Everything the platform may hold for a machine is something the + // device may keep too, or is the platform's own second half of one. + for (const kind of HOLDABLE) { + if (kind === "prompt.enqueue" || kind === "triage.enqueue") continue; + expect([kind, O.rule(kind)]).toEqual([kind, "late"]); + } +}); + +test("a later one about the same thing is not sent ahead of an earlier one that has not been taken", async () => { + const store = O.memoryStore(); + const older = O.make("task.move", { task: 21016, to: "first" }, T0); + const newer = O.make("task.move", { task: 21016, to: "last" }, T0 + 1); + const other = O.make("task.move", { task: 21017, to: "first" }, T0 + 2); + const alone = O.make("ask.send", { text: "x" }, T0 + 3); + for (const e of [older, newer, other, alone]) await store.put(e); + const sent: unknown[] = []; + // Nothing can take the older one just now; anything else would be taken. + const busy = async (e: Entry): Promise => { + sent.push(e.kind === "task.move" ? `${e.args.task} ${e.args.to}` : e.kind); + return e.id === older.id ? { status: 503, body: { error: "no machine" } } : ok(); + }; + const out = await O.flush(store, busy, () => T0 + 10); + // The newer move of that task was not sent: done first, the older + // would undo it when its turn came. The rest went. + expect(sent).toEqual(["21016 first", "21017 first", "ask.send"]); + expect(out.changed.map((e) => [e.id, e.state, e.note])).toEqual([ + [older.id, "waiting", "Nothing could take it just now. It is offered again."], + [newer.id, "waiting", "It goes after an earlier one about the same thing, which has not been taken yet."], + [other.id, "done", ""], + [alone.id, "done", ""], + ]); + expect([out.waiting, out.looked.length]).toEqual([2, 4]); + // The same again changes nothing, and writes nothing. + sent.length = 0; + expect((await O.flush(store, busy, () => T0 + 11)).changed).toEqual([]); + expect(sent).toEqual(["21016 first"]); + // Being done right now is the same: the newer waits for it to end. + sent.length = 0; + await O.flush( + store, + async (e) => { + sent.push(`${e.args.task} ${e.args.to}`); + return { status: 409, body: { error: "This is still being done.", running: true } }; + }, + () => T0 + 12, + ); + expect(sent).toEqual(["21016 first"]); + // Once the older is taken, the newer goes after it, in the same pass. + sent.length = 0; + const after = await O.flush( + store, + async (e) => { + sent.push(`${e.args.task} ${e.args.to}`); + return ok(); + }, + () => T0 + 13, + ); + expect(sent).toEqual(["21016 first", "21016 last"]); + expect(after.changed.map((e) => [e.id, e.state, e.note])).toEqual([ + [older.id, "done", ""], + [newer.id, "done", ""], + ]); + // One that failed, or went stale, is not waited for: the owner is told of it instead. + const again = O.memoryStore(); + await again.put(O.make("issue.rank", { issue: 301, rank: "now" }, T0)); + await again.put(O.make("issue.rank", { issue: 301, rank: "next" }, T0 + 1)); + const refused = await O.flush( + again, + async (e) => (e.args.rank === "now" ? { status: 404, body: { error: "no such issue" } } : ok()), + () => T0 + 2, + ); + expect(refused.changed.map((e) => [e.args.rank, e.state])).toEqual([ + ["now", "failed"], + ["next", "done"], + ]); +}); + +test("sent in order behind one about the same thing that is not taken: it is kept, said why, and the older is tried once", async () => { + const store = O.memoryStore(); + const older = O.make("issue.rank", { issue: 301, rank: "now" }, T0); + await store.put(older); + const newer = O.make("issue.rank", { issue: 301, rank: "next" }, T0 + 60_000); + await store.put(newer); + const sent: unknown[] = []; + const did = await O.sendInOrder( + store, + newer.id, + async (e) => { + sent.push(e.args.rank); + return { status: 503, body: { error: "no machine" } }; + }, + () => T0 + 61_000, + ); + expect(sent).toEqual(["now"]); + expect(did.entry).toMatchObject({ + id: newer.id, + state: "waiting", + tries: 0, + note: "It goes after an earlier one about the same thing, which has not been taken yet.", + }); + expect(did.others.map((e) => [e.id, e.state])).toEqual([[older.id, "waiting"]]); +}); + +test("something done now goes behind what is already waiting, so the older cannot undo it later", async () => { + const store = O.memoryStore(); + // Kept from when there was no connection: the issue ranked "now". + const older = O.make("issue.rank", { issue: 301, rank: "now" }, T0); + await store.put(older); + // Connected again, and before anything else has sent it, the owner + // ranks the same issue "next". + const newer = O.make("issue.rank", { issue: 301, rank: "next" }, T0 + 60_000); + await store.put(newer); + const ranks: unknown[] = []; + const did = await O.sendInOrder( + store, + newer.id, + async (e) => { + ranks.push(e.args.rank); + return ok({ rank: e.args.rank }); + }, + () => T0 + 61_000, + ); + // The older went first, so the issue ends as the owner last said. + expect(ranks).toEqual(["now", "next"]); + expect(did.entry).toMatchObject({ id: newer.id, state: "done", result: { rank: "next" } }); + expect(did.others.map((e) => [e.id, e.state])).toEqual([[older.id, "done"]]); + expect([did.signin, did.offline]).toEqual([false, false]); +}); + +test("sent in order: what each outcome leaves behind", async () => { + const fresh = async (answer: (e: Entry) => Answer | Promise) => { + const store = O.memoryStore(); + const entry = O.make("ask.send", { text: "x" }, T0); + await store.put(entry); + const did = await O.sendInOrder( + store, + entry.id, + async (e) => answer(e), + () => T0 + 1, + ); + return { did, left: await store.all() }; + }; + // No connection: it waits, written down. + const offline = await fresh(() => ({ network: true })); + expect([offline.did.entry?.state, offline.did.offline, offline.left.map((e) => e.state)]).toEqual([ + "waiting", + true, + ["waiting"], + ]); + // No sign-in: the same, and it says which. + const signin = await fresh(() => ({ signin: true, status: 0, body: null })); + expect([signin.did.entry?.state, signin.did.signin, signin.did.entry?.note]).toEqual([ + "waiting", + true, + "Sign in again to send this.", + ]); + // Refused: said at once, and nothing of it is kept. + const failed = await fresh(() => ({ status: 404, body: { error: "no such issue" } })); + expect([failed.did.entry?.state, failed.did.entry?.note, failed.left]).toEqual(["failed", "no such issue", []]); + // Kept by the platform for a machine. + const held = await fresh(() => ({ status: 200, body: { ok: true, held: true, result: null } })); + expect([held.did.entry?.state, held.left.map((e) => e.state)]).toEqual(["held", ["held"]]); + // Taken back while it was out: said as that. + const store = O.memoryStore(); + const entry = O.make("ask.send", { text: "x" }, T0); + await store.put(entry); + const gone = await O.sendInOrder(store, entry.id, async () => { + await store.remove(entry.id); + return { network: true }; + }); + expect(gone.entry).toBeNull(); +}); + +test("sent in order while another send is under way: it is not left behind", async () => { + const store = O.memoryStore(); + const first = O.make("ask.send", { text: "already going" }, T0); + await store.put(first); + let open: () => void = () => {}; + const gate = new Promise((r) => { + open = r; + }); + const sent: unknown[] = []; + const send = async (e: Entry) => { + sent.push(e.args.text); + if (e.args.text === "already going") await gate; + return ok(); + }; + const under = O.flush(store, send, () => T0 + 1); + await new Promise((r) => setTimeout(r, 5)); + // The owner does something else while that is out. + const second = O.make("ask.send", { text: "done meanwhile" }, T0 + 2); + await store.put(second); + const mine = O.sendInOrder(store, second.id, send, () => T0 + 3); + open(); + await under; + expect((await mine).entry).toMatchObject({ state: "done" }); + expect(sent).toEqual(["already going", "done meanwhile"]); +}); + test("two flushes at once are one flush: nothing is sent twice", async () => { const store = O.memoryStore(); await store.put(O.make("ask.send", { text: "once" }, T0)); diff --git a/pm-stack/console/test/sw.test.ts b/pm-stack/console/test/sw.test.ts index 3a8425c61c..7a474ffe9e 100644 --- a/pm-stack/console/test/sw.test.ts +++ b/pm-stack/console/test/sw.test.ts @@ -22,15 +22,23 @@ const PUBLIC = join(import.meta.dir, "../public"); /** The browser's cache, as far as the worker uses it. */ function fakeCaches() { const stores = new Map>(); + /** A device with no room left: every write is refused. */ + const full = { on: false }; + /** A browser that gives this site no cache at all: it cannot be opened. */ + const none = { on: false }; const keyOf = (key: string | Request) => { const url = new URL(typeof key === "string" ? key : key.url, ORIGIN); return url.pathname + url.search; }; const open = async (name: string) => { + if (none.on) throw new DOMException("The operation is insecure.", "SecurityError"); if (!stores.has(name)) stores.set(name, new Map()); const store = stores.get(name) as Map; return { - put: async (key: string | Request, res: Response) => void store.set(keyOf(key), res), + put: async (key: string | Request, res: Response) => { + if (full.on) throw new DOMException("Quota exceeded", "QuotaExceededError"); + store.set(keyOf(key), res); + }, match: async (key: string | Request) => store.get(keyOf(key))?.clone(), keys: async () => [...store.keys()].map((k) => new Request(ORIGIN + k)), delete: async (key: string | Request) => store.delete(keyOf(key)), @@ -38,11 +46,16 @@ function fakeCaches() { }; return { open, - keys: async () => [...stores.keys()], + keys: async () => { + if (none.on) throw new DOMException("The operation is insecure.", "SecurityError"); + return [...stores.keys()]; + }, delete: async (name: string) => stores.delete(name), /** For the tests: what is kept under a name. */ kept: (name = "pm-console-v1") => [...(stores.get(name)?.keys() ?? [])].sort(), stores, + full, + none, }; } @@ -585,3 +598,167 @@ test("the app's page is already sending: the worker leaves it to the page", asyn expect(sent).toEqual(["/console/api/act"]); expect((await store.all()).map((e) => e.state)).toEqual(["done"]); }); + +test("a device with no room to keep a copy still gets the network's answer", async () => { + const w = worker([], { net: () => json({ v: 1 }) }); + w.caches.full.on = true; + const read = w.get("/console/api/doc/core"); + expect(await (await read.given)?.json()).toEqual({ v: 1 }); + await read.settled(); + const page = w.get("/console/", { mode: "navigate" }); + expect((await page.given)?.status).toBe(200); + await page.settled(); + // Told its copy is current, with nowhere to note it: the answer is passed on all the same. + w.state.net = () => new Response(null, { status: 304 }); + expect((await w.get("/console/api/doc/core").given)?.status).toBe(304); + // Nothing was kept, so with no connection there is nothing to show: said as that. + w.state.net = down; + await expect(w.get("/console/api/doc/core").given).rejects.toThrow("Failed to fetch"); + // With room again, it keeps again. + w.caches.full.on = false; + w.state.net = () => json({ v: 2 }); + await w.get("/console/api/doc/core").settled(); + w.state.net = down; + expect(await (await w.get("/console/api/doc/core").given)?.json()).toEqual({ v: 2 }); +}); + +test("a browser that gives no cache at all: the network answers as if the worker were not there", async () => { + // The network takes a moment, as a real one does: long enough for + // anything left to fail on its own to be noticed. + const w = worker([], { + net: async () => { + await new Promise((r) => setTimeout(r, 3)); + return json({ v: 1 }); + }, + }); + w.caches.none.on = true; + const unhandled: unknown[] = []; + const note = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", note); + try { + // It is installed and takes the page all the same, for what else + // it does: notifications, and sending what was done offline. + await w.fire("install", {}); + await w.fire("activate", {}); + expect(w.did).toEqual(["skipWaiting", "claim"]); + const read = w.get("/console/api/doc/core"); + expect(await (await read.given)?.json()).toEqual({ v: 1 }); + await read.settled(); + const page = w.get("/console/", { mode: "navigate" }); + expect((await page.given)?.status).toBe(200); + await page.settled(); + // With no connection there is nothing to fall back on, and it fails as itself. + w.state.net = async () => { + await new Promise((r) => setTimeout(r, 3)); + return down(new URL(ORIGIN)); + }; + await expect(w.get("/console/api/doc/core").given).rejects.toThrow("Failed to fetch"); + await new Promise((r) => setTimeout(r, 5)); + } finally { + process.off("unhandledRejection", note); + } + // Nothing was left to fail on its own behind an answer. + expect(unhandled).toEqual([]); +}); + +test("woken with the app closed and something still not taken, the worker asks to be woken again", async () => { + type Entry = { id: string; kind: string; state: string; note: string }; + const answers: Record Response> = { + "ask.send": () => json({ ok: true, result: {} }), + // No machine in reach for it just now. + "message.send": () => + json({ error: "The laptop cannot be reached, and too much is already waiting for it." }, {}, 503), + }; + const net: Net = (_url, init) => { + const body = JSON.parse(String((init as { body?: string }).body)) as { kind: string }; + return answers[body.kind](); + }; + const w = worker([], { net }); + const outbox = w.scope.PMOutbox as { + memoryStore: () => { all: () => Promise; put: (e: unknown) => Promise }; + make: (kind: string, args: unknown, now: number) => unknown; + idbStore: unknown; + }; + const store = outbox.memoryStore(); + outbox.idbStore = () => store; + await store.put(outbox.make("message.send", { to: ["a"], text: "x" }, Date.now() - 2)); + await store.put(outbox.make("ask.send", { text: "y" }, Date.now() - 1)); + // One went, one could not be taken yet: the browser is to call again. + await expect(w.fire("sync", { tag: "pm-outbox" })).rejects.toThrow("not all sent yet"); + expect((await store.all()).map((e) => [e.kind, e.state]).sort()).toEqual([ + ["ask.send", "done"], + ["message.send", "waiting"], + ]); + // Being done right now under its name: the same. + answers["message.send"] = () => json({ error: "This is still being done.", running: true }, {}, 409); + await expect(w.fire("sync", { tag: "pm-outbox" })).rejects.toThrow("not all sent yet"); + // Taken at last: nothing is left, and the browser need not call again. + answers["message.send"] = () => json({ ok: true, held: true, result: null }); + await w.fire("sync", { tag: "pm-outbox" }); + expect((await store.all()).map((e) => e.state).sort()).toEqual(["done", "held"]); + // What only waits for the owner to look again is not a reason to be woken. + await store.put(outbox.make("pr.merge", { pr: 55 }, Date.now() - 3_600_000)); + await w.fire("sync", { tag: "pm-outbox" }); + expect((await store.all()).map((e) => e.state).sort()).toEqual(["done", "held", "stale"]); +}); + +test("on the browser's last call, what still waits is said, since nothing will send it until the app is opened", async () => { + type Entry = { id: string; kind: string; state: string }; + const taken = { yes: false }; + const net: Net = (_url, init) => { + const body = JSON.parse(String((init as { body?: string }).body)) as { kind: string }; + if (body.kind === "ask.send") return json({ ok: true, result: {} }); + return taken.yes ? json({ ok: true, result: {} }) : json({ error: "no machine" }, {}, 503); + }; + const setUp = async (windows: { url: string }[], permission = "granted") => { + const w = worker(windows, { net, permission }); + const outbox = w.scope.PMOutbox as { + memoryStore: () => { all: () => Promise; put: (e: unknown) => Promise }; + make: (kind: string, args: unknown, now: number) => unknown; + idbStore: unknown; + }; + const store = outbox.memoryStore(); + outbox.idbStore = () => store; + await store.put(outbox.make("ask.send", { text: "goes" }, Date.now() - 3)); + await store.put(outbox.make("message.send", { to: ["a"], text: "x" }, Date.now() - 2)); + await store.put(outbox.make("message.send", { to: ["b"], text: "y" }, Date.now() - 1)); + return { w, store }; + }; + // Not the last call: the browser will call again, and only what went is said. + const early = await setUp([]); + await expect(early.w.fire("sync", { tag: "pm-outbox", lastChance: false })).rejects.toThrow("not all sent yet"); + expect(early.w.shown.map((s) => s.options.body)).toEqual(["1 sent."]); + // The last call: what is left is said with it, in the one notification. + const last = await setUp([]); + await expect(last.w.fire("sync", { tag: "pm-outbox", lastChance: true })).rejects.toThrow("not all sent yet"); + expect(last.w.shown).toEqual([ + { + title: "What you did offline", + options: { + body: "1 sent, 2 still waiting (open the app to send them).", + tag: "outbox", + icon: "/icons/icon-192.png", + badge: "/icons/icon-192.png", + data: { url: "/console/#more/device" }, + }, + }, + ]); + // Called once more by something else with nothing new to say but what is left: one, said as one. + last.w.shown.length = 0; + const one = (await last.store.all()).find((e) => e.kind === "message.send") as Entry; + await last.store.put({ ...one, state: "done" }); + await expect(last.w.fire("sync", { tag: "pm-outbox", lastChance: true })).rejects.toThrow("not all sent yet"); + expect(last.w.shown.map((s) => s.options.body)).toEqual(["1 still waiting (open the app to send it)."]); + // With the app open, the app shows what waits itself; without leave to notify, nothing is shown. + const open = await setUp([{ url: `${ORIGIN}/console/#now` }]); + await expect(open.w.fire("sync", { tag: "pm-outbox", lastChance: true })).rejects.toThrow("not all sent yet"); + expect(open.w.shown).toEqual([]); + const quiet = await setUp([], "default"); + await expect(quiet.w.fire("sync", { tag: "pm-outbox", lastChance: true })).rejects.toThrow("not all sent yet"); + expect(quiet.w.shown).toEqual([]); + // The last call with nothing left: only what went. + taken.yes = true; + const clean = await setUp([]); + await clean.w.fire("sync", { tag: "pm-outbox", lastChance: true }); + expect(clean.w.shown.map((s) => s.options.body)).toEqual(["3 sent."]); +}); diff --git a/pm-stack/console/test/work.test.ts b/pm-stack/console/test/work.test.ts index c1e59df215..61f12a12f0 100644 --- a/pm-stack/console/test/work.test.ts +++ b/pm-stack/console/test/work.test.ts @@ -1035,6 +1035,52 @@ describe("the interface's endpoints", () => { expect(bare.w.sqls.flat().filter((s) => s.sql.startsWith("UPDATE tasks SET priority")).length).toBe(2); }); + test("two arrivals under one name at the same moment: one does it, the other is told it is being done", async () => { + const { d, w, audited } = deps(); + d.named = new Named(memoryStore()); + const moves = () => w.sqls.flat().filter((s) => s.sql.startsWith("UPDATE tasks SET priority")).length; + const body = (id: string) => ({ kind: "task.move", args: { task: 21016, to: "first" }, id }); + // The record of what is done is slow to write, which is where two + // arrivals used to pass each other: both had looked, neither had begun. + let open: () => void = () => {}; + const gate = new Promise((r) => { + open = r; + }); + const audit = d.audit; + d.audit = async (e) => { + await gate; + return audit(e); + }; + const id = "0e000000-0000-4000-8000-000000000002"; + const a = handle(post("/console/api/act", body(id)), d); + const b = handle(post("/console/api/act", body(id)), d); + await new Promise((r) => setTimeout(r, 5)); + open(); + const answers = await Promise.all([a, b]); + expect(answers.map((r) => r.status).sort()).toEqual([200, 409]); + const told = await (answers.find((r) => r.status === 409) as Response).json(); + expect(told).toEqual({ error: "This is still being done.", running: true }); + expect(moves()).toBe(1); + expect(audited.filter((e) => e.phase === "start")).toHaveLength(1); + // Asked again once it is over, it is answered from the record. + expect(await (await handle(post("/console/api/act", body(id)), d)).json()).toMatchObject({ ok: true, again: true }); + // An action that could not be recorded is not taken, and its name + // is not left taken either: tried again, it is simply done. + const other = "0e000000-0000-4000-8000-000000000003"; + d.audit = async () => { + throw new Error("disk full"); + }; + const refused = await handle(post("/console/api/act", body(other)), d); + expect([refused.status, await refused.json()]).toEqual([ + 502, + { error: "the action could not be recorded, so it was not taken" }, + ]); + d.audit = audit; + const retried = await handle(post("/console/api/act", body(other)), d); + expect(await retried.json()).toEqual({ ok: true, result: { task: 21016, priority: 10 } }); + expect(moves()).toBe(2); + }); + test("the record of names: what each state means, how many are kept, and a record that cannot be read", async () => { const store = memoryStore(); const named = new Named(store); @@ -1063,6 +1109,12 @@ describe("the interface's endpoints", () => { await failing.begin("d"); await expect(failing.end("d", { ok: true })).rejects.toThrow("disk full"); expect(failing.isRunning("d")).toBe(false); + // A name is taken by one at a time, and given back. + const one = new Named(memoryStore()); + expect([one.take("t"), one.take("t"), one.isRunning("t")]).toEqual([true, false, true]); + expect(await one.seen("t")).toEqual({ state: "running" }); + one.release("t"); + expect([one.isRunning("t"), await one.seen("t"), one.take("t")]).toEqual([false, null, true]); // Three hundred names are kept: the oldest is forgotten first, and // one seen again counts as new. const many = new Named(memoryStore()); @@ -1079,6 +1131,60 @@ describe("the interface's endpoints", () => { expect(await broken.seen("x")).toBeNull(); }); + test("the record of names on a slow disk: read once however many ask together, and no write lands over a later one", async () => { + let content: string | null = JSON.stringify({ old: { ok: true } }); + let reads = 0; + // Each write takes as long as it is told to. + const delays: number[] = []; + const disk = { + read: async () => { + reads++; + await new Promise((r) => setTimeout(r, 5)); + return content; + }, + write: async (text: string) => { + await new Promise((r) => setTimeout(r, delays.shift() ?? 1)); + content = text; + }, + }; + const named = new Named(disk); + // Three ask at the same moment, before the record has been read. + await Promise.all([named.begin("a"), named.begin("b"), named.record("c", { ok: true })]); + expect(reads).toBe(1); + // All three are in the record, with what was there before. + expect(Object.keys(JSON.parse(content as string))).toEqual(["old", "a", "b", "c"]); + expect([named.isRunning("a"), named.isRunning("b")]).toEqual([true, true]); + // One write is slow, and another name is written down while it is + // out: the slow one does not land afterwards, over the newer. + delays.push(12, 1); + const slow = named.record("d", { ok: true }); + await new Promise((r) => setTimeout(r, 3)); + const quick = named.record("e", { ok: true }); + await Promise.all([slow, quick]); + expect(Object.keys(JSON.parse(content as string))).toEqual(["old", "a", "b", "c", "d", "e"]); + // A process started now reads all of them back. + const after = new Named(disk); + expect([await after.seen("a"), await after.seen("c"), await after.seen("e")]).toEqual([ + { state: "lost" }, + { state: "done", fate: { ok: true } }, + { state: "done", fate: { ok: true } }, + ]); + // A write that fails is its own caller's to hear of; the next one is written all the same. + const flaky = { fail: true }; + const kept: string[] = []; + const sometimes = new Named({ + read: async () => null, + write: async (text) => { + if (flaky.fail) throw new Error("disk full"); + kept.push(text); + }, + }); + await expect(sometimes.record("x", { ok: true })).rejects.toThrow("disk full"); + flaky.fail = false; + await sometimes.record("y", { ok: true }); + expect(Object.keys(JSON.parse(kept[kept.length - 1]))).toEqual(["x", "y"]); + }); + test("an action runs, is recorded without the owner's words, and shows in the state", async () => { const { d, w, audited } = deps(); // What an action changes is read again before the answer goes back, From 9e252b2ccfd089211d27ed111355785d6111cba4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:51:37 -0600 Subject: [PATCH 4/6] fix(pm-console): a name keeps to the side that first took it, and "sent" means recorded Two findings from review of the last change, both real. - Which side does a kind can change: the edge is turned away for an hour, then takes the kind back. An action given to the laptop, its answer lost, and sent again after the change was done again by the edge, which had no record of the name; and the other way about. The edge now writes down a name it hands to a machine as given, and looks a name up before choosing a side. - An answer to a question settled in the meantime comes back as a success that says "not recorded". Sent from what the device kept, it was marked sent. It is now "could not be done", with why, as the laptop already says of one it does late. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- ...rchitecture_pm_platform_cloudflare_core.md | 17 ++++- pm-stack/console/README.md | 7 +- pm-stack/console/edge/README.md | 9 +++ pm-stack/console/edge/src/edge.ts | 35 +++++++-- pm-stack/console/public/outbox.js | 21 +++++- pm-stack/console/test/edge.test.ts | 73 ++++++++++++++++++- pm-stack/console/test/outbox.test.ts | 39 ++++++++++ 7 files changed, 187 insertions(+), 14 deletions(-) diff --git a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md index 60ef6fc600..788af88234 100644 --- a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md +++ b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md @@ -480,7 +480,22 @@ found three more of the same kinds. All are fixed in the same change. with no cache at all (a browser that gives the site no storage) the worker installs and answers as if it kept nothing. -Checked: 339 tests under bun, the keeper's 25. 40 planted faults in +A second review of those fixes found two more, both real: + +- **A name could be done once on each side.** Which side does a kind + can change (the edge is turned away for an hour, then takes it + back). An action given to the laptop, its answer lost, and sent again + after the change was done again by the edge, which had no record of + the name; and the other way about. The edge now writes down a name + it hands to a machine as given, and looks a name up before choosing + a side: a name keeps to the side that first took it. +- **A refused answer was counted as sent.** An answer to a question + settled in the meantime comes back as a success that says "not + recorded". Sent from what the device kept, it was marked sent. It is + now "could not be done", with why, as the laptop already says of one + it does late. + +Checked: 341 tests under bun, the keeper's 25. 46 planted faults in the new code, all caught (two more were planted and found to change nothing: each is behind a second guard). In a real Chrome against both demos: the offline flow, light diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 6326d5c762..63ff1b0212 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -208,7 +208,12 @@ the Android app alike (which is the same site in Chrome). never came is safe: Cloudflare keeps the names it did (a week, three hundred), and a machine keeps its own (`src/named.ts`). A name is taken by one arrival at a time: a second one while the first is still - being done is told so, and asks again. + being done is told so, and asks again. And a name keeps to the side + that first took it, Cloudflare or a machine, whichever would be + chosen for it later. +- **"Sent" means recorded.** An answer the platform took and did not + record (a question that was settled in the meantime) is not counted + as sent: it is listed under "could not be done", with why. - **In the order it was done.** Something done now goes behind whatever is already waiting, oldest first, and is not sent ahead of it. Two about the same thing (an issue ranked twice, a task moved twice) keep diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index 78c10bb2a3..f147fed566 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -344,6 +344,15 @@ open nothing. waits once. A name is taken by one arrival at a time, here and on the laptop, before anything else is waited for: of two that arrive together one does it and the other is told it is being done. +- A name keeps to the side that first took it. What the edge hands to + a machine it writes down as given, under the name; sent again, it + goes to a machine again, even if the edge would do that kind itself + by then, and what the edge did is answered from the edge's record + even if it would hand that kind over by then. Chosen afresh each + time, a name whose answer was lost while the choice changed could be + done once on each side. The cost: something that may not be done + late, given to a machine that then cannot be reached, stays the + machine's (the edge cannot know whether it was done). - What is done late is done in the order the owner did it. An action that may be held goes behind an earlier one about the same thing (the same issue, task, reference or set of questions) that a machine has diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 0405811513..cdb03c6ce1 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -184,7 +184,9 @@ const ACTED_BODY_CHARS = 4000; interface Acted { at: number; kind: string; - state: "running" | "done"; + /** "given": handed to a machine under this name. Nothing was done + * here, and only the machine knows what became of it. */ + state: "running" | "done" | "given"; status?: number; body?: Record; } @@ -1533,11 +1535,21 @@ export class Edge { // console's own classes, and is never sent to a machine, so no // machine can do it a second time. Otherwise it is a machine's // to do. - if ( - (DIRECT_ACTIONS as readonly string[]).includes(kind) && - this.primary(cfg) && - !this.refusedKinds().includes(kind) - ) { + // A name keeps to the side that first took it, whatever would + // be chosen for it today. What this side did is answered from + // its record; what was given to a machine goes to a machine + // again, which has its own. Chosen afresh each time, a name + // whose answer was lost while the choice changed (this side was + // turned away for an hour, say) would be done once on each side. + const before = id === null ? null : (((await this.kv.get(`a:${id}`)) as Acted | undefined) ?? null); + const given = before?.state === "given"; + const here = + before !== null + ? !given + : (DIRECT_ACTIONS as readonly string[]).includes(kind) && + this.primary(cfg) && + !this.refusedKinds().includes(kind); + if (here) { try { return await this.once(id, kind, () => this.directAct(kind, args as Record, by, who.via, id), @@ -1547,6 +1559,11 @@ export class Edge { if (!(error instanceof HandOver)) throw error; } } + // Written down as a machine's before it goes anywhere. + if (id !== null && !given) { + await this.kv.put(`a:${id}`, { at: this.now(), kind, state: "given" } satisfies Acted); + await this.actedIndex(id); + } // What may be done late goes behind anything already waiting // for a machine that is about the same thing. Sent straight to // a machine that has just come back, it would be done before @@ -1646,7 +1663,11 @@ export class Edge { /** Note a name as used, and forget the ones that are too old or too many. */ private async actedIndex(id: string): Promise { const now = this.now(); - const index = ((await this.kv.get("acted")) as { id: string; at: number }[] | undefined) ?? []; + // Once in the list, however often it is noted (a name given to a + // machine after this side was turned away is noted twice). + const index = (((await this.kv.get("acted")) as { id: string; at: number }[] | undefined) ?? []).filter( + (entry) => entry.id !== id, + ); index.push({ id, at: now }); const keep = index.filter((entry) => now - entry.at < ACTED_FOR_MS).slice(-ACTED_KEPT); const kept = new Set(keep.map((entry) => entry.id)); diff --git a/pm-stack/console/public/outbox.js b/pm-stack/console/public/outbox.js index 4f01ab80dc..6141c38fcd 100644 --- a/pm-stack/console/public/outbox.js +++ b/pm-stack/console/public/outbox.js @@ -166,9 +166,24 @@ return { state: "waiting", note: "Sign in again to send this.", stop: true, signin: true }; } if (status === 200 && body.ok === true) { - return body.held === true - ? { state: "held", note: "Kept for the laptop, which will do it when it is back.", result: null } - : { state: "done", note: "", result: body.result ?? null }; + if (body.held === true) { + return { state: "held", note: "Kept for the laptop, which will do it when it is back.", result: null }; + } + // Taken, and answered "not recorded" without an error: an answer + // to a question that was settled in the meantime. That is not + // "sent", and it is said as what it is (the laptop says the same + // of one it does late). + const refused = Array.isArray(body.result?.refused) ? body.result.refused : []; + if (refused.length > 0) { + const why = String(refused[0]?.why ?? "no reason given"); + const applied = Number(body.result?.applied) || 0; + return { + state: "failed", + note: applied > 0 ? `${applied} recorded, ${refused.length} not recorded: ${why}` : `Not recorded: ${why}`, + result: body.result, + }; + } + return { state: "done", note: "", result: body.result ?? null }; } const why = typeof body.error === "string" && body.error !== "" ? body.error : `http ${status}`; // Being done right now under this name: ask again shortly. diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 66cdbba33a..d46da5d2d3 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -3239,12 +3239,81 @@ describe("the edge does the core itself", () => { w.ghRefuses.push((method, url) => method === "PUT" && url.includes("/merge")); const first = await w.act("pr.merge", { pr: 55 }, id); expect(await first.json()).toMatchObject({ ok: true, result: { merged: 55 } }); - // Nothing was done here, so nothing is written down here under the name ... - expect(w.stored.has(`a:${id}`)).toBe(false); + // Nothing was done here: what is written down under the name is + // that it was given to a machine ... + expect(w.stored.get(`a:${id}`)).toMatchObject({ kind: "pr.merge", state: "given" }); // ... and sent again, it goes to the laptop, which knows it did it. const second = await w.act("pr.merge", { pr: 55 }, id); expect(await second.json()).toMatchObject({ ok: true, result: { merged: 55 }, again: true }); expect(w.ran).toEqual([{ kind: "pr.merge", args: { pr: 55 } }]); + // Noted once in the list of names, though it was noted twice. + expect((w.stored.get("acted") as { id: string }[]).filter((e) => e.id === id)).toHaveLength(1); + }); + + test("a name keeps to the side that first took it: given to the laptop, it is not done here later, and done here, it is not given to the laptop later", async () => { + const w = await primary(); + const merge = (method: string, url: string) => method === "PUT" && url.includes("/merge"); + const comment = (method: string, url: string) => method === "POST" && /\/issues\/\d+\/comments$/.test(url); + const posted = () => w.githubCalls.filter((c) => comment(c.method, c.url)).length; + // This side is turned away for comments, so one goes to the laptop, + // which posts it; and its answer is lost on the way back. + w.ghRefuses.push(comment); + const given = "0d000000-0000-4000-8000-000000000001"; + w.net.loseAnswer = true; + const first = await w.act("issue.comment", { issue: 7, text: "once, by the laptop" }, given); + w.net.loseAnswer = false; + expect(await first.json()).toMatchObject({ ok: true, held: true }); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + const before = posted(); + // The token is put right and this side takes comments back. + w.ghRefuses.length = 0; + expect((await w.act("edge.retry", {})).status).toBe(200); + expect(((await (await w.browse("/console/health")).json()) as { refused: string[] }).refused).toEqual([]); + // The device never heard, and sends the comment again under its name. + // It is the laptop's: this side does not post it. + const again = await w.act("issue.comment", { issue: 7, text: "once, by the laptop" }, given); + expect(await again.json()).toMatchObject({ ok: true }); + expect(posted()).toBe(before); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + // A new comment, under a new name, is this side's again. + const fresh = await w.act("issue.comment", { issue: 7, text: "a new one" }, "0d000000-0000-4000-8000-000000000002"); + expect(await fresh.json()).toMatchObject({ ok: true }); + expect(posted()).toBe(before + 1); + expect(w.ran.filter((r) => r.kind === "issue.comment")).toHaveLength(1); + + // Something that may not be done late, given to the laptop the same + // way: its answer lost, the device is told it is not known ... + w.ghRefuses.push(merge); + const merged = "0d000000-0000-4000-8000-000000000003"; + w.net.loseAnswer = true; + const lost = await w.act("pr.merge", { pr: 55 }, merged); + w.net.loseAnswer = false; + expect(lost.status).toBe(503); + expect(w.ran.filter((r) => r.kind === "pr.merge")).toHaveLength(1); + w.ghRefuses.length = 0; + await w.act("edge.retry", {}); + // ... and asking again under the name reaches the laptop, which + // says it merged it. This side never asks GitHub to merge. + const asked = await w.act("pr.merge", { pr: 55 }, merged); + expect(await asked.json()).toMatchObject({ ok: true, result: { merged: 55 }, again: true }); + expect(w.ghMerged).toEqual([]); + expect(w.ran.filter((r) => r.kind === "pr.merge")).toHaveLength(1); + + // The other way about: done here, then this side is turned away for + // the kind. The name is still answered from here, and the laptop is + // not asked to do it. + const here = "0d000000-0000-4000-8000-000000000004"; + const done = await w.act("issue.rank", { issue: 301, rank: "next" }, here); + expect(await done.json()).toMatchObject({ ok: true }); + w.ghRefuses.push((method) => method !== "GET"); + const turned = await w.act("issue.rank", { issue: 201, rank: "next" }, "0d000000-0000-4000-8000-000000000005"); + expect(turned.status).not.toBe(200); + expect(((await (await w.browse("/console/health")).json()) as { refused: string[] }).refused).toContain( + "issue.rank", + ); + const repeat = await w.act("issue.rank", { issue: 301, rank: "next" }, here); + expect(await repeat.json()).toMatchObject({ ok: true, again: true }); + expect(w.ran.filter((r) => r.kind === "issue.rank")).toEqual([]); }); test("the names remembered here are bounded: the oldest are forgotten, and an answer too long to keep is kept as how it went", async () => { diff --git a/pm-stack/console/test/outbox.test.ts b/pm-stack/console/test/outbox.test.ts index d7ecd6d32b..abc82ba6bb 100644 --- a/pm-stack/console/test/outbox.test.ts +++ b/pm-stack/console/test/outbox.test.ts @@ -221,6 +221,45 @@ test("what each kind of answer does to an entry", () => { } }); +test("an answer the platform took and did not record is not counted as sent", async () => { + // The question was settled before the answer kept on the device got there. + const settled = { applied: 0, refused: [{ qid: "q1", why: "already-resolved" }] }; + expect(O.classify({ status: 200, body: { ok: true, result: settled } })).toEqual({ + state: "failed", + note: "Not recorded: already-resolved", + result: settled, + }); + // Some of a set recorded, some not: said as both. + const part = { applied: 2, refused: [{ qid: "q3", why: "already-resolved" }, { qid: "q4" }] }; + expect(O.classify({ status: 200, body: { ok: true, result: part } })).toMatchObject({ + state: "failed", + note: "2 recorded, 2 not recorded: already-resolved", + }); + expect(O.classify({ status: 200, body: { ok: true, result: { applied: 0, refused: [{}] } } }).note).toBe( + "Not recorded: no reason given", + ); + // Answered again from the platform's record, it is said the same. + expect(O.classify({ status: 200, body: { ok: true, result: settled, again: true } }).state).toBe("failed"); + // Nothing refused is plain success, whatever else the result says. + for (const result of [{ applied: 1, refused: [] }, { applied: 1 }, { refused: "no" }, null, "text", 7]) { + expect([result, O.classify({ status: 200, body: { ok: true, result } }).state]).toEqual([result, "done"]); + } + // Sent from what was kept: it ends as "could not be done", with why, and is said so. + const store = O.memoryStore(); + await store.put(O.make("question.answer", { set: "s1", qid: "q1", option: "a" }, T0)); + await store.put(O.make("ask.send", { text: "x" }, T0 + 1)); + const out = await O.flush( + store, + async (e) => (e.kind === "question.answer" ? { status: 200, body: { ok: true, result: settled } } : ok()), + () => T0 + 2, + ); + expect(out.changed.map((e) => [e.kind, e.state, e.note])).toEqual([ + ["question.answer", "failed", "Not recorded: already-resolved"], + ["ask.send", "done", ""], + ]); + expect(O.summary(await store.all())).toMatchObject({ failed: 1, done: 1, open: 1 }); +}); + test("a timely action is sent by itself only while it is fresh, or once the owner has looked again", () => { const merge = O.make("pr.merge", { pr: 55 }, T0); expect(O.due(merge, T0)).toBe(true); From c5c1a1db74f96ddd6f38aea2d8eaf744a6cb5667 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 10:10:38 -0600 Subject: [PATCH 5/6] fix(pm-console): write an action down before it waits its turn; show a question again when its answer is taken back Two findings from review, both real, both in the page. - An action was written down only once it held the turn to send. With another tab or the worker in the middle of a slow send, closing the page lost it. It is written down first, and only the sending waits. One try at sending is given a minute, so a request that hangs cannot hold every sender up. - The page kept its own list of questions answered here, and "do not send" did not clear it: the question stayed hidden. The list is now worked out from what is kept, so a question is out of the list while its answer waits (across a reload too) and back when the answer is taken back or does not count. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- ...rchitecture_pm_platform_cloudflare_core.md | 20 ++- pm-stack/console/README.md | 9 +- pm-stack/console/public/app.js | 117 ++++++++++++------ pm-stack/console/public/outbox.js | 14 ++- pm-stack/console/test/app.test.ts | 27 ++++ pm-stack/console/test/outbox.test.ts | 27 +++- 6 files changed, 171 insertions(+), 43 deletions(-) diff --git a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md index 788af88234..759dd9bf75 100644 --- a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md +++ b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md @@ -495,13 +495,29 @@ A second review of those fixes found two more, both real: now "could not be done", with why, as the laptop already says of one it does late. -Checked: 341 tests under bun, the keeper's 25. 46 planted faults in +A third review found two more, both real, both in the page: + +- **An action waited its turn in memory.** It was written down only + once it held the turn to send; with another tab or the worker in the + middle of a slow send, closing the page lost it. It is now written + down first, and only the sending waits. One try at sending is given a + minute, so a request that hangs cannot hold every sender up. +- **A taken-back answer left its question hidden.** The page kept its + own list of questions answered here. The list is now worked out from + what is kept: a question is out of the list while its answer waits + (across a reload too) and back when the answer is taken back or does + not count. + +Checked: 342 tests under bun, the keeper's 25. 52 planted faults in the new code, all caught (two more were planted and found to change nothing: each is behind a second guard). In a real Chrome against both demos: the offline flow, light and dark; the worker woken with the app closed; an older waiting rank and a new one leave the device in order and are done in order (and with -the old direct send planted, that check fails); axe-core over 20 +the old direct send planted, that check fails); an answer kept, taken +back and kept again, and an action done while another sender holds the +turn and the page then closed (each fails against the code before its +fix); axe-core over 20 screens, the dialogs and the toasts: no violations. The Worker in its real runtime passes its own checks. diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 63ff1b0212..04cc39087e 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -200,7 +200,9 @@ the Android app alike (which is the same site in Chrome). "Keep a copy of every screen now", for before a flight. - **What the owner does is kept and sent once.** Every action is given a name on the device (a UUID) and written to the browser's own - database before it is sent (`public/outbox.js`). With no connection it + database before it is sent (`public/outbox.js`), and before it waits + its turn behind a send already under way, so a page closed meanwhile + loses nothing. One try is given a minute. With no connection it waits there, and is sent when the connection is back: by the page if the app is open, by the service worker if it is not (Background Sync, where the browser has it). The platform does an action once under its @@ -213,7 +215,10 @@ the Android app alike (which is the same site in Chrome). chosen for it later. - **"Sent" means recorded.** An answer the platform took and did not record (a question that was settled in the meantime) is not counted - as sent: it is listed under "could not be done", with why. + as sent: it is listed under "could not be done", with why. A question + is left out of the list while its answer is kept and not yet + recorded, across a reload too, and is shown again if the answer is + taken back or does not count. - **In the order it was done.** Something done now goes behind whatever is already waiting, oldest first, and is not sent ahead of it. Two about the same thing (an issue ranked twice, a task moved twice) keep diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index a40c1480d4..b41887926d 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -237,19 +237,32 @@ async function loadDoc(name) { return true; } -/** Questions answered on this device that the list may still show for a - * while: the answer is on its way, or held until the laptop is back. */ -const answeredHere = new Set(); +/** Answers being sent this moment, by their question. */ +const sendingAnswers = new Set(); const questionKey = (q) => `${q.set}|${q.ledger}|${q.qid}`; +/** Questions answered on this device whose answer has not been + * recorded yet: it is on its way, waits here for a connection, or is + * held for a machine. The list may still show them for a while, and + * they are left out of it. It is worked out from what is kept, so one + * whose answer the owner took back, or that turned out not to count, + * is shown again, and one still waiting stays out after a reload. */ +export function answeredKeys(entries, sending = []) { + const keys = new Set(sending); + for (const e of entries || []) { + if ((e.kind === "question.answer" || e.kind === "question.defer") && (e.state === "waiting" || e.state === "held")) { + keys.add(questionKey(e.args || {})); + } + } + return keys; +} + function withoutAnswered(doc) { const q = doc?.questions; if (!q?.open) return; - const present = new Set(q.open.map(questionKey)); - // Gone from the list: the answer arrived, and there is nothing to hide. - for (const key of answeredHere) if (!present.has(key)) answeredHere.delete(key); - if (answeredHere.size === 0) return; - q.open = q.open.filter((x) => !answeredHere.has(questionKey(x))); + const hidden = answeredKeys(kept, sendingAnswers); + if (hidden.size === 0) return; + q.open = q.open.filter((x) => !hidden.has(questionKey(x))); q.total = q.open.length; } @@ -265,11 +278,30 @@ const KEPT_NOTE = "Kept on this device. It is sent when you are connected."; /** Read what is kept, for the line that says so and the screen that lists it. */ async function readKept() { if (!outbox) return []; + const before = answeredKeys(kept); try { kept = (await outbox.all()).sort((a, b) => b.at - a.at); } catch { // The list as it was is better than none. } + const now = answeredKeys(kept); + if (docs.questions) { + if ([...before].some((key) => !now.has(key))) { + // An answer that was waiting and no longer is (recorded, taken + // back, or refused): the questions are read again whole, so that + // one still open is shown again. (The copy here had it taken out.) + etags.questions = null; + loadDoc("questions").then( + () => draw(), + () => {}, + ); + } else if ([...now].some((key) => !before.has(key))) { + // One found waiting that the list was read without (the list + // came first, at start-up): taken out of it now. + withoutAnswered(docs.questions); + draw(); + } + } drawKept(); return kept; } @@ -331,36 +363,41 @@ function flushOutbox() { async function submit(kind, args) { if (!Outbox) return { state: "refused", note: "This page cannot send that." }; const entry = Outbox.make(kind, args, Date.now()); - // Under the lock a send of what is waiting takes (here or in the - // service worker): while this is written down and not yet answered, - // nothing else may take it for something left waiting and send it too. - // (If one did, the platform would still do it once; the owner would - // be told twice.) - const work = () => submitNow(entry); - return navigator.locks?.request ? navigator.locks.request("pm-outbox", work) : work(); -} - -async function submitNow(entry) { - // Sent by itself, behind nothing: what needs a connection by its - // nature (it is not written down), or everything, in a browser that - // will not let this page keep anything. - const direct = async () => { - const answer = await Outbox.httpSend(entry); - const out = Outbox.classify(answer); - if (out.state === "done") return { state: "done", result: out.result }; - if (out.state === "held") return { state: "held" }; - if (out.state === "failed") return { state: "failed", note: out.note }; - if (out.signin) signedOut = true; - return { state: "refused", note: answer.network ? "This needs a connection." : out.signin ? NO_SIGNIN : out.note }; - }; - if (Outbox.rule(entry.kind) === "now" || outbox === null) return direct(); + // What needs a connection by its nature is sent by itself. It is not + // written down, so nothing else can take it for something waiting. + if (Outbox.rule(entry.kind) === "now" || outbox === null) return sendAlone(entry); + // Written down before anything is waited for, its turn to be sent + // included: another tab or the service worker may be in the middle of + // a slow send, and a page closed while this waited its turn would + // take what the owner did with it. try { await outbox.put(entry); } catch { - return direct(); + // A browser that will not let this page keep anything. + return sendAlone(entry); } - // It goes behind whatever is already waiting, in the order things - // were done (outbox.js says why). + // Sent under the lock a send of what is waiting takes, here or in the + // service worker: one sender at a time, in the order things were done. + // (If another sender takes this one first, the platform still does it + // once, and this finds it done.) + const work = () => sendKept(entry); + return navigator.locks?.request ? navigator.locks.request("pm-outbox", work) : work(); +} + +/** Sent by itself, behind nothing, and kept nowhere. */ +async function sendAlone(entry) { + const answer = await Outbox.httpSend(entry); + const out = Outbox.classify(answer); + if (out.state === "done") return { state: "done", result: out.result }; + if (out.state === "held") return { state: "held" }; + if (out.state === "failed") return { state: "failed", note: out.note }; + if (out.signin) signedOut = true; + return { state: "refused", note: answer.network ? "This needs a connection." : out.signin ? NO_SIGNIN : out.note }; +} + +/** Sent in its turn: behind whatever is already waiting, in the order + * things were done (outbox.js says why). */ +async function sendKept(entry) { let did; try { did = await Outbox.sendInOrder(outbox, entry.id, (e) => Outbox.httpSend(e)); @@ -680,13 +717,19 @@ function flushPending() { } async function sendAnswer(kind, args, key, said) { - const out = await submit(kind, args); - await readKept(); + // Out of the list while it is on its way, whatever is read meanwhile. + sendingAnswers.add(key); + let out; + try { + out = await submit(kind, args); + await readKept(); + } finally { + sendingAnswers.delete(key); + } if (out.state === "failed" || out.state === "refused") toast(out.note, true); else { if (out.result?.refused?.length) toast(`Not recorded: ${out.result.refused[0].why}`, true); else { - answeredHere.add(key); // A choice was already acknowledged when it was made (with its // Undo); anything else says so now, or the question would simply // vanish. diff --git a/pm-stack/console/public/outbox.js b/pm-stack/console/public/outbox.js index 6141c38fcd..9eee14325a 100644 --- a/pm-stack/console/public/outbox.js +++ b/pm-stack/console/public/outbox.js @@ -354,6 +354,14 @@ return changed; } + /** How long one try may take before it is given up on. A request + * that hung would otherwise hold up everything behind it, in every + * tab and in the worker, for as long as it hung. Given up on is not + * "not done": it is offered again under its name, and the platform + * does it once. */ + const SEND_WAIT_MS = 60_000; + const gaveUp = (error) => error?.name === "TimeoutError" || error?.name === "AbortError"; + /** One try at sending an entry to the platform. */ async function httpSend(entry, fetchImpl = root.fetch.bind(root)) { let res; @@ -366,6 +374,7 @@ // site. It is not followed: it is how this is told from no // connection at all. redirect: "manual", + ...(root.AbortSignal?.timeout ? { signal: root.AbortSignal.timeout(SEND_WAIT_MS) } : {}), }); } catch { return { network: true }; @@ -374,7 +383,9 @@ let body = null; try { body = await res.json(); - } catch { + } catch (error) { + // Given up on part-way through the answer: no answer at all. + if (gaveUp(error)) return { network: true }; body = null; } // No sign-in, whoever says so; or refused by something in between @@ -430,6 +441,7 @@ root.PMOutbox = { TIMELY_MS, + SEND_WAIT_MS, rule, subject, sayOf, diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index 53eb9312f4..a283de76c5 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -7,6 +7,7 @@ import { readFileSync } from "node:fs"; import { ago, androidSource, + answeredKeys, awayNotice, awayState, band, @@ -729,3 +730,29 @@ test("what the owner is told of something just done, from what became of it when note: "It was taken back before it was sent.", }); }); + +test("a question is left out of the list while its answer is kept and not yet recorded, and is shown again when the answer is taken back", () => { + const answer = (qid: string, state: string, kind = "question.answer") => ({ + kind, + state, + args: { set: "s1", ledger: "l1", qid, option: "a" }, + }); + // Waiting for a connection, or with the platform for a machine: left out. + expect([ + ...answeredKeys([answer("q1", "waiting"), answer("q2", "held"), answer("q3", "waiting", "question.defer")]), + ]).toEqual(["s1|l1|q1", "s1|l1|q2", "s1|l1|q3"]); + // Recorded, refused, or kept back: nothing to leave out any more. + expect([...answeredKeys([answer("q1", "done"), answer("q2", "failed"), answer("q3", "stale")])]).toEqual([]); + // Taken back by the owner, the entry is gone, and so is the reason to hide the question. + expect([...answeredKeys([])]).toEqual([]); + expect([...answeredKeys(null)]).toEqual([]); + // Other things that are kept are not answers. + expect([ + ...answeredKeys([ + { kind: "ask.send", state: "waiting", args: { text: "x" } }, + { kind: "questions.accept", state: "waiting", args: { set: "s1" } }, + ]), + ]).toEqual([]); + // One being sent this moment is left out too, with what is kept. + expect([...answeredKeys([answer("q1", "waiting")], ["s1|l1|q9"])]).toEqual(["s1|l1|q9", "s1|l1|q1"]); +}); diff --git a/pm-stack/console/test/outbox.test.ts b/pm-stack/console/test/outbox.test.ts index abc82ba6bb..c3284a56d9 100644 --- a/pm-stack/console/test/outbox.test.ts +++ b/pm-stack/console/test/outbox.test.ts @@ -33,6 +33,7 @@ interface Store { } const O = (globalThis as unknown as { PMOutbox: Record }).PMOutbox as { TIMELY_MS: number; + SEND_WAIT_MS: number; rule(kind: string): "late" | "timely" | "now"; subject(kind: string, args?: unknown): string | null; sayOf(kind: string, args?: unknown): string; @@ -827,12 +828,36 @@ test("one try at sending: what goes out, and how each kind of answer is read", a // It goes as the app's own writes do, under its name, and the way to // a sign-in page is not followed. expect(calls[0].url).toBe("/console/api/act"); - expect(calls[0].init).toEqual({ + const { signal, ...sent } = calls[0].init; + expect(sent).toEqual({ method: "POST", headers: { "Content-Type": "application/json", "X-PM-Console": "1" }, body: JSON.stringify({ kind: "ask.send", args: { text: "hello" }, id: entry.id }), redirect: "manual", }); + // One try is given a minute and no longer: a request that hung would + // hold up everything behind it, in every tab and in the worker. + expect(O.SEND_WAIT_MS).toBe(60_000); + expect(signal).toBeInstanceOf(AbortSignal); + expect((signal as AbortSignal).aborted).toBe(false); + // Given up on, before any answer or part-way through one, is no + // answer: it is offered again under its name. + const late = (name: string) => Object.assign(new Error("The operation timed out."), { name }); + expect( + await O.httpSend(entry, async () => { + throw late("TimeoutError"); + }), + ).toEqual({ network: true }); + for (const name of ["TimeoutError", "AbortError"]) { + const cut = { + status: 200, + type: "basic", + json: async () => { + throw late(name); + }, + }; + expect(await O.httpSend(entry, answering(cut))).toEqual({ network: true }); + } // No answer. expect( await O.httpSend(entry, async () => { From bd1d03fb2af68ab747a28afc8da4cb6e5fe6f236 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 10:31:58 -0600 Subject: [PATCH 6/6] fix(pm-console): keep what is being typed through a background send; a cut-off answer is retried Three findings from review, all real. - When something kept earlier was sent, the screen was drawn again whatever the owner was doing, and a bug report, a note or a message half typed was gone. A background send now draws the screen again only when nobody is in the middle of something, and those three forms keep what is typed across any redraw. - An answer whose body stops arriving part-way was read as "sign in again", which also stopped the worker from asking to be woken again. It is no answer, and is offered again. - A failed answer could leave its question hidden if the list was read while the answer was on its way. On failure the list is read again whole. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- ...rchitecture_pm_platform_cloudflare_core.md | 20 ++++- pm-stack/console/README.md | 8 +- pm-stack/console/public/app.js | 77 +++++++++++++------ pm-stack/console/public/outbox.js | 9 ++- pm-stack/console/test/outbox.test.ts | 16 +++- 5 files changed, 97 insertions(+), 33 deletions(-) diff --git a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md index 759dd9bf75..d79a493dd0 100644 --- a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md +++ b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md @@ -508,6 +508,22 @@ A third review found two more, both real, both in the page: (across a reload too) and back when the answer is taken back or does not count. +A fourth review found three more, all real: + +- **A draft was erased by a send in the background.** When something + kept earlier was sent, the screen was drawn again whatever the owner + was doing, and a bug report, a note or a message half typed was + gone. A background send now draws the screen again only when nobody + is in the middle of something, and those three forms keep what is + typed across any redraw (as the prompt box already did). +- **A cut-off answer was read as "sign in again".** An answer whose + body stops arriving is no answer, and is offered again; only a body + that arrives and is not JSON is taken for something other than the + platform. +- **A failed answer could leave its question hidden**, if the list was + read while the answer was on its way. On failure the list is read + again whole. + Checked: 342 tests under bun, the keeper's 25. 52 planted faults in the new code, all caught (two more were planted and found to change nothing: each is behind a second guard). In a real Chrome against both @@ -516,7 +532,9 @@ and dark; the worker woken with the app closed; an older waiting rank and a new one leave the device in order and are done in order (and with the old direct send planted, that check fails); an answer kept, taken back and kept again, and an action done while another sender holds the -turn and the page then closed (each fails against the code before its +turn and the page then closed; a draft kept through a background send +with the cursor in it and with it set aside, and a question back after +its answer failed (each of these fails against the code before its fix); axe-core over 20 screens, the dialogs and the toasts: no violations. The Worker in its real runtime passes its own checks. diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 04cc39087e..d4f6463843 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -202,7 +202,9 @@ the Android app alike (which is the same site in Chrome). a name on the device (a UUID) and written to the browser's own database before it is sent (`public/outbox.js`), and before it waits its turn behind a send already under way, so a page closed meanwhile - loses nothing. One try is given a minute. With no connection it + loses nothing. One try is given a minute, and an answer that stops + arriving part-way is no answer (it is offered again, never taken for + a sign-in that ran out). With no connection it waits there, and is sent when the connection is back: by the page if the app is open, by the service worker if it is not (Background Sync, where the browser has it). The platform does an action once under its @@ -219,6 +221,10 @@ the Android app alike (which is the same site in Chrome). is left out of the list while its answer is kept and not yet recorded, across a reload too, and is shown again if the answer is taken back or does not count. +- **What is being typed is not lost to a send in the background.** A + bug report, a note or a message half written stays where it is when + something kept earlier gets sent and the screen is drawn again; it is + let go when it is sent. - **In the order it was done.** Something done now goes behind whatever is already waiting, oldest first, and is not sent ahead of it. Two about the same thing (an issue ranked twice, a task moved twice) keep diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index b41887926d..2562cda6e6 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -336,7 +336,9 @@ function flushOutbox() { const said = flushSaid(out.changed); if (said) { toast(said, out.changed.some((e) => e.state === "failed")); - refresh(true); + // Not from under someone in the middle of typing: this was not + // their doing, and can wait for them. + refresh("idle"); } }; try { @@ -726,17 +728,20 @@ async function sendAnswer(kind, args, key, said) { } finally { sendingAnswers.delete(key); } - if (out.state === "failed" || out.state === "refused") toast(out.note, true); - else { - if (out.result?.refused?.length) toast(`Not recorded: ${out.result.refused[0].why}`, true); - else { - // A choice was already acknowledged when it was made (with its - // Undo); anything else says so now, or the question would simply - // vanish. - if (out.state === "held") toast(HELD_NOTE); - else if (out.state === "kept") toast(out.note); - else if (said) toast(said); - } + if (out.state === "failed" || out.state === "refused") { + toast(out.note, true); + // The question is still open. If the list was read while the answer + // was on its way, the question was taken out of that copy: the list + // is read again whole, so that it is there to answer again. + etags.questions = null; + await loadDoc("questions").catch(() => {}); + } else { + // A choice was already acknowledged when it was made (with its + // Undo); anything else says so now, or the question would simply + // vanish. + if (out.state === "held") toast(HELD_NOTE); + else if (out.state === "kept") toast(out.note); + else if (said) toast(said); picks.delete(key); if (docs.questions?.questions) { const open = docs.questions.questions.open.filter((q) => `${q.set}|${q.ledger}|${q.qid}` !== key); @@ -1642,10 +1647,31 @@ async function viewRoadmap(sub) { return out; } +/** What is being typed in a form, by the form. A screen is drawn again + * whenever something it shows changes, and when what was kept gets + * sent: what was typed and not yet sent is put back, and let go when + * it is sent. */ +const typing = new Map(); +function typed(key, attrs) { + const box = h("textarea", { ...attrs, oninput: (e) => typing.set(key, e.target.value) }); + box.value = typing.get(key) ?? ""; + return box; +} +/** Send what was typed in a form: let go of before it is sent (the + * screen is drawn again when it goes), and put back if it did not go. */ +async function sendTyped(key, box, send) { + const words = box.value; + typing.delete(key); + const sent = await send(words); + if (sent) box.value = ""; + else typing.set(key, words); + return sent; +} + /** Bugs: report one in a sentence; what is open, soonest first; what was fixed lately. */ async function viewBugs() { const [caps, bugs] = await Promise.all([capabilityList(), api(freshly("bugs"))]); - const words = h("textarea", { rows: 4, maxlength: 8000, "aria-label": "What went wrong", placeholder: "What went wrong, and what you expected" }); + const words = typed("bug", { rows: 4, maxlength: 8000, "aria-label": "What went wrong", placeholder: "What went wrong, and what you expected" }); const where = h( "select", { "aria-label": "Where" }, @@ -1665,8 +1691,7 @@ async function viewBugs() { const report = async (e) => { if (!words.value.trim()) return toast("Say what went wrong first", true); const form = { text: words.value, area: where.value, rank: soon.value, session: session.checked }; - const sent = await act("intake.send", { id: newId(), ...intakeArgs({ kind: "bug" }, form) }, intakeSaid, e.target); - if (sent) words.value = ""; + await sendTyped("bug", words, () => act("intake.send", { id: newId(), ...intakeArgs({ kind: "bug" }, form) }, intakeSaid, e.target)); }; return [ card( @@ -1691,7 +1716,7 @@ const KIND_SAID = { bug: "Bug", note: "Note", session: "Session", change: "Chang /** Intake: everything that was said through the app, where it went, and how it stands. */ async function viewIntake() { const [caps, list] = await Promise.all([capabilityList(), api(freshly("intake"))]); - const words = h("textarea", { rows: 3, maxlength: 8000, "aria-label": "A note", placeholder: "A note, an idea, a change of mind" }); + const words = typed("note", { rows: 3, maxlength: 8000, "aria-label": "A note", placeholder: "A note, an idea, a change of mind" }); const where = h( "select", { "aria-label": "About" }, @@ -1702,8 +1727,7 @@ async function viewIntake() { const send = async (e) => { if (!words.value.trim()) return toast("Write the note first", true); const form = { text: words.value, area: where.value, session: session.checked }; - const sent = await act("intake.send", { id: newId(), ...intakeArgs({ kind: "note" }, form) }, intakeSaid, e.target); - if (sent) words.value = ""; + await sendTyped("note", words, () => act("intake.send", { id: newId(), ...intakeArgs({ kind: "note" }, form) }, intakeSaid, e.target)); }; const titleOf = (id) => caps.find((c) => c.id === id)?.title || id; return [ @@ -2491,7 +2515,7 @@ function viewIssues() { async function viewAgents() { const agents = docs.ops?.agents || []; const to = h("select", { "aria-label": "To" }, h("option", { value: "all" }, "Everyone"), agents.map((a) => h("option", { value: `agent:${a.name}` }, a.name))); - const text = h("textarea", { rows: 3, placeholder: "A message, or a command to act on", "aria-label": "Message" }); + const text = typed("message", { rows: 3, placeholder: "A message, or a command to act on", "aria-label": "Message" }); const command = h("input", { type: "checkbox", id: "cmd" }); const compose = card( to, @@ -2504,7 +2528,9 @@ async function viewAgents() { "button", { onclick: (e) => - text.value.trim() ? act("message.send", { to: [to.value], text: text.value, command: command.checked }, "Sent", e.target) : toast("Write a message first", true), + text.value.trim() + ? sendTyped("message", text, (words) => act("message.send", { to: [to.value], text: words, command: command.checked }, "Sent", e.target)) + : toast("Write a message first", true), }, "Send", ), @@ -2800,9 +2826,12 @@ async function refresh(force) { if (!docs.core) loadError = error.message; } drawKept(); - // An open dialog or a half-typed answer is not redrawn from under the reader. + // An open dialog or a half-typed answer is not redrawn from under the + // reader, unless it is the reader who asked (`force` is true). + // "idle" asks for the screen to be drawn again whether or not what + // it shows changed, but only when nobody is in the middle of something. const busy = $("ask").open || pending.size > 0 || (document.activeElement && ["TEXTAREA", "INPUT", "SELECT"].includes(document.activeElement.tagName)); - if (force || (changed && !busy)) draw(); + if (force === true || ((changed || force === "idle") && !busy)) draw(); else { drawTabs(); drawFresh(); @@ -2849,14 +2878,14 @@ if (typeof document !== "undefined" && view) { const changed = Array.isArray(event.data.changed) ? event.data.changed : []; const said = flushSaid(changed); if (said) toast(said, changed.some((e) => e.state === "failed")); - readKept().then(() => changed.length && refresh(true)); + readKept().then(() => changed.length && refresh("idle")); }); // The worker has just taken this page over. What the page read // before then went past it and was not kept: read it again, whole, // so that the device has a copy from the first visit on. navigator.serviceWorker.addEventListener("controllerchange", () => { for (const name of Object.keys(etags)) delete etags[name]; - refresh(true); + refresh("idle"); for (const name of ["questions", "ops"]) loadDoc(name).catch(() => {}); }); } diff --git a/pm-stack/console/public/outbox.js b/pm-stack/console/public/outbox.js index 9eee14325a..b57572ae2b 100644 --- a/pm-stack/console/public/outbox.js +++ b/pm-stack/console/public/outbox.js @@ -360,7 +360,6 @@ * "not done": it is offered again under its name, and the platform * does it once. */ const SEND_WAIT_MS = 60_000; - const gaveUp = (error) => error?.name === "TimeoutError" || error?.name === "AbortError"; /** One try at sending an entry to the platform. */ async function httpSend(entry, fetchImpl = root.fetch.bind(root)) { @@ -384,8 +383,12 @@ try { body = await res.json(); } catch (error) { - // Given up on part-way through the answer: no answer at all. - if (gaveUp(error)) return { network: true }; + // An answer that is not JSON is not the platform's own (a sign-in + // page, something in between), and is read below as that. Any + // other failure is the answer not arriving whole: the connection + // went part-way through it, or the try was given up on. That is + // no answer at all, and it is offered again. + if (error?.name !== "SyntaxError") return { network: true }; body = null; } // No sign-in, whoever says so; or refused by something in between diff --git a/pm-stack/console/test/outbox.test.ts b/pm-stack/console/test/outbox.test.ts index c3284a56d9..d28dbfea0e 100644 --- a/pm-stack/console/test/outbox.test.ts +++ b/pm-stack/console/test/outbox.test.ts @@ -817,7 +817,7 @@ test("one try at sending: what goes out, and how each kind of answer is read", a status, type, json: async () => { - if (body === undefined) throw new Error("not json"); + if (body === undefined) throw new SyntaxError("Unexpected token '<', \"\" is not valid JSON"); return body; }, }); @@ -848,15 +848,23 @@ test("one try at sending: what goes out, and how each kind of answer is read", a throw late("TimeoutError"); }), ).toEqual({ network: true }); - for (const name of ["TimeoutError", "AbortError"]) { + // So is an answer that stops arriving part-way (the connection went + // after its first lines): whatever is thrown that is not "this is + // not JSON" is no answer, never a reason to ask for a sign-in. + for (const failure of [ + late("TimeoutError"), + late("AbortError"), + new TypeError("network error"), + new Error("terminated"), + ]) { const cut = { status: 200, type: "basic", json: async () => { - throw late(name); + throw failure; }, }; - expect(await O.httpSend(entry, answering(cut))).toEqual({ network: true }); + expect([failure.name, await O.httpSend(entry, answering(cut))]).toEqual([failure.name, { network: true }]); } // No answer. expect(