diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index 18890a7619..7a5c1d28fb 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -11,7 +11,7 @@ runs the fleet's tools can be reached. | -------------------------------------------------------- | ------------------------------ | --------------------------------------------------------------------------- | | The app's page, script and icons | edge | unchanged | | Checking who is calling | edge, and again on the laptop | the edge still answers the owner; anyone it is unsure of gets nothing | -| State (in progress, next, needs me, prompts, pull…) | edge, from the laptop's report | served as of the last report, with that time shown | +| State (in progress, next, needs me, prompts, pull…) | edge, from the laptop's report | pull requests can be refreshed from GitHub after one minute of silence; other data remains as of the last report | | Notifications: keys, subscriptions, sending | edge | unchanged; and one says the laptop has gone quiet | | Linked phones and the widget's summary | edge | unchanged | | Actions safe to do late (prompts, answers, comments, …) | laptop, relayed at once | held at the edge, run once when it is back, dropped after a day and said so | @@ -77,9 +77,12 @@ laptop: pm-console (../src/server.ts), reporting through ../src/sync.ts only actions on the late list, and records each in its audit log as `via: edge-held` with who took it and when. -The Worker has no secrets configured. The keys it uses it made itself -(notification signing) or were published to it (the laptop's, the -sign-in issuer's). +The optional direct pull-request read uses the `GITHUB_TOKEN` Worker +secret only when `GITHUB_READ_ENABLED=on`. It is disabled by default; +`/console/health` reports whether it is enabled, whether the secret exists, +and whether the capability is ready. The token is sent only to GitHub's +read endpoint and is never returned by health. Other edge reads and writes +are not implemented by this first slice. ## Deploy, and going back @@ -116,10 +119,11 @@ simply what is behind the hostname. ## Limits worth knowing -- State at the edge is the laptop's last report. With the laptop gone it - ages, and the app says how old it is; it does not go on changing. -- Reading the queue and filing a prompt straight from the edge, with the - laptop off, is not built: it needs the queue store's and GitHub's - credentials at the edge. +- State at the edge is the laptop's last report except for open pull + requests, which can refresh from GitHub after the laptop has been quiet + for one minute and the direct-read switch and secret are present. +- Fresh board, ranked-issue and prompt reads, and direct actions remain + unimplemented. Prompt queue-task creation still requires the documented + fleet queue contract or explicit laptop enqueue on return. - 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 89a47cd991..c4e6979c4b 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -87,6 +87,8 @@ const AUDIT_KEPT = 300; const WATCHING_MS = 90_000; /** The host is reported silent after this long without a sync. */ export const SILENT_MS = 10 * 60_000; +/** The laptop is quiet long enough to bypass it for safe reads. */ +const DIRECT_READ_AFTER_MS = 60_000; const KEY_FETCH_EVERY_MS = 30_000; const STATIC: Record = { "app.js": "text/javascript; charset=utf-8", @@ -123,8 +125,16 @@ export interface EdgeOptions { now?: () => number; /** Reaches the sign-in issuer's keys and the push services. */ fetchImpl?: typeof fetch; + /** Reads a section from its source when the host has gone quiet. */ + freshRead?: (section: string, config: EdgeConfig) => Promise; + githubReadEnabled?: boolean; + githubTokenConfigured?: boolean; /** Ask to be woken at a time: the check for a silent host. */ setAlarm?: (at: number) => Promise; + /** Work that may finish after the response has gone: the object's + * own waitUntil, so a background read is not cut off with the + * response. Defaults to letting it run unattended. */ + later?: (work: Promise) => void; } export class Edge { @@ -132,6 +142,13 @@ export class Edge { private now: () => number; private fetchImpl: typeof fetch; private setAlarm: (at: number) => Promise; + private later: (work: Promise) => void; + private freshRead?: EdgeOptions["freshRead"]; + private githubReadEnabled: boolean; + private githubTokenConfigured: boolean; + /** A pull-request read already running: shared by every request + * while it runs, so a slow GitHub is asked once, not once a poll. */ + private prsRefresh: Promise | null = null; private cfg: EdgeConfig | null | undefined; private mirrors = new Map(); private held: Held[] | null = null; @@ -156,7 +173,11 @@ export class Edge { this.kv = options.kv; this.now = options.now ?? Date.now; this.fetchImpl = options.fetchImpl ?? fetch; + this.freshRead = options.freshRead; + this.githubReadEnabled = options.githubReadEnabled ?? false; + this.githubTokenConfigured = options.githubTokenConfigured ?? false; this.setAlarm = options.setAlarm ?? (async () => {}); + this.later = options.later ?? ((work) => void work); this.docs = new Docs( Object.fromEntries( Object.entries(SECTIONS).map(([name, ttlMs]) => [ @@ -477,6 +498,31 @@ export class Edge { } } + /** Read pull requests from GitHub again without making a document + * wait for it: the read runs after the response, through the + * object's waitUntil, and a request that arrives while it runs + * shares it instead of starting another. */ + private refreshPrs(cfg: EdgeConfig): void { + if (this.prsRefresh) return; + const read = this.freshRead; + if (!read) return; + this.prsRefresh = (async () => { + try { + this.docs.record("prs", await read("prs", cfg), this.now()); + } catch (error) { + // The stored copy is still the last good list: read it back + // before saying the fresh read failed, so the failure does not + // hide it. A failed read stamps the section's time, which is + // what decides whether the stored copy is ever loaded. + await this.docs.refresh("prs"); + this.docs.recordFailure("prs", error); + } finally { + this.prsRefresh = null; + } + })(); + this.later(this.prsRefresh); + } + // ---- requests ---------------------------------------------------------- async fetch(req: Request): Promise { @@ -502,6 +548,9 @@ export class Edge { ok: true, edge: true, configured: cfg !== null, + githubReadEnabled: this.githubReadEnabled, + githubTokenConfigured: this.githubTokenConfigured, + githubReadReady: this.freshRead !== undefined, hostSeen: this.hostSeen || null, // Since this object last started: requests it answered as the // owner's, and requests it left to the host to judge. @@ -570,6 +619,20 @@ export class Edge { } if (seg.length === 2 && seg[0] === "doc" && DOC_NAMES.includes(seg[1] as DocName)) { this.lastDocAt = this.now(); + // Pull requests are a read-only GitHub view. When the laptop is + // quiet, refresh them directly if this Worker has that capability. + // The read runs in the background: the document answers at once + // from what is cached, and the fresh list arrives on the next + // poll. Only a stale section is refreshed, so GitHub is asked + // at most once per interval while the laptop is quiet. + if ( + seg[1] === "ops" && + this.freshRead && + this.now() - (this.hostSeen ?? 0) >= DIRECT_READ_AFTER_MS && + this.docs.isStale("prs") + ) { + this.refreshPrs(cfg); + } const res = docResponse(req, await this.docs.doc(seg[1] as DocName)); // When the host last reported, beside the document rather than // in it: it changes with every report and the content does not. diff --git a/pm-stack/console/edge/src/github.ts b/pm-stack/console/edge/src/github.ts new file mode 100644 index 0000000000..d45471a2b7 --- /dev/null +++ b/pm-stack/console/edge/src/github.ts @@ -0,0 +1,46 @@ +export interface PullRequestSummary { + number: number; + title: string; + draft: boolean; + url: string; + created: string; + author: string; + branch: string; +} + +/** Read the same bounded open-PR view the laptop console presents. */ +export async function readOpenPullRequests( + repo: string, + token: string, + fetchImpl: typeof fetch = fetch, +): Promise { + const response = await fetchImpl(`https://api.github.com/repos/${repo}/pulls?state=open&per_page=60`, { + headers: { + accept: "application/vnd.github+json", + authorization: `Bearer ${token}`, + "user-agent": "pm-console-edge", + "x-github-api-version": "2022-11-28", + }, + signal: AbortSignal.timeout(20_000), + }); + if (!response.ok) throw new Error(`GitHub answered http ${response.status}`); + const pulls = (await response.json()) as { + number: number; + title: string; + draft: boolean; + html_url: string; + created_at: string; + user: { login: string }; + head: { ref: string }; + }[]; + if (!Array.isArray(pulls)) throw new Error("GitHub returned an invalid pull request list"); + return pulls.map((pull) => ({ + number: pull.number, + title: pull.title, + draft: pull.draft, + url: pull.html_url, + created: pull.created_at.slice(0, 16), + author: pull.user.login, + branch: pull.head.ref, + })); +} diff --git a/pm-stack/console/edge/src/worker.ts b/pm-stack/console/edge/src/worker.ts index 934517fe6a..fdab3e3df9 100644 --- a/pm-stack/console/edge/src/worker.ts +++ b/pm-stack/console/edge/src/worker.ts @@ -10,11 +10,16 @@ import { DurableObject } from "cloudflare:workers"; import { Edge } from "./edge.ts"; import { route } from "./entry.ts"; +import { readOpenPullRequests } from "./github.ts"; interface Env { PM: DurableObjectNamespace; ASSETS: { fetch(request: Request): Promise }; PUBLIC_HOST: string; + /** Optional read-only GitHub token; provisioned as a Worker secret. */ + GITHUB_TOKEN?: string; + /** Explicit opt-in; reads stay disabled unless set to `on`. */ + GITHUB_READ_ENABLED?: string; VERSION?: string; /** Local development only: where the host is, when it is not simply * behind this hostname's route. Never set where this is deployed. */ @@ -36,6 +41,17 @@ export class PmEdge extends DurableObject { }, }, setAlarm: (at) => ctx.storage.setAlarm(at), + // The object's own waitUntil: a background read outlives the + // response that started it. + later: (work) => ctx.waitUntil(work), + githubReadEnabled: env.GITHUB_READ_ENABLED === "on", + githubTokenConfigured: Boolean(env.GITHUB_TOKEN), + freshRead: env.GITHUB_READ_ENABLED === "on" && env.GITHUB_TOKEN + ? (section, config) => + section === "prs" + ? readOpenPullRequests(config.repo, env.GITHUB_TOKEN as string) + : Promise.reject(new Error("unsupported edge read")) + : undefined, }); } diff --git a/pm-stack/console/src/docs.ts b/pm-stack/console/src/docs.ts index d74c154c28..db1bd61cf9 100644 --- a/pm-stack/console/src/docs.ts +++ b/pm-stack/console/src/docs.ts @@ -96,10 +96,15 @@ export class Docs { const loaded = await s.load(); const now = this.now(); // A copy read elsewhere is as old as that read, never newer than now. - s.data = loaded instanceof Stamped ? loaded.data : loaded; - s.goodAt = loaded instanceof Stamped ? Math.min(now, loaded.at) : now; - s.error = loaded instanceof Stamped ? loaded.error : null; - s.ok = s.error === null; + const loadedAt = loaded instanceof Stamped ? Math.min(now, loaded.at) : now; + // A read that finishes after a newer one must not put its older + // copy back: the section keeps the freshest data it has. + if (loadedAt >= s.goodAt) { + s.data = loaded instanceof Stamped ? loaded.data : loaded; + s.goodAt = loadedAt; + s.error = loaded instanceof Stamped ? loaded.error : null; + s.ok = s.error === null; + } } catch (error) { s.ok = false; s.error = (error as Error).message.slice(0, 300); @@ -116,10 +121,37 @@ export class Docs { await Promise.all(names.map((n) => this.refresh(n))); } + /** Record a section read by another trusted source, such as the edge + * reading GitHub while the laptop is away. */ + record(name: string, data: unknown, at = this.now()): void { + const s = this.sections.get(name); + if (!s) return; + s.data = data; + s.at = at; + s.goodAt = at; + s.ok = true; + s.error = null; + } + + /** Keep the last good value, but say that a fresh read failed. */ + recordFailure(name: string, error: unknown): void { + const s = this.sections.get(name); + if (!s) return; + s.at = this.now(); + s.ok = false; + s.error = (error as Error).message.slice(0, 300); + } + private stale(s: Section): boolean { return this.now() - s.at > s.ttlMs; } + /** Whether a section is due a fresh read: never read, or older than its interval. */ + isStale(name: string): boolean { + const s = this.sections.get(name); + return s !== undefined && this.stale(s); + } + /** One pass of the background loop: refresh what is stale, if anyone is looking. */ tick(): void { if (this.now() - this.asked > WATCH_MS) return; diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index cc9428d307..f7b9c28a5a 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -14,6 +14,7 @@ import { beforeEach, describe, expect, test } from "bun:test"; import { Edge, type KV, SILENT_MS } from "../edge/src/edge.ts"; import { forgetPoke, type Io, route } from "../edge/src/entry.ts"; +import { readOpenPullRequests } from "../edge/src/github.ts"; import type { Action } from "../src/actions.ts"; import { clearJwksCache, identify } from "../src/auth.ts"; import { readConfig } from "../src/config.ts"; @@ -51,7 +52,7 @@ const SECTION_NAMES = [ "more", ]; -async function setup() { +async function setup(options: { freshRead?: (section: string, config: EdgeConfig) => Promise } = {}) { const now = { t: START }; const clock = () => now.t; const access = await signer("k1"); @@ -86,14 +87,18 @@ async function setup() { }, }; const alarm = { at: 0 }; + /** Work the edge schedules after a response: the stand-in for waitUntil. */ + const later: Promise[] = []; const makeEdge = () => new Edge({ kv, now: clock, fetchImpl: outward as never, + freshRead: options.freshRead, setAlarm: async (at) => { alarm.at = at; }, + later: (work) => later.push(work), }); const edge = { now: makeEdge() }; @@ -216,7 +221,6 @@ async function setup() { }; // ---- the Worker's routing, with the two wired together ----------------- - const later: Promise[] = []; const files = new Map([ ["/console/index.html", "PM"], ["/console/app.js", "// app"], @@ -366,6 +370,9 @@ describe("before the host's first report", () => { ok: true, edge: true, configured: false, + githubReadEnabled: false, + githubTokenConfigured: false, + githubReadReady: false, hostSeen: null, answered: 0, deferred: 0, @@ -408,6 +415,107 @@ describe("before the host's first report", () => { }); }); +describe("fresh GitHub reads while the host is away", () => { + test("uses the read-only GitHub boundary and maps pull requests for the console", async () => { + let request: { url: string; init?: RequestInit } | null = null; + const pulls = await readOpenPullRequests("developing-today/code", "test-token", async (url, init) => { + request = { url: String(url), init }; + return Response.json([ + { + number: 42, + title: "Fresh PR", + draft: false, + html_url: "https://github.com/developing-today/code/pull/42", + created_at: "2026-11-22T12:34:56Z", + user: { login: "worker" }, + head: { ref: "queue/42" }, + }, + ]); + }); + expect(request?.url).toBe("https://api.github.com/repos/developing-today/code/pulls?state=open&per_page=60"); + expect(new Headers(request?.init?.headers).get("authorization")).toBe("Bearer test-token"); + // GitHub rejects requests without one, and a Worker sends none by default. + expect(new Headers(request?.init?.headers).get("user-agent")).toBe("pm-console-edge"); + expect(pulls).toEqual([ + { + number: 42, + title: "Fresh PR", + draft: false, + url: "https://github.com/developing-today/code/pull/42", + created: "2026-11-22T12:34", + author: "worker", + branch: "queue/42", + }, + ]); + }); + + test("refreshes pull requests only after the host is silent", async () => { + const reads: string[] = []; + const w = await setup({ + freshRead: async (section, config) => { + reads.push(`${section}:${config.repo}`); + return [{ number: 42, title: "Fresh PR", url: "https://example.test/pr/42" }]; + }, + }); + await w.hostReads(); + await w.link.now.once(); + const before = await w.browse("/console/api/doc/ops"); + expect((await before.json()).prs).toEqual([]); + expect(reads).toEqual([]); + + w.hostSaw.length = 0; + w.net.hostUp = false; + // Past both the silence gate (60s) and the prs interval (90s). + w.now.t += 91_000; + // The document answers at once, from what the host last reported. + const first = await w.browse("/console/api/doc/ops"); + expect((await first.json()).prs).toEqual([]); + // The fresh read finishes after the response, through waitUntil. + await Promise.all(w.later); + const fresh = await w.browse("/console/api/doc/ops"); + expect((await fresh.json()).prs).toEqual([ + { number: 42, title: "Fresh PR", url: "https://example.test/pr/42" }, + ]); + expect(reads).toEqual(["prs:developing-today/code"]); + expect(w.hostSaw).toEqual([]); + // A second poll inside the interval asks GitHub for nothing more. + await w.browse("/console/api/doc/ops"); + expect(reads).toEqual(["prs:developing-today/code"]); + }); + + test("a failed fresh read after a restart keeps the laptop's last pull requests", async () => { + const w = await setup({ + freshRead: async () => { + throw new Error("GitHub is down"); + }, + }); + w.data.prs = [ + { + number: 7, + title: "Host PR", + draft: false, + url: "https://example.test/pr/7", + created: "2026-11-22T11:00", + author: "worker", + branch: "queue/7", + }, + ]; + await w.hostReads(); + await w.link.now.once(); + // The object restarts with the laptop away: nothing in memory. + w.edge.now = w.makeEdge(); + w.net.hostUp = false; + w.now.t += 91_000; + await w.browse("/console/api/doc/ops"); + await Promise.all(w.later); + // The last good list is still shown, and the failed read is said to have failed. + const again = await w.browse("/console/api/doc/ops"); + const doc = (await again.json()) as Record; + expect(doc.prs).toEqual(w.data.prs); + expect(doc.health.prs).toEqual({ ok: false, error: "GitHub is down" }); + }); +}); + describe("the owner, at the edge", () => { test("the app and its state come from the edge, and only for a verified owner", async () => { const w = await setup();