From 5e83979dc8f28c8d98f96509580ee87e2b6f8c0b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 18:00:26 -0600 Subject: [PATCH 1/5] feat(pm-console): keep the signed Android build at the edge The download came from the laptop alone, so with the laptop away it failed. The laptop's report now describes its build (fingerprint, size, date); the edge asks for a build it does not have, the next report carries it, and the edge keeps it only if it is the build described. Nothing is sent again until the build changes. The edge serves its copy when it is the laptop's newest build or when the laptop is not there to ask, and otherwise passes the download to the laptop. The app says when the copy it would hand out is older than the laptop's newest. Five of six planted faults are caught; the sixth removes one of two size checks that each stop an oversized build on their own. Refs #12521. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- pm-stack/console/edge/src/edge.ts | 106 ++++++++++++++++++++++- pm-stack/console/public/app.js | 9 ++ pm-stack/console/src/edge-proto.ts | 31 +++++++ pm-stack/console/src/server.ts | 22 +++++ pm-stack/console/src/sync.ts | 17 ++++ pm-stack/console/test/edge.test.ts | 124 +++++++++++++++++++++++++++ pm-stack/console/test/signin.test.ts | 30 +++++++ 7 files changed, 338 insertions(+), 1 deletion(-) diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 80d0dc29da..6ec208ea68 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -23,6 +23,8 @@ import { DIRECT_ACTIONS, DIRECT_READ_SECTIONS, directClasses, directRead } from import { Devices, KeyedLimiter, Limiter } from "../../src/devices.ts"; import { type Act, DOC_NAMES, type DocName, Docs, Stamped } from "../../src/docs.ts"; import { + type ApkReport, + apkReport, type EdgeConfig, edgeConfig, HELD_FOR_MS, @@ -47,6 +49,7 @@ import { json, manifest, type Phones, + SECURITY, sameSiteWrite, } from "../../src/http.ts"; import { Notifier } from "../../src/notify.ts"; @@ -85,6 +88,16 @@ const SIGNATURE = /^[A-Za-z0-9_-]{86}$/; /** Reports from one address that may fail their checks in a minute * before that address is refused unread. The host's own never fail. */ const SYNC_REFUSALS = 20; +/** The Android build is kept in pieces of this many bytes. */ +const APK_CHUNK = 512 * 1024; +/** With no report for this long, the laptop is not there to ask. */ +const HOST_QUIET_MS = 60_000; + +interface ApkMeta { + sha256: string; + size: number; + at: number; +} const ACT_LIMIT = 256 * 1024; const HELD_MAX = 100; const ACTS_KEPT = 30; @@ -171,6 +184,8 @@ export class Edge { private sure = 0; private unsure = 0; private hostVersion: string | null = null; + private latestApk: ApkMeta | null | undefined; + private keptApk: (ApkMeta & { chunks: number }) | null | undefined; private syncRefused: KeyedLimiter; readonly docs: Docs; readonly push: Push; @@ -219,6 +234,67 @@ export class Edge { this.table = ownActions(this.push, devices); } + // ---- the Android build ------------------------------------------------- + + /** What the app is told of the copy kept here. */ + private async apkState(): Promise<{ at: number; current: boolean } | null> { + const kept = await this.apkKept(); + if (!kept) return null; + const latest = await this.apkLatest(); + return { at: kept.at, current: !latest || latest.sha256 === kept.sha256 }; + } + + /** The build the host last said it has. */ + private async apkLatest(): Promise { + if (this.latestApk === undefined) + this.latestApk = ((await this.kv.get("apk:latest")) as ApkMeta | undefined) ?? null; + return this.latestApk; + } + + /** The build a copy of which is kept here. */ + private async apkKept(): Promise<(ApkMeta & { chunks: number }) | null> { + if (this.keptApk === undefined) { + this.keptApk = ((await this.kv.get("apk")) as (ApkMeta & { chunks: number }) | undefined) ?? null; + } + return this.keptApk; + } + + /** Take in a build the host sent, if it is what the host says it is. */ + private async keepApk(build: ApkReport): Promise { + const bytes = Uint8Array.from(atob(build.data ?? ""), (c) => c.charCodeAt(0)); + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + const sha256 = [...digest].map((b) => b.toString(16).padStart(2, "0")).join(""); + if (bytes.byteLength !== build.size || sha256 !== build.sha256) + throw new Error("the build sent is not the build described"); + const before = await this.apkKept(); + const chunks = Math.ceil(bytes.byteLength / APK_CHUNK); + for (let i = 0; i < chunks; i++) await this.kv.put(`apk:${i}`, bytes.slice(i * APK_CHUNK, (i + 1) * APK_CHUNK)); + for (let i = chunks; i < (before?.chunks ?? 0); i++) await this.kv.delete(`apk:${i}`); + this.keptApk = { sha256, size: build.size, at: build.at, chunks }; + await this.kv.put("apk", this.keptApk); + } + + /** The kept build, as a download. */ + private async serveApk(kept: ApkMeta & { chunks: number }): Promise { + const bytes = new Uint8Array(kept.size); + let at = 0; + for (let i = 0; i < kept.chunks; i++) { + const part = (await this.kv.get(`apk:${i}`)) as Uint8Array | undefined; + if (!part) return json({ error: "the copy of the Android build kept here is incomplete" }, 503); + bytes.set(part, at); + at += part.byteLength; + } + return new Response(bytes, { + headers: { + "Content-Type": "application/vnd.android.package-archive", + "Content-Disposition": 'attachment; filename="pm-console.apk"', + "Cache-Control": "no-store", + "X-Build-At": String(kept.at), + ...SECURITY, + }, + }); + } + // ---- what is kept ------------------------------------------------------ private async config(): Promise { @@ -666,8 +742,24 @@ export class Edge { await this.notifier.tick().catch((error) => console.error(`pm-edge: notify: ${(error as Error).message}`)); } + // The Android build: what the host has now, and the build itself + // when the host sent it because this side asked. + const build = apkReport(msg.apk); + if ( + JSON.stringify(build && { sha256: build.sha256, size: build.size, at: build.at }) !== + JSON.stringify(await this.apkLatest()) + ) { + this.latestApk = build && { sha256: build.sha256, size: build.size, at: build.at }; + if (this.latestApk) await this.kv.put("apk:latest", this.latestApk); + else await this.kv.delete("apk:latest"); + } + if (build?.data) + await this.keepApk(build).catch((error) => console.error(`pm-edge: apk: ${(error as Error).message}`)); + // What the host has and this side has lost (its storage was reset). const want: string[] = []; + const kept = await this.apkKept(); + if (this.latestApk && kept?.sha256 !== this.latestApk.sha256) want.push("apk"); for (const name of Object.keys(SECTIONS)) { if (typeof msg.have?.[name]?.hash === "string" && !(await this.mirror(name))) want.push(name); } @@ -790,6 +882,14 @@ export class Edge { if (method === "GET" && Object.hasOwn(STATIC, rest)) { return next("asset", { path: `${BASE}/${rest}`, type: STATIC[rest] }); } + if (method === "GET" && rest === "pm-console.apk") { + // The newest build is the laptop's. The copy here is served when + // it is that build, or when the laptop is not there to ask. + const kept = await this.apkKept(); + const latest = await this.apkLatest(); + const quiet = this.now() - (this.hostSeen ?? 0) >= HOST_QUIET_MS; + if (kept && (kept.sha256 === latest?.sha256 || quiet)) return this.serveApk(kept); + } if (!rest.startsWith("api/")) return next("relay", { mode: "live" }); const seg = rest.slice(4).split("/"); @@ -801,7 +901,11 @@ export class Edge { ...who, repo: cfg.repo, queue: cfg.queue, - androidApp: cfg.androidApp, + // There is a build to hand out if the laptop has one or a + // copy is kept here; `androidBuild` says of the copy when it + // was built and whether it is the laptop's newest. + androidApp: cfg.androidApp || (await this.apkKept()) !== null, + androidBuild: await this.apkState(), androidPackage: cfg.androidPackage, edge: true, }); diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 1bf7a2a36d..6735247cce 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -1236,6 +1236,15 @@ async function viewPhone(sub) { h("li", {}, h("b", {}, "Notifications. "), "Turn them on under Notifications; they arrive as the app's own."), ), me.androidApp ? h("div", { class: "row end" }, h("a", { class: "button", href: "/console/pm-console.apk" }, "Download the app")) : null, + // Served from Cloudflare's copy when the laptop is away: say so + // when that copy is not the laptop's newest build. + me.androidBuild && !me.androidBuild.current + ? h( + "p", + { class: "meta" }, + `With the laptop away you get the copy kept at Cloudflare, built ${ago(new Date(me.androidBuild.at).toISOString())}. The laptop has a newer build, which will be here once it has reported again.`, + ) + : null, ), ); return out; diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index 71e3de1d80..e38b27db04 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -57,6 +57,11 @@ export interface SyncRequest { v: 1; /** Milliseconds, later than every sync before it. */ at: number; + /** The signed Android build the host has, if it has one: its + * fingerprint, size and date, and the build itself (base64) only in a + * report that follows the edge asking for it. The edge keeps a copy, + * so the app can be downloaded while the host is away. */ + apk?: ApkReport; /** The commit the host's console is running. The edge says it in its * health answer, so whether a merge has reached the host can be seen * from anywhere, without reaching the host. */ @@ -91,6 +96,32 @@ export interface Held { at: string; } +export interface ApkReport { + sha256: string; + size: number; + /** When the build was put in place on the host, in milliseconds. */ + at: number; + data?: string; +} + +/** The largest Android build that is carried in a report. */ +export const APK_LIMIT = 5 * 1024 * 1024; + +/** A build's description as a report may give it, or null. */ +export function apkReport(value: unknown): ApkReport | null { + const v = value as Record | null; + if (!v || typeof v !== "object") return null; + if (typeof v.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(v.sha256)) return null; + if (typeof v.size !== "number" || !Number.isSafeInteger(v.size) || v.size <= 0 || v.size > APK_LIMIT) return null; + if (typeof v.at !== "number" || !Number.isFinite(v.at)) return null; + return { + sha256: v.sha256, + size: v.size, + at: v.at, + ...(typeof v.data === "string" ? { data: v.data } : {}), + }; +} + export interface SyncResponse { ok: true; /** Someone has the app open: keep every section fresh. */ diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 20a6dcd776..3db3645503 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -543,6 +543,27 @@ export function marked(res: Response): Response { return new Response(res.body, { status: res.status, statusText: res.statusText, headers }); } +/** The signed Android build at `path`, described for the edge. Its + * fingerprint is worked out again only when the file has changed. */ +export function androidBuild(path: string) { + let known: { mtime: number; size: number; sha256: string } | null = null; + return async () => { + const file = Bun.file(path); + if (!(await file.exists())) return null; + const { lastModified: mtime, size } = file; + if (!known || known.mtime !== mtime || known.size !== size) { + const sha256 = new Bun.CryptoHasher("sha256").update(await file.arrayBuffer()).digest("hex"); + known = { mtime, size, sha256 }; + } + return { + sha256: known.sha256, + size, + at: mtime, + read: async () => new Uint8Array(await Bun.file(path).arrayBuffer()), + }; + }; +} + /** The commit this console was started from, or nothing if it cannot * be told (not a checkout, no git). The service is restarted when a * merge is put into service, so this is the code that is running. */ @@ -588,6 +609,7 @@ if (import.meta.main) { ? new EdgeLink({ url: cfg.edgeUrl, version: await runningCommit(), + apk: androidBuild(cfg.androidApk), keys: fileStore(cfg.edgeKeyFile), done: fileStore(cfg.edgeDoneFile), docs, diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index df311c6963..215c8d4712 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -11,6 +11,7 @@ // interrupted instead of being run a second time. import type { Docs } from "./docs.ts"; import { + APK_LIMIT, type EdgeConfig, type Held, HOLDABLE, @@ -50,6 +51,9 @@ export interface LinkOptions { run: (held: Held) => Promise; /** The commit this console is running, if it could be found. */ version?: string; + /** The signed Android build on this host, if there is one, and a way + * to read it when the edge asks for it. */ + apk?: () => Promise<{ sha256: string; size: number; at: number; read: () => Promise } | null>; fetchImpl?: typeof fetch; now?: () => number; log?: (line: string) => void; @@ -185,10 +189,23 @@ export class EdgeLink { const sections = snapshot.filter((s) => this.sent.get(s.name) !== s.hash || this.want.has(s.name)); const acks = [...this.acks]; const at = Math.max(this.now(), this.lastAt + 1); + // The Android build: always what it is, and the build itself only + // when the edge has said it lacks this one. + const build = (await this.o.apk?.().catch(() => null)) ?? null; + const apk = + build && build.size <= APK_LIMIT + ? { + sha256: build.sha256, + size: build.size, + at: build.at, + ...(this.want.has("apk") ? { data: Buffer.from(await build.read()).toString("base64") } : {}), + } + : null; const message: SyncRequest & { acts: unknown } = { v: 1, at, ...(this.o.version ? { version: this.o.version } : {}), + ...(apk ? { apk } : {}), config: await this.o.config(), sections, have: Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at, error: s.error }])), diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 089e0c34dc..3119a693a9 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -551,6 +551,13 @@ async function setup(options: { direct?: boolean } = {}) { }, }; const net = { hostUp: true, edgeUp: true, loseAnswer: false, giveUpEarly: false }; + /** The signed Android build on the host, if any, and how often it was read to be sent. */ + const build: { bytes: Uint8Array | null; at: number; reads: number; corrupt: boolean } = { + bytes: null, + at: 0, + reads: 0, + corrupt: false, + }; /** Requests to the host still running after the edge stopped waiting. */ const stillRunning: Promise[] = []; const hostSaw: string[] = []; @@ -606,6 +613,20 @@ async function setup(options: { direct?: boolean } = {}) { const makeLink = () => new EdgeLink({ version: "0123abcd4567", + apk: async () => { + if (!build.bytes) return null; + const bytes = build.bytes; + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + return { + sha256: [...digest].map((b) => b.toString(16).padStart(2, "0")).join(""), + size: bytes.byteLength, + at: build.at, + read: async () => { + build.reads++; + return build.corrupt ? bytes.map((b) => b ^ 1) : bytes; + }, + }; + }, url: `https://${HOST}`, keys, done, @@ -700,6 +721,7 @@ async function setup(options: { direct?: boolean } = {}) { act, core, hostReads, + build, failing, gate, stillRunning, @@ -1286,6 +1308,108 @@ describe("actions", () => { }); }); +describe("the Android build", () => { + const apk = (seed: number, size = 700_000) => Uint8Array.from({ length: size }, (_, i) => (i * 31 + seed) % 251); + const report = async (w: Awaited>) => { + w.now.t += 1_000; + return w.link.now.once(); + }; + const download = async (w: Awaited>) => { + const res = await w.browse("/console/pm-console.apk"); + return { res, bytes: new Uint8Array(await res.arrayBuffer()) }; + }; + + test("a copy is kept at the edge, sent once, and served when the laptop is away", async () => { + const w = await setup(); + await w.hostReads(); + // The host has no build: nothing is asked for, and the app is told there is none. + expect((await report(w))?.want).not.toContain("apk"); + w.build.bytes = apk(1); + w.build.at = w.now.t; + // It has one now. The first report only describes it; the edge asks; the next carries it. + expect((await report(w))?.want).toContain("apk"); + expect(w.build.reads).toBe(0); + expect((await report(w))?.want).not.toContain("apk"); + expect(w.build.reads).toBe(1); + // After that it is not sent again, however many reports follow. + await report(w); + await report(w); + expect(w.build.reads).toBe(1); + // The copy is the laptop's build, so it is served from here without asking the laptop. + w.hostSaw.length = 0; + let got = await download(w); + expect(got.res.status).toBe(200); + expect(got.res.headers.get("content-type")).toBe("application/vnd.android.package-archive"); + expect(got.res.headers.get("content-disposition")).toBe('attachment; filename="pm-console.apk"'); + expect(got.bytes).toEqual(apk(1)); + expect(w.hostSaw).toEqual([]); + // The edge restarts and the laptop goes away: still served, byte for byte. + w.edge.now = w.makeEdge(); + w.net.hostUp = false; + w.now.t += 10 * 60_000; + got = await download(w); + expect(got.res.status).toBe(200); + expect(got.bytes).toEqual(apk(1)); + const me = (await (await w.browse("/console/api/me")).json()) as Record; + expect(me.androidApp).toBe(true); + expect(me.androidBuild).toEqual({ at: w.build.at, current: true }); + // Only the owner gets it. + expect((await w.browse("/console/pm-console.apk", { token: null })).status).not.toBe(200); + }); + + test("a newer build on the laptop is fetched, and until then the app says the copy is older", async () => { + const w = await setup(); + await w.hostReads(); + w.build.bytes = apk(1); + w.build.at = w.now.t; + await report(w); + await report(w); + const first = w.build.at; + // A new build is signed on the laptop. The edge has heard of it but does not have it yet. + w.build.bytes = apk(2, 900_000); + w.build.at = w.now.t + 500; + expect((await report(w))?.want).toContain("apk"); + let me = (await (await w.browse("/console/api/me")).json()) as Record; + expect(me.androidBuild).toEqual({ at: first, current: false }); + // The laptop is there, so the download is the laptop's: the newest. + w.hostSaw.length = 0; + await w.browse("/console/pm-console.apk"); + expect(w.hostSaw).toEqual(["GET /console/pm-console.apk"]); + // The next report brings it, and then the copy is current again. + await report(w); + me = (await (await w.browse("/console/api/me")).json()) as Record; + expect(me.androidBuild).toEqual({ at: w.build.at, current: true }); + w.net.hostUp = false; + w.now.t += 10 * 60_000; + expect((await download(w)).bytes).toEqual(apk(2, 900_000)); + }); + + test("a build that is not the one described is not kept, and one too large is not sent", async () => { + const w = await setup(); + await w.hostReads(); + w.build.bytes = apk(3); + w.build.at = w.now.t; + w.build.corrupt = true; + await report(w); + await report(w); + // What arrived did not match its fingerprint: nothing is kept, and it is asked for again. + expect(w.stored.has("apk")).toBe(false); + expect((await report(w))?.want).toContain("apk"); + w.build.corrupt = false; + await report(w); + expect((w.stored.get("apk") as { size: number }).size).toBe(700_000); + // A build too large to carry in a report is never read to be sent. + const big = await setup(); + await big.hostReads(); + big.build.bytes = new Uint8Array(5 * 1024 * 1024 + 1); + big.build.at = big.now.t; + await report(big); + await report(big); + expect(big.build.reads).toBe(0); + expect(big.stored.has("apk")).toBe(false); + }); +}); + describe("the host's report is the host's", () => { const report = async ( w: Awaited>, diff --git a/pm-stack/console/test/signin.test.ts b/pm-stack/console/test/signin.test.ts index 9de318034c..5138da6931 100644 --- a/pm-stack/console/test/signin.test.ts +++ b/pm-stack/console/test/signin.test.ts @@ -168,3 +168,33 @@ describe("sign-in", () => { expect(failed.message).not.toContain(VALUE); }); }); + +test("the Android build on the laptop is described for the edge, and fingerprinted only when it changes", async () => { + const { androidBuild } = await import("../src/server.ts"); + const { mkdtempSync, writeFileSync, utimesSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const dir = mkdtempSync(join(tmpdir(), "pm-apk-")); + try { + const path = join(dir, "pm-console.apk"); + const build = androidBuild(path); + // No build installed: nothing to describe. + expect(await build()).toBeNull(); + writeFileSync(path, "first build"); + const one = await build(); + // SHA-256 of the text, worked out separately with sha256sum. + expect(one?.sha256).toBe("f3adf3a4014af2dc15376ed0b22ac63cae9073430512bad33659b8f352c9fb30"); + expect(one?.size).toBe(11); + expect(new TextDecoder().decode(await one?.read())).toBe("first build"); + // Unchanged: the same description. + expect((await build())?.sha256).toBe(one?.sha256); + // A new build put in its place, same length: a new fingerprint and date. + writeFileSync(path, "other build"); + utimesSync(path, new Date(Date.now() + 5_000), new Date(Date.now() + 5_000)); + const two = await build(); + expect(two?.sha256).not.toBe(one?.sha256); + expect(two?.at).toBeGreaterThan(one?.at ?? 0); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); From 8c1840ba16b62f812ab38c87a4016915aa3750f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 18:01:15 -0600 Subject: [PATCH 2/5] docs(pm-console): record the switch, the report's limits and what is still open Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- ...T11-10-00Z_architecture_pm_console_edge.md | 48 +++++++++++++++++++ planning/plans/2026-11-21_results-first.md | 1 + 2 files changed, 49 insertions(+) diff --git a/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md b/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md index 151f8c6ce1..25fc12eabd 100644 --- a/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md +++ b/doc/2026-11-22T11-10-00Z_architecture_pm_console_edge/2026-11-22T11-10-00Z_architecture_pm_console_edge.md @@ -171,3 +171,51 @@ One change nobody asked for: the contact handed to push services with every notification was the owner's address. It is now the project's page. Delivery does not depend on it, and an address has no reason to travel to Google or Mozilla with each message. + +## 2026-11-23T00:20Z Update: the owner's switch, the report's limits, the build's copy + +Direct mode (the edge reading and acting by itself while the laptop is +away) was built by the fleet in #12579 and deployed switched off. What +was added around it since: + +- **The switch is the owner's, in the app** (#12712). More, Laptop away + says what the mode covers and what turning it on hands over: the + repository automation token and the queue store token, as secrets of + the Worker. It runs `expose.py --edge-direct` on the laptop, where + the tokens are. The script now sends them through Cloudflare's API + rather than a tool that had to be installed; turning the mode off + takes them away again; an attempt that fails part-way leaves the + Worker holding nothing; a mode that is on gets back what the Worker + has lost; and runs take turns, so the timer cannot undo what the app + is doing. +- **Reports are refused unread** when they say they are too large or + are not shaped like a report, and an address with twenty refused + reports in a minute is refused unread until the minute is out + (#12715). A report the laptop signed that is merely wrong is not held + against its address. +- **The edge says which commit the laptop runs** (`hostVersion` in + `/console/health`, #12715). That a merge has reached the laptop can + be seen from anywhere. It was first used to confirm exactly that when + the session had no other way to look at the laptop. +- **A unit that keeps failing on its timer is reported**, once, with + what it is for, and so is its mending (#12719). This is what was + missing when `pm-git-sync` failed for two hours unseen. +- **The signed Android build is kept at the edge**, sent once per + build in the laptop's report and kept only if it matches its + fingerprint. The download is served from that copy when it is the + newest build or the laptop is away. + +Still open, and why: + +- Direct mode is off until the owner turns it on. Its check against + the real queue store and GitHub runs when it is turned on and shows + on the same screen; the five-minute laptop-away check in #12518 has + not been done. +- A rebuild commit that changes `flake.lock` still leaves the laptop's + `main` ahead and behind at once (#12520). It is now reported within + five minutes instead of never; carrying the commit to `main` without + a person is not built, because it has to be tried on the laptop. +- The deploy still uses `wrangler deploy`. The `cf` release flow is + staged in #12561 and needs two protected environments with their own + tokens before it can run. +- The Android project is still on androidbrowserhelper 2.5.0. diff --git a/planning/plans/2026-11-21_results-first.md b/planning/plans/2026-11-21_results-first.md index 0ab9ae3978..82c8f365cf 100644 --- a/planning/plans/2026-11-21_results-first.md +++ b/planning/plans/2026-11-21_results-first.md @@ -335,3 +335,4 @@ To undo: revert the plan's PR. The skills are additive and are loaded by descrip - 2026-11-22: The console is served from Cloudflare. #12501 gave the Android app its own parts (widget, share, dictation, tile, shortcuts) and a signed-in link for the widget. #12505 put a Worker, `pm-console-edge`, in front of the laptop: it serves the app, keeps the laptop's last report, holds twelve kinds of action for the laptop's return, sends notifications, and says when the laptop has gone quiet. #12511 finished the cutover (the setup script's health check was being refused as `Python-urllib`) and fixed what the first review found, including an action that could run twice. Live check: `curl https://pm-console-edge.developing-today.workers.dev/console/health` answers `configured: true` with a current `hostSeen`. Not checked: the owner's real sign-in at the edge; the counters `answered` and `deferred` in that answer show which happened at the first visit. - 2026-11-22: The laptop had stopped deploying merges for two hours: an empty rebuild marker commit on its `main` made the fast-forward-only sync stand still, 28 merges behind. Repaired by hand, then #12515 taught `pm-git-sync` to move empty markers aside (in service after the next system rebuild). A rebuild commit that changes `flake.lock` still diverges (#12520). - 2026-11-22: #12517 added More, Sign-in: the steps, the two addresses and a form that turn Google sign-in on from the app. The Google client itself still has to be made by a signed-in person (#12417). Not built: the edge acting on the queue and GitHub by itself while the laptop is away; designed in #12518. Also filed: #12519 (linked phones across an edge on/off change), #12521 (limit the report endpoint, Android build at the edge, `cf` deploy flow). +- 2026-11-23: The fleet built the edge acting by itself while the laptop is away (#12579); it is deployed and off. #12712 made turning it on the owner's switch in the app (More, Laptop away) and made the script behind it need nothing installed. #12715: reports refused unread from an address that keeps sending bad ones, and `hostVersion` in the edge's health, which showed the laptop taking merges with no access to the laptop. #12719: a unit that keeps failing on its timer is reported. The signed Android build is kept at the edge. Open: turning direct mode on and its laptop-away check (#12518), rebuild commits that change `flake.lock` (#12520), the `cf` deploy flow (#12561), the Android library upgrade. From 68d94241c16aabdd54a3c6ff0e9283a4f61594a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 18:04:51 -0600 Subject: [PATCH 3/5] feat(pm-console): the edge's health says whether it holds the Android build So that the copy's arrival at the deployed Worker can be checked from outside, like the laptop's commit. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- pm-stack/console/edge/src/edge.ts | 3 +++ pm-stack/console/test/edge.test.ts | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 9a7473bad8..98d3c03447 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -837,6 +837,9 @@ export class Edge { hostSeen: this.hostSeen || null, // The commit the host's console is running, as it last said. hostVersion: this.hostVersion, + // The copy of the Android build kept here: when it was built, + // and whether it is the host's newest. Null if there is none. + androidBuild: await this.apkState(), // Since this object last started: requests it answered as the // owner's, and requests it left to the host to judge. answered: this.sure, diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 9178c45a63..5cdd221f1b 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -760,6 +760,7 @@ describe("before the host's first report", () => { selfCheck: null, hostSeen: null, hostVersion: null, + androidBuild: null, answered: 0, deferred: 0, version: "test", @@ -1353,6 +1354,9 @@ describe("the Android build", () => { const me = (await (await w.browse("/console/api/me")).json()) as Record; expect(me.androidApp).toBe(true); expect(me.androidBuild).toEqual({ at: w.build.at, current: true }); + // Health says the same of the copy, to anyone: it is how its arrival is checked from outside. + const health = (await (await w.browse("/console/health", { token: null })).json()) as Record; + expect(health.androidBuild).toEqual({ at: w.build.at, current: true }); // Only the owner gets it. expect((await w.browse("/console/pm-console.apk", { token: null })).status).not.toBe(200); }); From daa229b0defcc241e7beecb304b4f37698c764d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 18:14:14 -0600 Subject: [PATCH 4/5] fix(pm-console): a build the edge cannot keep is not re-sent with every report If a build did not match its description, or could not be stored, the edge asked for it again at once, and a missing piece made the laptop report every half second: half a megabyte, twice a second, for as long as it kept failing. The edge now asks again no sooner than ten minutes later, and being asked for the build no longer hurries the laptop. Three planted faults are each caught. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- pm-stack/console/edge/src/edge.ts | 19 ++++++++++++++++--- pm-stack/console/src/sync.ts | 4 +++- pm-stack/console/test/edge.test.ts | 17 ++++++++++++++--- 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 98d3c03447..9b26975a59 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -90,6 +90,8 @@ const SIGNATURE = /^[A-Za-z0-9_-]{86}$/; const SYNC_REFUSALS = 20; /** The Android build is kept in pieces of this many bytes. */ const APK_CHUNK = 512 * 1024; +/** A build that could not be kept is asked for again no sooner than this. */ +const APK_RETRY_MS = 10 * 60_000; /** With no report for this long, the laptop is not there to ask. */ const HOST_QUIET_MS = 60_000; @@ -186,6 +188,8 @@ export class Edge { private hostVersion: string | null = null; private latestApk: ApkMeta | null | undefined; private keptApk: (ApkMeta & { chunks: number }) | null | undefined; + /** The build that could not be kept when it was last sent, and when. */ + private apkFailed: { sha256: string; at: number } | null = null; private syncRefused: KeyedLimiter; readonly docs: Docs; readonly push: Push; @@ -757,13 +761,22 @@ export class Edge { if (this.latestApk) await this.kv.put("apk:latest", this.latestApk); else await this.kv.delete("apk:latest"); } - if (build?.data) - await this.keepApk(build).catch((error) => console.error(`pm-edge: apk: ${(error as Error).message}`)); + if (build?.data) { + await this.keepApk(build).catch((error) => { + // Not kept (it did not match its description, or could not be + // stored). It is not asked for again at once: a build that + // fails every time would otherwise be sent with every report. + this.apkFailed = { sha256: build.sha256, at: now }; + console.error(`pm-edge: apk: ${(error as Error).message}`); + }); + } // What the host has and this side has lost (its storage was reset). const want: string[] = []; const kept = await this.apkKept(); - if (this.latestApk && kept?.sha256 !== this.latestApk.sha256) want.push("apk"); + const failedLately = + this.apkFailed?.sha256 === this.latestApk?.sha256 && now - (this.apkFailed?.at ?? 0) < APK_RETRY_MS; + if (this.latestApk && kept?.sha256 !== this.latestApk.sha256 && !failedLately) want.push("apk"); for (const name of Object.keys(SECTIONS)) { if (typeof msg.have?.[name]?.hash === "string" && !(await this.mirror(name))) want.push(name); } diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index 215c8d4712..31a0b58490 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -268,7 +268,9 @@ export class EdgeLink { } const answer = await this.once(); // Something was done or is wanted: say so at once. - if (this.acks.length > 0 || this.want.size > 0) return 500; + // (The Android build is not such a thing: it waits for the next + // ordinary report, and half a megabyte is never sent in a hurry.) + if (this.acks.length > 0 || [...this.want].some((name) => name !== "apk")) return 500; return answer?.watching || this.o.docs.watched() ? FAST_MS : IDLE_MS; } diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 5cdd221f1b..53e0ed51a3 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -1328,7 +1328,10 @@ describe("the Android build", () => { w.build.bytes = apk(1); w.build.at = w.now.t; // It has one now. The first report only describes it; the edge asks; the next carries it. - expect((await report(w))?.want).toContain("apk"); + // Being asked for the build does not hurry the host the way a missing section does. + w.now.t += 1_000; + expect(await w.link.now.turn()).toBeGreaterThan(500); + expect(w.link.now.last?.want).toContain("apk"); expect(w.build.reads).toBe(0); expect((await report(w))?.want).not.toContain("apk"); expect(w.build.reads).toBe(1); @@ -1396,11 +1399,19 @@ describe("the Android build", () => { w.build.corrupt = true; await report(w); await report(w); - // What arrived did not match its fingerprint: nothing is kept, and it is asked for again. + // What arrived did not match its fingerprint: nothing is kept. expect(w.stored.has("apk")).toBe(false); - expect((await report(w))?.want).toContain("apk"); + expect(w.build.reads).toBe(1); + // It is not asked for again with every report: a build that fails + // every time would be half a megabyte in each of them. + for (let i = 0; i < 20; i++) expect((await report(w))?.want).not.toContain("apk"); + expect(w.build.reads).toBe(1); + // Ten minutes on it is asked for once more, and this time it is right. w.build.corrupt = false; + w.now.t += 10 * 60_000; + expect((await report(w))?.want).toContain("apk"); await report(w); + expect(w.build.reads).toBe(2); expect((w.stored.get("apk") as { size: number }).size).toBe(700_000); // A build too large to carry in a report is never read to be sent. const big = await setup(); From d7078f03df3ef2167ec5e159ff4deb2eb476b385 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 18:15:41 -0600 Subject: [PATCH 5/5] fix(pm-console): the build goes alone when it would not fit, and the edge reads back the laptop's last report first Two review findings on the build kept at the edge: - A report carrying the build and large changed sections could pass what the edge takes in one report; refused as too large, it would be built the same way again. The build now goes alone when the two would not fit, and the sections follow in the next report. - After a restart the edge chose which build to serve before reading back when the laptop last reported, so a laptop that was there looked absent and the older copy was served. It reads that back first. Both faults, planted again, fail the new tests. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- pm-stack/console/edge/src/edge.ts | 5 +++- pm-stack/console/src/edge-proto.ts | 5 ++++ pm-stack/console/src/sync.ts | 24 ++++++++++------- pm-stack/console/test/edge.test.ts | 42 ++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 11 deletions(-) diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 9b26975a59..492394a90e 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -904,7 +904,10 @@ export class Edge { } if (method === "GET" && rest === "pm-console.apk") { // The newest build is the laptop's. The copy here is served when - // it is that build, or when the laptop is not there to ask. + // it is that build, or when the laptop is not there to ask. After + // a restart, when the laptop was last heard from has to be read + // back first, or it would look as if it never had been. + await this.ready(); const kept = await this.apkKept(); const latest = await this.apkLatest(); const quiet = this.now() - (this.hostSeen ?? 0) >= HOST_QUIET_MS; diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index e38b27db04..5daf14e4ac 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -106,6 +106,11 @@ export interface ApkReport { /** The largest Android build that is carried in a report. */ export const APK_LIMIT = 5 * 1024 * 1024; +/** What the host keeps a report under, with room to spare below what + * the edge refuses as too large (8 MiB). A report that would carry the + * build past this carries the build alone, and the sections follow in + * the next one. */ +export const REPORT_ROOM = 7.5 * 1024 * 1024; /** A build's description as a report may give it, or null. */ export function apkReport(value: unknown): ApkReport | null { diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index 31a0b58490..7bbca73de9 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -12,6 +12,7 @@ import type { Docs } from "./docs.ts"; import { APK_LIMIT, + type ApkReport, type EdgeConfig, type Held, HOLDABLE, @@ -20,6 +21,7 @@ import { type PublicKey, type PhoneLinks, publicKey, + REPORT_ROOM, type SyncRequest, type SyncResponse, sign, @@ -186,21 +188,23 @@ export class EdgeLink { try { const pair = await this.keys(); const snapshot = this.o.docs.snapshot(); - const sections = snapshot.filter((s) => this.sent.get(s.name) !== s.hash || this.want.has(s.name)); + let sections = snapshot.filter((s) => this.sent.get(s.name) !== s.hash || this.want.has(s.name)); const acks = [...this.acks]; const at = Math.max(this.now(), this.lastAt + 1); // The Android build: always what it is, and the build itself only // when the edge has said it lacks this one. const build = (await this.o.apk?.().catch(() => null)) ?? null; - const apk = - build && build.size <= APK_LIMIT - ? { - sha256: build.sha256, - size: build.size, - at: build.at, - ...(this.want.has("apk") ? { data: Buffer.from(await build.read()).toString("base64") } : {}), - } - : null; + const apk: ApkReport | null = + build && build.size <= APK_LIMIT ? { sha256: build.sha256, size: build.size, at: build.at } : null; + if (apk && build && this.want.has("apk")) { + apk.data = Buffer.from(await build.read()).toString("base64"); + // The build and large sections together could pass what the edge + // takes in one report, and a report refused as too large would be + // built the same way again and again. So the build goes alone + // then; the sections are not marked sent and follow next time. + const others = sections.reduce((sum, s) => sum + JSON.stringify(s.data).length, 0); + if (apk.data.length + others > REPORT_ROOM) sections = []; + } const message: SyncRequest & { acts: unknown } = { v: 1, at, diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 53e0ed51a3..b3ea25c41e 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -1391,6 +1391,48 @@ describe("the Android build", () => { expect((await download(w)).bytes).toEqual(apk(2, 900_000)); }); + test("after the edge restarts, a laptop that is there is still asked for its newer build", async () => { + const w = await setup(); + await w.hostReads(); + w.build.bytes = apk(1); + w.build.at = w.now.t; + await report(w); + await report(w); + // A newer build is announced, and the edge restarts before it has a copy. + w.build.bytes = apk(2); + w.build.at = w.now.t + 500; + await report(w); + w.edge.now = w.makeEdge(); + w.hostSaw.length = 0; + const got = await download(w); + // The laptop reported seconds ago: the download is its newest build, not the older copy. + expect(w.hostSaw).toEqual(["GET /console/pm-console.apk"]); + expect(got.bytes).not.toEqual(apk(1)); + }); + + test("a build and large sections that will not fit one report go in two, and both arrive", async () => { + const w = await setup(); + await w.hostReads(); + await report(w); + // Nearly the largest build that is carried, and three megabytes of questions changed at once. + w.build.bytes = apk(5, 4_900_000); + w.build.at = w.now.t; + await report(w); // described; the edge asks for it + w.data.questions = { sets: [{ id: "big", text: "q".repeat(3_000_000) }] }; + w.now.t += 11_000; + await w.hostReads(); + // Every report from here is accepted: none is refused as too large. + const answers = [await report(w), await report(w), await report(w)]; + expect(answers.every((answer) => answer?.ok === true)).toBe(true); + expect((w.stored.get("apk") as { size: number }).size).toBe(4_900_000); + // And the questions arrived whole, in the report after the build's. + const pieces = (w.stored.get("m:questions") as { chunks: number } | undefined)?.chunks ?? 0; + expect(pieces).toBeGreaterThan(1); + let text = ""; + for (let i = 0; i < pieces; i++) text += String(w.stored.get(`m:questions:${i}`)); + expect(JSON.parse(text).sets[0].text.length).toBe(3_000_000); + }); + test("a build that is not the one described is not kept, and one too large is not sent", async () => { const w = await setup(); await w.hostReads();