Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions planning/plans/2026-11-21_results-first.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
125 changes: 124 additions & 1 deletion pm-stack/console/edge/src/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -47,6 +49,7 @@ import {
json,
manifest,
type Phones,
SECURITY,
sameSiteWrite,
} from "../../src/http.ts";
import { Notifier } from "../../src/notify.ts";
Expand Down Expand Up @@ -85,6 +88,18 @@ 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;
/** 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;

interface ApkMeta {
sha256: string;
size: number;
at: number;
}
const ACT_LIMIT = 256 * 1024;
const HELD_MAX = 100;
const ACTS_KEPT = 30;
Expand Down Expand Up @@ -171,6 +186,10 @@ 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;
/** 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;
Expand Down Expand Up @@ -219,6 +238,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<ApkMeta | null> {
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<void> {
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<Response> {
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<EdgeConfig | null> {
Expand Down Expand Up @@ -670,8 +750,33 @@ 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) => {
// 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();
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);
}
Expand Down Expand Up @@ -745,6 +850,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,
Expand Down Expand Up @@ -794,6 +902,17 @@ 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. 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;
if (kept && (kept.sha256 === latest?.sha256 || quiet)) return this.serveApk(kept);
Comment on lines +913 to +914

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore the host timestamp before choosing the APK

If the Durable Object restarts after the laptop announces a newer build but before that build is copied, an APK request can incorrectly receive the older build even while the laptop is available. hostSeen starts as null and is restored from storage only by ready(), but this route returns before the general ready() call below it. Consequently, the quiet check uses zero and bypasses the newer build on the laptop despite a recent persisted report. Call ready() before evaluating this gate.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real. Fixed in the next commit: ready() runs before the gate, so when the laptop last reported is read back before deciding it is away. Tested: a newer build is announced, the edge restarts before it has a copy, and the download goes to the laptop instead of handing out the older copy. Removing the call fails that test.


Generated by Claude Code

}
if (!rest.startsWith("api/")) return next("relay", { mode: "live" });

const seg = rest.slice(4).split("/");
Expand All @@ -805,7 +924,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,
});
Expand Down
9 changes: 9 additions & 0 deletions pm-stack/console/public/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
36 changes: 36 additions & 0 deletions pm-stack/console/src/edge-proto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -91,6 +96,37 @@ 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;
/** 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 {
const v = value as Record<string, unknown> | 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. */
Expand Down
22 changes: 22 additions & 0 deletions pm-stack/console/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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,
Expand Down
Loading