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 d79a493dd0..1d9b9f4945 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 @@ -549,3 +549,56 @@ 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. + +## 2026-11-23T16:50Z Update: step 4 in service, and step 5 (machines) + +**Step 4 is in service.** Merged as #13287 after four rounds of review +(thirteen findings, all real, each with a test and most with a check +in a real browser that fails against the code before its fix). At +16:38Z the Worker and the laptop both ran `2a96e875037d`; the Worker +said it does the core itself and had been turned away for nothing. + +Seen in that answer: the Worker's own read of pull requests had failed +a quarter of an hour earlier with GitHub's "rate limit exceeded" for +the owner's account. The Worker's token is the fleet's, and the fleet +had used the hour's allowance. The Worker treats that as "one too many +just now" and asks again in five minutes, which is right; but a +platform whose core reads stop when agents are busy is not doing the +core by itself. Filed with the gaps: its own allowance. + +**Step 5 is built: the laptop is a machine.** Decision 5 above, as it +turned out: + +- **A machine says what it is.** Each report carries the machine's name + and what it can do: the kinds of action it has and the sections it + reads. The edge keeps what it last said beside when it last reported. + A console older than this says nothing, and is shown as a machine + that has not said what it can do. +- **The edge answers for the whole.** `GET /console/api/machines` is + answered at the edge with no machine asked: what the edge does itself + right now, each machine and whether it is reporting, and what waits + for one. A machine serving the app by itself answers the same read + with itself. +- **What waits can be taken back.** `held.drop` removes one held action + before a machine has it, and records it as not sent under its name, + so the device that sent it learns so. +- **The screen** (More, Machines) says each of those in words, and that + one machine can be connected today. + +What this does not do yet, and is filed: a second machine under its own +key; each action sent to a machine that can do it (today there is one, +so "a machine" is "the machine"); what is held kept per machine. + +Review found two faults, both real. Taken back, an action could be +kept again when a device that never heard it was kept offered it again: +taking back now ends the name, and the offer is answered "taken back". +And the screen did not notice a machine going quiet unless something +else changed: it now asks again while it is open, and is drawn again +when what it shows has changed. + +Checked: 351 tests under bun. 28 planted faults in the new code, all +caught. In a real Chrome against both demos, light and dark: the +screen with nothing in front of the machine and with the edge in front; +something held while the machine is out of reach, listed in the owner's +words, taken back after a question, and recorded as not sent. axe-core +over 21 screens and the new dialog: no violations. diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index d4f6463843..2abfb1216e 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -178,6 +178,40 @@ 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. +### Machines + +This host is a machine, and the platform treats it as one of however +many there are. A machine is anything that reports to the edge under a +key the edge knows. In every report it says what it is called +(`PM_CONSOLE_MACHINE`, or the host's own name) and what it can do: the +kinds of action it has, and the sections it reads. Nothing about a +machine is assumed from its being "the laptop". + +More, Machines shows: + +- **Cloudflare's own part**: whether it does the core itself, and what + it was turned away for lately. +- **Each machine**: whether it is reporting and when it was last heard + from, the commit it runs, and what only it reports and only it can + do, in words. What Cloudflare does itself is not counted as the + machine's. +- **What waits for a machine**: everything the owner did that is held + until one is back, oldest first, each with "Take back" (`held.drop`). + Taken back, it is recorded as not sent under its name, so the device + that sent it shows it under "could not be done"; offered again by a + device that never heard it was kept, it stays taken back. + +The screen keeps itself current while it is open: a machine going +quiet or coming back, or something new waiting, draws it again. + +The edge answers that screen itself, so it is there with every machine +away. Served straight from a machine, the machine answers with itself. + +One machine can report today: the one the tunnel leads to, whose key is +the only one the edge takes reports under. Enrolling another under its +own key, and sending each action to a machine that can do it, are not +built. + ### With no connection The app opens and can be used with no connection, in a browser and in @@ -333,21 +367,22 @@ the route if the console does not come up with its sign-in settings. ## Configuration -| Variable | Default | Meaning | -| --------------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -| `PM_CONSOLE_PORT`, `PM_CONSOLE_BIND` | `4872`, `127.0.0.1` | Listener; the address must be loopback | -| `PM_CONSOLE_OWNER_EMAILS` | none (nobody) | Comma-separated owner addresses | -| `PM_CONSOLE_ACCESS_TEAM_DOMAIN`, `PM_CONSOLE_ACCESS_AUD` | unset | The Access issuer; set together | -| `PM_CONSOLE_ISSUERS_FILE` | unset | JSON list of further issuers | -| `PM_CONSOLE_CERT_NAMES` | none | Certificate common names that are the owner | -| `PM_CONSOLE_DASHBOARD_URL` | `http://127.0.0.1:4870` | The dashboard behind the gate; loopback, or empty | -| `PM_CONSOLE_UNITS`, `PM_CONSOLE_PROTECTED_UNITS` | the stack's units | Units the console manages; units it will not stop | -| `PM_CONSOLE_ANDROID_PACKAGE`, `PM_CONSOLE_ANDROID_SHA256` | `today.developing.pmconsole`, none | The Android app's identity in the asset-links file | -| `PM_CONSOLE_ANDROID_APK` | `~/.local/state/pm-console/android/pm-console.apk` | The signed build the console hands to the owner | -| `PM_CONSOLE_DEVICES_FILE` | `~/.local/state/pm-console/devices.json` | Linked phones (hashes of their tokens) | -| `PM_CONSOLE_EDGE_URL` | unset (reports to nobody) | The public address the edge answers on, `https://` | -| `PM_CONSOLE_EDGE_KEY_FILE`, `PM_CONSOLE_EDGE_DONE_FILE` | `edge-key.json`, `edge-done.json` in the state dir | This host's signing key; what it ran for the edge | -| `PM_CONSOLE_REPO`, `PM_CONSOLE_QUEUE` | `developing-today/code`, `repo-health-code-pilot` | What it operates on | +| Variable | Default | Meaning | +| --------------------------------------------------------- | -------------------------------------------------- | ----------------------------------------------------- | +| `PM_CONSOLE_PORT`, `PM_CONSOLE_BIND` | `4872`, `127.0.0.1` | Listener; the address must be loopback | +| `PM_CONSOLE_OWNER_EMAILS` | none (nobody) | Comma-separated owner addresses | +| `PM_CONSOLE_ACCESS_TEAM_DOMAIN`, `PM_CONSOLE_ACCESS_AUD` | unset | The Access issuer; set together | +| `PM_CONSOLE_ISSUERS_FILE` | unset | JSON list of further issuers | +| `PM_CONSOLE_CERT_NAMES` | none | Certificate common names that are the owner | +| `PM_CONSOLE_DASHBOARD_URL` | `http://127.0.0.1:4870` | The dashboard behind the gate; loopback, or empty | +| `PM_CONSOLE_UNITS`, `PM_CONSOLE_PROTECTED_UNITS` | the stack's units | Units the console manages; units it will not stop | +| `PM_CONSOLE_ANDROID_PACKAGE`, `PM_CONSOLE_ANDROID_SHA256` | `today.developing.pmconsole`, none | The Android app's identity in the asset-links file | +| `PM_CONSOLE_ANDROID_APK` | `~/.local/state/pm-console/android/pm-console.apk` | The signed build the console hands to the owner | +| `PM_CONSOLE_DEVICES_FILE` | `~/.local/state/pm-console/devices.json` | Linked phones (hashes of their tokens) | +| `PM_CONSOLE_EDGE_URL` | unset (reports to nobody) | The public address the edge answers on, `https://` | +| `PM_CONSOLE_EDGE_KEY_FILE`, `PM_CONSOLE_EDGE_DONE_FILE` | `edge-key.json`, `edge-done.json` in the state dir | This host's signing key; what it ran for the edge | +| `PM_CONSOLE_MACHINE` | the host's own name | What this machine is called where machines are listed | +| `PM_CONSOLE_REPO`, `PM_CONSOLE_QUEUE` | `developing-today/code`, `repo-health-code-pilot` | What it operates on | A malformed port, a listen address or dashboard address that is not loopback, an edge address that is not plain `https://host`, or a diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index f147fed566..b4b7ff2a95 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -36,6 +36,16 @@ action is the laptop's, relayed at once or held. The list of actions that may be done late is `HOLDABLE` in `../src/edge-proto.ts`. +"A machine" above is whatever reports under the key the edge holds. It +says what it is called and what it can do in each report (`machine` in +the report: its name, the kinds of action it has, the sections it +reads), and the edge keeps what it last said beside when it last +reported. `GET /console/api/machines` answers from that with no machine +asked: what the edge does itself right now (its own actions always, the +core when it has the means, less what it was turned away for), each +machine, and what is held. `held.drop` takes one held action back +before a machine has it, and records it as not sent under its name. + ## How it is put together ``` diff --git a/pm-stack/console/edge/src/direct.ts b/pm-stack/console/edge/src/direct.ts index a3cefe35b1..40152aca69 100644 --- a/pm-stack/console/edge/src/direct.ts +++ b/pm-stack/console/edge/src/direct.ts @@ -211,6 +211,7 @@ export function directConfig(edge: EdgeConfig): Config { edgeUrl: null, edgeKeyFile: "", edgeDoneFile: "", + machineName: "", decisionsFile: "", promptLabel: edge.promptLabel, needsRepos: edge.needsRepos, diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index cdb03c6ce1..5765a17d0c 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -47,6 +47,9 @@ import { type Held, HOLDABLE, keyId, + type MachineReport, + type MachinesAnswer, + machineReport, type PublicKey, publicKey, subjectOf, @@ -298,6 +301,10 @@ export class Edge { private sure = 0; private unsure = 0; private hostVersion: string | null = null; + /** What the machine that reports says of itself: its name and what + * it can do. Null until one has said, or from a console older than + * the saying. */ + private machine: MachineReport | 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. */ @@ -380,6 +387,43 @@ export class Edge { touch: [], audit: () => ({}), }, + // Something waiting for a machine is taken back by the owner + // before one has it. (One a machine was already handed may still + // be done: its answer then finds nothing waiting, and is let go.) + "held.drop": { + run: async (a) => { + await this.ready(); + const held = await this.heldList(); + const at = held.findIndex((h) => h.id === a.id); + if (at < 0) { + throw new OpError(404, "That is no longer waiting: a machine took it, or it was taken back already."); + } + const [gone] = held.splice(at, 1); + await this.saveHeld(); + // Under its name it is over. A device that never heard it was + // kept offers it again: it is told it was taken back, and it + // is neither kept again nor handed to a machine. + await this.kv.put(`a:${gone.id}`, { + at: this.now(), + kind: gone.kind, + state: "done", + status: 410, + body: { error: "This was taken back before a machine took it." }, + } satisfies Acted); + await this.actedIndex(gone.id); + await this.logAct({ + id: gone.id, + kind: gone.kind, + at: gone.at, + by: gone.who, + status: "failed", + note: "Not sent: taken back before a machine took it.", + }); + return { dropped: gone.id, kind: gone.kind }; + }, + touch: [], + audit: (a) => ({ id: a.id }), + }, }; } @@ -622,6 +666,46 @@ export class Edge { await this.showEdge(); } + /** The platform's own part, each machine that reports, and what is + * held for one: what the Machines screen is drawn from. Answered + * here, so it is there with every machine away. */ + private async machinesSaid(cfg: EdgeConfig | null): Promise { + await this.ready(); + const primary = this.primary(cfg); + const refused = this.refusedKinds(); + const seen = this.hostSeen || null; + return { + served: "edge", + platform: { + primary, + // What it does itself right now. Its own (notifications, linked + // phones, what is held) always; the core when it has the means, + // less what it was turned away for and a machine does for the hour. + actions: [ + ...Object.keys(this.table).sort(), + ...(primary ? (DIRECT_ACTIONS as readonly string[]).filter((kind) => !refused.includes(kind)) : []), + ], + sections: primary ? this.owned(cfg) : [], + refused: [...refused, ...this.refusedReads().map((name) => `read.${name}`)], + }, + // One machine can report today: the one whose key this side holds. + machines: + seen === null + ? [] + : [ + { + name: this.machine?.name ?? "A machine", + seen, + quiet: this.now() - seen >= HOST_QUIET_MS, + version: this.hostVersion, + actions: this.machine?.actions ?? [], + sections: this.machine?.sections ?? [], + }, + ], + held: [...(await this.heldList())], + }; + } + /** What the app is told of this side, beside its state: how much is * waiting for a machine, and whether this side does the core itself. */ private async showEdge(): Promise { @@ -672,12 +756,14 @@ export class Edge { seq: number; confirmed?: Record; version?: string | null; + machine?: unknown; } | undefined; this.hostSeen = host?.seen ?? 0; this.hostSeq = host?.seq ?? 0; this.confirmed = host?.confirmed ?? {}; this.hostVersion = host?.version ?? null; + this.machine = machineReport(host?.machine); } if (!this.awayRead) { this.awayRead = true; @@ -1175,7 +1261,14 @@ export class Edge { this.hostSeen = now; this.hostSeq = msg.at; this.hostVersion = typeof msg.version === "string" && /^[0-9a-f]{7,40}$/.test(msg.version) ? msg.version : null; - await this.kv.put("host", { seen: now, seq: msg.at, confirmed: this.confirmed, version: this.hostVersion }); + this.machine = machineReport(msg.machine); + await this.kv.put("host", { + seen: now, + seq: msg.at, + confirmed: this.confirmed, + version: this.hostVersion, + machine: this.machine, + }); if (wasSilent) { try { const delivery = await this.push.send("trouble", { @@ -1480,6 +1573,7 @@ export class Edge { } if (seg.length === 1 && seg[0] === "push") return json(await this.push.status()); if (seg.length === 1 && seg[0] === "devices") return json(await this.phones.devices.list()); + if (seg.length === 1 && seg[0] === "machines") return json(await this.machinesSaid(cfg)); // What needs only GitHub and the queue store is read here, by // the code a machine would read it with. const mine = this.mine(cfg); diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 2562cda6e6..99e5dcd8b5 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -1128,6 +1128,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/machines", "Machines", "each machine, what only it can do, and what waits for one"), 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"), ), @@ -2017,6 +2018,182 @@ async function viewAway() { ]; } +/** What each kind of action is, in a few words: for saying what the + * platform does itself and what only a machine can. */ +const CAN_SAID = { + "ask.send": "send a prompt", + "ask.reply": "reply on a prompt", + "ask.close": "close a prompt", + "issue.comment": "comment on an issue", + "need.comment": "reply on something that needs you", + "issue.rank": "rank an issue", + "task.move": "move a task", + "task.cancel": "cancel a task", + "task.unblock": "unblock a task", + "pr.merge": "merge", + "deploy.start": "start a deploy", + "intake.send": "file a note, a bug or a change", + "question.answer": "record an answer", + "question.defer": "hand a question back", + "questions.accept": "accept the recommended answers", + "hands.done": "mark something for your hands done", + "message.send": "message an agent", + "unit.act": "start, stop or restart a unit", + "sso.google": "set up Google sign-in", + "edge.direct": "turn Cloudflare's own doing on or off", + "prompt.enqueue": "file a prompt's task in the queue", + "triage.enqueue": "file a triage task in the queue", + "push.on": "turn notifications on for a device", + "push.off": "turn notifications off for a device", + "push.class": "choose which notifications a device gets", + "push.test": "send a test notification", + "device.approve": "link a phone", + "device.remove": "remove a phone", +}; +/** What each section of the state is, in a few words. One with no + * words of its own is part of another (the count of questions). */ +const SECTION_SAID = { + board: "the board", + sessions: "sessions", + census: "what needs you", + asks: "your prompts", + questionCount: "", + questions: "questions", + prs: "pull requests", + priorities: "ranked issues", + agents: "agents", + services: "its units", + more: "the dashboard's pages", +}; + +/** A list in words: "a, b and c". */ +export const listed = (items) => (items.length <= 1 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`); + +/** One machine as the Machines screen says it: whether it is + * reporting, what it runs, and what only it reports and does. What the + * platform does itself (`platform`, null when nothing is in front of + * the machine) is not counted as the machine's. */ +export function machineSaid(machine, platform, now = Date.now()) { + const theirs = new Set(platform?.sections || []); + const done = new Set(platform?.actions || []); + const words = (names, said) => [...new Set(names.map((name) => (name in said ? said[name] : name)).filter(Boolean))]; + const when = machine.seen === null ? "" : ago(new Date(machine.seen).toISOString(), now); + return { + name: machine.name, + reporting: machine.seen !== null && !machine.quiet, + state: machine.seen === null ? "It has never reported." : machine.quiet ? `Not reporting. Last heard from ${when}.` : `Reporting. Last heard from ${when}.`, + version: machine.version ? String(machine.version).slice(0, 7) : "", + reports: words((machine.sections || []).filter((name) => !theirs.has(name)), SECTION_SAID), + does: words((machine.actions || []).filter((kind) => !done.has(kind)), CAN_SAID), + // A console older than this screen does not say what it can do. + said: (machine.actions || []).length + (machine.sections || []).length > 0, + }; +} + +/** What the Machines screen shows that can change with nothing else + * changing: who is reporting, what the platform does itself, what + * waits. When a machine was last heard from changes with every report + * and is left out, except by the minute once it has gone quiet (the + * screen says for how long). The screen is drawn again when this is + * no longer what it was drawn from. */ +export function machinesMark(m, now = Date.now()) { + return JSON.stringify({ + platform: m?.platform ? [m.platform.primary, m.platform.refused, m.platform.actions.length, m.platform.sections.length] : null, + machines: (m?.machines || []).map((x) => [ + x.name, + x.quiet, + x.version, + (x.actions || []).length, + (x.sections || []).length, + x.quiet && x.seen ? Math.floor((now - x.seen) / 60_000) : 0, + ]), + held: (m?.held || []).map((item) => item.id), + }); +} +let machinesDrawn = ""; + +/** Machines: the platform's own part, each machine that reports and + * what only it can do, and what waits for one. */ +async function viewMachines() { + const m = await api("machines"); + machinesDrawn = machinesMark(m); + const platform = m.platform; + const held = Array.isArray(m.held) ? m.held : []; + const takeBack = async (item, e) => { + const queueOnly = item.kind === "prompt.enqueue" || item.kind === "triage.enqueue"; + const sure = await ask({ + title: "Take this back?", + text: queueOnly + ? `${Outbox.sayOf(item.kind, item.args)}. The issue stays; without its task the fleet will not pick it up by itself.` + : `${Outbox.sayOf(item.kind, item.args)}. It will not be done. If a machine has already been handed it, it may still be.`, + okLabel: "Take back", + danger: true, + }); + if (sure === null) return; + if (await act("held.drop", { id: item.id }, "Taken back", e.target)) draw(); + }; + const out = [ + card( + h("h3", {}, "Cloudflare"), + h( + "p", + { class: "meta" }, + platform === null + ? "Not in front right now: the app is coming straight from the machine below, which does everything." + : platform.primary + ? "Does the core itself, with a machine connected or not. A machine reports what only it has and does what only it can." + : "Serves the app and keeps what you send. A machine does the rest.", + ), + platform?.refused?.length ? h("p", { class: "why" }, `Turned away lately for ${listed(platform.refused.map((kind) => REFUSED_SAID[kind] || String(kind)))}: a machine does that for now.`) : null, + platform === null ? null : h("div", { class: "row end" }, h("button", { class: "small ghost", onclick: () => go("more/away") }, "What it does")), + ), + h("h2", {}, `Machines (${m.machines.length})`), + ]; + if (m.machines.length === 0) out.push(card(h("p", { class: "meta" }, "No machine has reported yet."))); + for (const machine of m.machines) { + const s = machineSaid(machine, platform); + out.push( + card( + h("div", { class: "row" }, chip(s.reporting ? "reporting" : "away", s.reporting ? "good" : "warn")), + h("h3", {}, s.name), + h("p", { class: "meta" }, [s.state, s.version ? `Running ${s.version}.` : ""].filter(Boolean).join(" ")), + !s.said + ? h("p", { class: "meta" }, "It has not said what it can do: its console is older than this screen.") + : platform === null + ? h("p", {}, "It reports everything and does everything: nothing is in front of it.") + : [ + s.reports.length ? h("p", {}, h("b", {}, "Only it reports: "), `${listed(s.reports)}.`) : null, + s.does.length + ? h("details", {}, h("summary", {}, `Only it can do ${s.does.length} thing${s.does.length === 1 ? "" : "s"}`), h("ul", { class: "plain" }, s.does.map((what) => h("li", {}, what)))) + : h("p", { class: "meta" }, "Nothing is left that only it can do."), + ], + ), + ); + } + out.push(h("h2", {}, `Waiting for a machine (${held.length})`)); + if (held.length === 0) out.push(card(h("p", { class: "meta" }, "Nothing is waiting."))); + for (const item of held) { + out.push( + card( + h("h3", {}, Outbox.sayOf(item.kind, item.args)), + h("p", { class: "meta" }, `${item.who} ยท ${ago(item.at)}`), + h("div", { class: "row end" }, h("button", { class: "small ghost", onclick: (e) => takeBack(item, e) }, "Take back")), + ), + ); + } + out.push( + h("h2", {}, "More than one"), + card( + h( + "p", + { class: "meta" }, + "One machine can be connected today: the one the tunnel leads to, whose key is the only one Cloudflare takes reports under. Connecting others, each under its own key and with what it can do, is not built yet.", + ), + ), + ); + return out; +} + /** 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) { @@ -2049,6 +2226,7 @@ export function everyRead(caps, edge) { "messages?limit=15", "push", "devices", + "machines", "signin", ...(edge ? ["android"] : []), ]; @@ -2636,6 +2814,7 @@ const VIEWS = { "more/phone": ["Phones", viewPhone], "more/signin": ["Sign-in", viewSignin], "more/away": ["Cloudflare", viewAway], + "more/machines": ["Machines", viewMachines], "more/device": ["On this device", viewDevice], "more/releases": ["Releases", viewReleases], "more/roadmap": ["Roadmap", viewRoadmap], @@ -2805,6 +2984,14 @@ async function refresh(force) { changed = await loadDoc("core"); loadError = ""; if (extra) changed = (await loadDoc(extra)) || changed; + // The Machines screen is drawn from an answer of its own, which can + // change with nothing else changing (a machine goes quiet, or comes + // back as it was). While that screen is open it is asked again, and + // the screen is drawn again when it says something else. + if (name === "more/machines") { + const now = await api("machines").catch(() => null); + if (now && machinesMark(now) !== machinesDrawn) changed = true; + } // 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. diff --git a/pm-stack/console/public/outbox.js b/pm-stack/console/public/outbox.js index b57572ae2b..4e909a8dbc 100644 --- a/pm-stack/console/public/outbox.js +++ b/pm-stack/console/public/outbox.js @@ -141,6 +141,12 @@ return `Message to ${Array.isArray(a.to) ? a.to.join(", ") : a.to}${quoted(a.text)}`; case "unit.act": return `${a.action} ${a.unit}`; + // The platform's own second half of something it filed itself: + // never kept here, and shown where what waits for a machine is. + case "prompt.enqueue": + return `File the queue task for prompt #${a.issue}`; + case "triage.enqueue": + return `File the triage task for #${a.issue}`; default: return String(kind); } diff --git a/pm-stack/console/scripts/demo-state.ts b/pm-stack/console/scripts/demo-state.ts index 781d22a30a..8bd28ca309 100644 --- a/pm-stack/console/scripts/demo-state.ts +++ b/pm-stack/console/scripts/demo-state.ts @@ -651,6 +651,8 @@ const table = new Proxy({} as Record>, { : { ok: true }, ), has: () => true, + // The kinds a real machine has, for where what it can do is listed. + ownKeys: () => Object.keys(real), getOwnPropertyDescriptor: () => ({ configurable: true, enumerable: true, value: done({}) }), }); @@ -668,6 +670,8 @@ export const demoDeps: Deps = { // 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()), + // What this machine is called where machines are listed. + self: { name: "framework", version: "0123abcd4567" }, 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 f7867965b6..92ad5e5dd3 100644 --- a/pm-stack/console/scripts/edge-demo.ts +++ b/pm-stack/console/scripts/edge-demo.ts @@ -96,6 +96,8 @@ const link = new EdgeLink({ done: memoryStore(), // One record with the host's own handler, as on the real host. named: demoDeps.named as Named, + machine: () => ({ name: "framework", actions: Object.keys(demoDeps.actions ?? {}).sort() }), + version: "0123abcd4567", docs: demoDocs, phones: demoDeps.phones!.devices, config: async () => ({ diff --git a/pm-stack/console/src/config.ts b/pm-stack/console/src/config.ts index df67eeb583..15546a4ffa 100644 --- a/pm-stack/console/src/config.ts +++ b/pm-stack/console/src/config.ts @@ -3,6 +3,7 @@ // decimal digits only, range-checked, and a bad value stops the process // at boot naming the variable. import { readFileSync } from "node:fs"; +import { machineName } from "./edge-proto.ts"; /** A token issuer whose signed tokens identify a caller. */ export interface Issuer { @@ -61,6 +62,9 @@ export interface Config { edgeKeyFile: string; /** What became of each action the edge held for this host. */ edgeDoneFile: string; + /** What this machine is called, where machines are listed. Empty when + * the environment does not say: the host's own name is used then. */ + machineName: string; /** The dashboard's decision-set store: the questions waiting on the * owner, and the per-set tokens that authorise an answer. */ decisionsFile: string; @@ -256,6 +260,7 @@ export function readConfig( edgeUrl, edgeKeyFile: env.PM_CONSOLE_EDGE_KEY_FILE ?? `${home}/.local/state/pm-console/edge-key.json`, edgeDoneFile: env.PM_CONSOLE_EDGE_DONE_FILE ?? `${home}/.local/state/pm-console/edge-done.json`, + machineName: machineName(env.PM_CONSOLE_MACHINE), decisionsFile: env.PM_CONSOLE_DECISIONS_FILE ?? `${home}/.local/state/pm-aggregator/decisions.json`, promptLabel: env.PM_CONSOLE_PROMPT_LABEL ?? "owner/prompt", needsRepos: list(env, "PM_CONSOLE_NEEDS_REPOS", [ diff --git a/pm-stack/console/src/docs.ts b/pm-stack/console/src/docs.ts index 1c2317ff52..08215f71cd 100644 --- a/pm-stack/console/src/docs.ts +++ b/pm-stack/console/src/docs.ts @@ -134,6 +134,11 @@ export class Docs { } } + /** Every section there is a reader for, read yet or not. */ + names(): string[] { + return [...this.sections.keys()]; + } + /** Read these sections now. A read already under way is shared. */ async touch(names: string[]): Promise { await Promise.all(names.map((n) => this.refresh(n))); diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index 5367830c41..33adbd1510 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -66,6 +66,10 @@ export interface SyncRequest { * health answer, so whether a merge has reached the host can be seen * from anywhere, without reaching the host. */ version?: string; + /** What this machine is called and what it can do. Absent from a + * console older than this: the edge then knows it only as a machine + * that reports. */ + machine?: MachineReport; config: EdgeConfig; /** Sections that changed since the edge last had them. */ sections: SyncSection[]; @@ -81,6 +85,69 @@ export interface SyncRequest { phones: PhoneLinks; } +/** What a machine says of itself in each report. A machine is anything + * that reports to the edge under a key the edge knows. It reports the + * state only it has (`sections`) and does what only it can (`actions`, + * by kind); everything else the platform does without it. */ +export interface MachineReport { + name: string; + actions: string[]; + sections: string[]; +} + +const MACHINE_NAME = /^[A-Za-z0-9][A-Za-z0-9 ._-]{0,62}$/; +const MACHINE_CAN = /^[A-Za-z][A-Za-z0-9._-]{0,47}$/; +/** How many kinds of action, or sections, one machine may say it has. */ +const MACHINE_CAN_MAX = 200; + +/** A name fit to show for a machine, from whatever it is called + * locally; empty when nothing of it is. */ +export function machineName(value: unknown): string { + const name = String(value ?? "") + .trim() + .replace(/[^A-Za-z0-9 ._-]+/g, "-") + .replace(/^[^A-Za-z0-9]+/, "") + .slice(0, 63); + return MACHINE_NAME.test(name) ? name : ""; +} + +/** A machine's account of itself as a report may give it, or null. */ +export function machineReport(value: unknown): MachineReport | null { + const v = value as Record | null; + if (!v || typeof v !== "object") return null; + if (typeof v.name !== "string" || !MACHINE_NAME.test(v.name)) return null; + const list = (given: unknown): string[] | null => { + if (!Array.isArray(given) || given.length > MACHINE_CAN_MAX) return null; + if (!given.every((item) => typeof item === "string" && MACHINE_CAN.test(item))) return null; + return [...new Set(given as string[])].sort(); + }; + const actions = list(v.actions); + const sections = list(v.sections); + return actions && sections ? { name: v.name, actions, sections } : null; +} + +/** What the Machines screen is drawn from: the platform's own part, + * each machine that reports, and what is held for one. */ +export interface MachinesAnswer { + /** Who answered: the edge, or a machine serving the app by itself. */ + served: "edge" | "machine"; + /** What the platform does with no machine: null when it is not in + * front, and an empty list of each when it only serves and waits. */ + platform: { primary: boolean; actions: string[]; sections: string[]; refused: string[] } | null; + machines: { + name: string; + /** When it last reported, in milliseconds; null if it never has. */ + seen: number | null; + /** It has not reported for long enough to be taken for away. */ + quiet: boolean; + version: string | null; + actions: string[]; + sections: string[]; + }[]; + /** What the owner did that waits for a machine, oldest first. */ + held: Held[]; +} + export interface PhoneLinks { devices: { id: string; name: string; hash: string; createdAt: string; seenAt: string | null }[]; removed: { hash: string; at: string }[]; diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 6ef681654f..913182dfa0 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -12,9 +12,10 @@ import { createHash } from "node:crypto"; import { mkdirSync, readFileSync } from "node:fs"; import { appendFile } from "node:fs/promises"; +import { hostname } from "node:os"; import { dirname, join } from "node:path"; import { actions, perform } from "./actions.ts"; -import { HOLDABLE, type Held } from "./edge-proto.ts"; +import { HOLDABLE, type Held, type MachinesAnswer, machineName } from "./edge-proto.ts"; import { AuthError, type Identity, identify } from "./auth.ts"; import { type Config, readConfig } from "./config.ts"; import { Devices, Limiter } from "./devices.ts"; @@ -145,6 +146,9 @@ export interface Deps { * once however often it arrives. The link keeps one; a host with no * edge in front of it keeps its own. */ named?: Pick & Partial>; + /** What this machine is called and the commit it runs, for where + * machines are listed. */ + self?: { name: string; version?: string }; } /** Text that shrinks well. The dashboard's fragments run to a megabyte @@ -319,6 +323,26 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul } if (seg.length === 1 && seg[0] === "push" && deps.push) return json(await deps.push.status()); if (seg.length === 1 && seg[0] === "devices" && deps.phones) return json(await deps.phones.devices.list()); + if (seg.length === 1 && seg[0] === "machines") { + // Asked of this machine itself (the edge answers for itself when + // it is in front): one machine, this one, and nothing held. + const answer: MachinesAnswer = { + served: "machine", + platform: null, + machines: [ + { + name: deps.self?.name ?? "this machine", + seen: Date.now(), + quiet: false, + version: deps.self?.version ?? null, + actions: Object.keys(deps.actions ?? {}).sort(), + sections: (deps.docs?.names() ?? []).sort(), + }, + ], + held: [], + }; + return json(answer); + } if (seg.length === 1 && seg[0] === "signin") return json(await ops.signin()); if (seg.length === 1 && seg[0] === "question" && deps.work) { return json(await deps.work.question(query.get("set"), query.get("ledger"), query.get("qid"))); @@ -686,10 +710,15 @@ if (import.meta.main) { 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 version = await runningCommit(); + // What this machine is called: what it was told to be, or its own name. + const self = { name: cfg.machineName || machineName(hostname()) || "machine", version }; + deps.self = self; const link = cfg.edgeUrl ? new EdgeLink({ url: cfg.edgeUrl, - version: await runningCommit(), + version, + machine: () => ({ name: self.name, actions: Object.keys(deps.actions ?? {}).sort() }), apk: androidBuild(cfg.androidApk), keys: fileStore(cfg.edgeKeyFile), done: fileStore(cfg.edgeDoneFile), diff --git a/pm-stack/console/src/sync.ts b/pm-stack/console/src/sync.ts index a12fcd8e75..f54196d83d 100644 --- a/pm-stack/console/src/sync.ts +++ b/pm-stack/console/src/sync.ts @@ -18,6 +18,7 @@ import { type Held, HOLDABLE, keyId, + machineReport, newKeyPair, type PublicKey, type PhoneLinks, @@ -59,6 +60,8 @@ export interface LinkOptions { run: (held: Held) => Promise; /** The commit this console is running, if it could be found. */ version?: string; + /** What this machine is called, and the kinds of action it does. */ + machine?: () => { name: string; actions: 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>; @@ -234,11 +237,16 @@ export class EdgeLink { const have = Object.fromEntries(snapshot.map((s) => [s.name, { hash: s.hash, at: s.at, error: s.error }])); const phones = await this.o.phones.links(); const acts = this.o.docs.recentActs(); + // What this machine is and can do: every section it can read + // (those the edge reads itself included), and the actions it has. + const self = this.o.machine?.(); + const machine = self ? machineReport({ ...self, sections: this.o.docs.names() }) : null; const encoded = (carried: typeof sections) => { const message: SyncRequest & { acts: unknown } = { v: 1, at, ...(this.o.version ? { version: this.o.version } : {}), + ...(machine ? { machine } : {}), ...(apk ? { apk } : {}), config, sections: carried, diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index a283de76c5..507491d69a 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -25,6 +25,9 @@ import { keptGroups, keptSaid, levelHeadings, + listed, + machineSaid, + machinesMark, phaseHeading, prCheck, runSaid, @@ -656,6 +659,7 @@ test("keeping a copy of every screen reads each under the address its screen ask "messages?limit=15", "push", "devices", + "machines", "signin", "android", ]); @@ -678,6 +682,7 @@ test("keeping a copy of every screen reads each under the address its screen ask "messages?limit=15", "push", "devices", + "machines", "signin", ]); }); @@ -756,3 +761,116 @@ test("a question is left out of the list while its answer is kept and not yet re // 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"]); }); + +test("a machine, as the Machines screen says it: what only it reports and does, beside what the platform does itself", () => { + const now = Date.parse("2026-11-23T12:00:00Z"); + const machine = { + name: "nixos", + seen: now - 12_000, + quiet: false, + version: "0123abcd4567", + actions: ["ask.send", "issue.rank", "question.answer", "task.cancel", "unit.act", "push.on", "something.new"], + sections: ["board", "sessions", "questionCount", "questions", "services", "asks"], + }; + // The platform does the core itself: only what is left is the machine's. + const platform = { + primary: true, + actions: ["ask.send", "issue.rank", "push.on"], + sections: ["board", "asks"], + refused: [], + }; + expect(machineSaid(machine, platform, now)).toEqual({ + name: "nixos", + reporting: true, + state: "Reporting. Last heard from just now.", + version: "0123abc", + // The count of questions is part of the questions, not a thing of its own. + reports: ["sessions", "questions", "its units"], + // A kind this screen has no words for is said as it is named. + does: ["record an answer", "cancel a task", "start, stop or restart a unit", "something.new"], + said: true, + }); + // With nothing in front of it, everything is the machine's. + const alone = machineSaid(machine, null, now); + expect(alone.reports).toEqual(["the board", "sessions", "questions", "its units", "your prompts"]); + expect(alone.does).toContain("send a prompt"); + // Away, and for how long. + expect(machineSaid({ ...machine, seen: now - 2 * 3600_000, quiet: true }, platform, now)).toMatchObject({ + reporting: false, + state: "Not reporting. Last heard from 2 h ago.", + }); + expect(machineSaid({ ...machine, seen: null, quiet: true }, platform, now)).toMatchObject({ + reporting: false, + state: "It has never reported.", + }); + // A console older than this screen: a machine that has not said what it can do. + expect( + machineSaid( + { name: "A machine", seen: now, quiet: false, version: null, actions: [], sections: [] }, + platform, + now, + ), + ).toMatchObject({ + version: "", + reports: [], + does: [], + said: false, + }); + // Lists in words. + expect([listed([]), listed(["a"]), listed(["a", "b"]), listed(["a", "b", "c"])]).toEqual([ + "", + "a", + "a and b", + "a, b and c", + ]); +}); + +test("the Machines screen is drawn again when what it shows has changed, and not for a report that changed nothing", () => { + const now = Date.parse("2026-11-23T12:00:00Z"); + const machine = { + name: "nixos", + seen: now - 5_000, + quiet: false, + version: "0123abcd4567", + actions: ["a.b"], + sections: ["board"], + }; + const answer = (more: Record = {}) => ({ + served: "edge", + platform: { primary: true, actions: ["ask.send"], sections: ["board"], refused: [] }, + machines: [machine], + held: [{ id: "h1", kind: "task.move" }], + ...more, + }); + const mark = machinesMark(answer(), now); + // Another report from a machine that is still reporting changes nothing that is shown. + expect(machinesMark(answer({ machines: [{ ...machine, seen: now }] }), now + 5_000)).toBe(mark); + // Each of these does. + for (const [why, changed] of [ + ["it went quiet", answer({ machines: [{ ...machine, quiet: true }] })], + ["it runs another commit", answer({ machines: [{ ...machine, version: "fedcba987654" }] })], + ["it can do something more", answer({ machines: [{ ...machine, actions: ["a.b", "c.d"] }] })], + ["it is called something else", answer({ machines: [{ ...machine, name: "amd" }] })], + ["there is another", answer({ machines: [machine, { ...machine, name: "amd" }] })], + ["there is none", answer({ machines: [] })], + ["something else waits", answer({ held: [{ id: "h1" }, { id: "h2" }] })], + ["nothing waits", answer({ held: [] })], + [ + "the platform stopped doing the core", + answer({ platform: { primary: false, actions: [], sections: [], refused: [] } }), + ], + [ + "the platform was turned away for something", + answer({ platform: { primary: true, actions: [], sections: ["board"], refused: ["pr.merge"] } }), + ], + ["nothing is in front any more", answer({ platform: null })], + ] as const) { + expect([why, machinesMark(changed, now) === mark]).toEqual([why, false]); + } + // Gone quiet, it is drawn again as the minutes pass (the screen says how long), not with every look. + const quiet = answer({ machines: [{ ...machine, quiet: true, seen: now - 90_000 }] }); + expect(machinesMark(quiet, now + 20_000)).toBe(machinesMark(quiet, now)); + expect(machinesMark(quiet, now + 60_000)).not.toBe(machinesMark(quiet, now)); + // An answer that is not one is not a crash. + expect(machinesMark(null, now)).toBe(machinesMark({}, now)); +}); diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts index 43d0c65187..f3034156fa 100644 --- a/pm-stack/console/test/console.test.ts +++ b/pm-stack/console/test/console.test.ts @@ -365,6 +365,12 @@ describe("configuration", () => { ), ).toThrow(/https/); expect(() => readConfig({ PM_CONSOLE_ISSUERS_FILE: "/x" }, () => "{}")).toThrow(ConfigError); + // What the machine is called where machines are listed: what the + // environment says, made fit to show; unsaid, the host's own name is + // used when the console starts. + expect(readConfig({ PM_CONSOLE_MACHINE: "nixos" }).machineName).toBe("nixos"); + expect(readConfig({ PM_CONSOLE_MACHINE: " Drew's laptop " }).machineName).toBe("Drew-s laptop"); + expect(readConfig({}).machineName).toBe(""); for (const bind of ["127.0.0.1", "::1", "localhost"]) { expect(readConfig({ PM_CONSOLE_BIND: bind }).bind).toBe(bind); } diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index d46da5d2d3..1240683563 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -20,7 +20,16 @@ import { clearJwksCache, identify } from "../src/auth.ts"; import { readConfig } from "../src/config.ts"; import { Devices, Limiter } from "../src/devices.ts"; import { Docs } from "../src/docs.ts"; -import { type EdgeConfig, edgeConfig as parseEdgeConfig, keyId, newKeyPair, sign } from "../src/edge-proto.ts"; +import { + type EdgeConfig, + edgeConfig as parseEdgeConfig, + keyId, + type MachinesAnswer, + machineName, + machineReport, + newKeyPair, + sign, +} from "../src/edge-proto.ts"; import { OpError } from "../src/errors.ts"; import { Ops } from "../src/ops.ts"; import { type Deps, handle, heldRunner, marked } from "../src/server.ts"; @@ -851,9 +860,15 @@ async function setup(options: { direct?: boolean } = {}) { }; const keys = memoryStore(); const done = memoryStore(); + /** What the machine says of itself in each report; null for a console + * older than the saying, which says nothing. */ + const machineSays: { now: { name: string; actions: string[] } | null } = { + now: { name: "nixos", actions: Object.keys(table).sort() }, + }; const makeLink = () => new EdgeLink({ version: "0123abcd4567", + ...(machineSays.now ? { machine: () => machineSays.now as { name: string; actions: string[] } } : {}), apk: async () => { if (!build.bytes) return null; const bytes = build.bytes; @@ -970,6 +985,7 @@ async function setup(options: { direct?: boolean } = {}) { io, link, makeLink, + machineSays, later, token, browse, @@ -1648,6 +1664,152 @@ describe("actions", () => { expect(await third.json()).toEqual({ ok: true, result: { task: 21016, priority: 10 } }); }); + test("machines: the edge says what it does itself, what each machine that reports can do, and what waits for one, with every machine away too", async () => { + const w = await setup(); + const machines = async () => (await (await w.browse("/console/api/machines")).json()) as MachinesAnswer; + await w.hostReads(); + await w.link.now.once(); + const first = await machines(); + expect([first.served, first.held]).toEqual(["edge", []]); + // It only serves and waits here. Its own it does itself (linked + // phones, notifications, what is held); everything else is the machine's. + expect(first.platform).toEqual({ + primary: false, + actions: [ + "device.approve", + "device.remove", + "edge.retry", + "held.drop", + "push.class", + "push.off", + "push.on", + "push.test", + ], + sections: [], + refused: [], + }); + expect(first.machines).toEqual([ + { + name: "nixos", + seen: w.now.t, + quiet: false, + version: "0123abcd4567", + // What it said it can do: the kinds of action it has, and every section it reads. + actions: [ + "ask.send", + "issue.comment", + "message.send", + "need.comment", + "pr.merge", + "prompt.enqueue", + "question.answer", + "task.move", + "triage.enqueue", + ], + sections: [...SECTION_NAMES].sort(), + }, + ]); + // The machine goes away. What the owner does that may wait, waits; the list says what. + w.net.hostUp = false; + w.net.edgeUp = false; + const kept = "0e000000-0000-4000-8000-000000000001"; + expect(await (await w.act("task.move", { task: 21016, to: "first" }, kept)).json()).toMatchObject({ held: true }); + expect(await (await w.act("message.send", { to: ["lane-1"], text: "when you are back" })).json()).toMatchObject({ + held: true, + }); + w.now.t += 5 * 60_000; + const away = await machines(); + expect(away.machines.map((m) => [m.name, m.quiet, m.seen])).toEqual([["nixos", true, w.now.t - 5 * 60_000]]); + expect(away.held.map((h) => [h.kind, h.args, h.who])).toEqual([ + ["task.move", { task: 21016, to: "first" }, OWNER], + ["message.send", { to: ["lane-1"], text: "when you are back" }, OWNER], + ]); + expect(away.held[0].id).toBe(kept); + // The object is put away and another starts in its place: it still knows the machine. + w.edge.now = w.makeEdge(); + expect((await machines()).machines.map((m) => [m.name, m.actions.length, m.sections.length])).toEqual([ + ["nixos", 9, SECTION_NAMES.length], + ]); + // The owner takes one back before the machine has it. + const dropped = await w.act("held.drop", { id: kept }); + expect(await dropped.json()).toEqual({ ok: true, result: { dropped: kept, kind: "task.move" } }); + expect((await machines()).held.map((h) => h.kind)).toEqual(["message.send"]); + // It is on the record as not sent, under its name, so the device that sent it learns so. + const { doc } = await w.core(); + expect(doc.acts.find((a: { id: string }) => a.id === kept)).toMatchObject({ + kind: "task.move", + status: "failed", + note: "Not sent: taken back before a machine took it.", + }); + expect(doc.edge.held).toBe(1); + // The device that sent it never heard it was kept, and offers it + // again under its name: it is told it was taken back. It is not + // kept a second time, and no machine is handed it. + const offered = await w.act("task.move", { task: 21016, to: "first" }, kept); + expect([offered.status, await offered.json()]).toEqual([ + 410, + { error: "This was taken back before a machine took it.", again: true }, + ]); + expect((await machines()).held.map((h) => h.kind)).toEqual(["message.send"]); + // Taken back twice, or something that was never waiting: said as that. + const again = await w.act("held.drop", { id: kept }); + expect([again.status, await again.json()]).toEqual([ + 404, + { error: "That is no longer waiting: a machine took it, or it was taken back already." }, + ]); + // The machine is back: it is given what still waits, and not what was taken back. + w.net.hostUp = true; + w.net.edgeUp = true; + w.now.t += 1_000; + await w.link.now.once(); + expect(w.ran.map((r) => r.kind)).toEqual(["message.send"]); + w.now.t += 1_000; + await w.link.now.once(); + const back = await machines(); + expect([back.machines[0].quiet, back.held]).toEqual([false, []]); + // Offered once more with the machine back: still taken back, and still not done. + const late = await w.act("task.move", { task: 21016, to: "first" }, kept); + expect(late.status).toBe(410); + expect(w.ran.map((r) => r.kind)).toEqual(["message.send"]); + }); + + test("machines: a console older than the saying is a machine that has not said what it can do; one that says nonsense, the same", async () => { + const w = await setup(); + w.machineSays.now = null; + w.link.now = w.makeLink(); + await w.hostReads(); + await w.link.now.once(); + const machines = async () => (await (await w.browse("/console/api/machines")).json()) as MachinesAnswer; + expect((await machines()).machines).toEqual([ + { name: "A machine", seen: w.now.t, quiet: false, version: "0123abcd4567", actions: [], sections: [] }, + ]); + // A name that is not one, or a list that is not a list of kinds. + for (const says of [ + { name: "nixos", actions: ["task.move"] }, + { name: "nixos", actions: ["task.move", "not a kind"] }, + { name: "", actions: [] }, + ]) { + w.machineSays.now = says; + w.link.now = w.makeLink(); + w.now.t += 1_000; + await w.link.now.once(); + expect([says, (await machines()).machines[0].name]).toEqual([says, "A machine"]); + } + // Said properly again, it is known again. + w.machineSays.now = { name: "amd", actions: ["task.move", "task.move", "ask.send"] }; + w.link.now = w.makeLink(); + w.now.t += 1_000; + await w.link.now.once(); + expect((await machines()).machines[0]).toMatchObject({ name: "amd", actions: ["ask.send", "task.move"] }); + }); + + test("machines: a machine says every section it has a reader for from its first report, before it has read any", async () => { + const w = await setup(); + await w.link.now.once(); + const said = (await (await w.browse("/console/api/machines")).json()) as MachinesAnswer; + expect(said.machines.map((m) => [m.name, m.sections])).toEqual([["nixos", [...SECTION_NAMES].sort()]]); + }); + test("held twice under one name, an action waits once", async () => { const w = await setup(); await w.hostReads(); @@ -3233,6 +3395,45 @@ describe("the edge does the core itself", () => { expect(w.ghMerged).toHaveLength(1); }); + test("machines: doing the core itself, the edge says which kinds it does and which sections it reads, less what it was turned away for", async () => { + const w = await primary(); + const machines = async () => (await (await w.browse("/console/api/machines")).json()) as MachinesAnswer; + const first = await machines(); + expect(first.platform).toEqual({ + primary: true, + actions: [ + "device.approve", + "device.remove", + "edge.retry", + "held.drop", + "push.class", + "push.off", + "push.on", + "push.test", + "ask.send", + "ask.reply", + "ask.close", + "issue.comment", + "need.comment", + "issue.rank", + "task.move", + "pr.merge", + "deploy.start", + "intake.send", + ], + sections: ["board", "prs", "priorities", "asks"], + refused: [], + }); + expect(first.machines.map((m) => m.name)).toEqual(["nixos"]); + // Turned away for merging: that is a machine's for the hour, and said so. + w.ghRefuses.push((method, url) => method === "PUT" && url.includes("/merge")); + await w.act("pr.merge", { pr: 55 }); + const turned = (await machines()).platform; + expect(turned?.actions).not.toContain("pr.merge"); + expect(turned?.actions).toContain("issue.rank"); + expect(turned?.refused).toEqual(["pr.merge"]); + }); + 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"; @@ -4532,3 +4733,39 @@ describe("telling the owner, with no machine", () => { expect(w.githubCalls.length).toBe(calls); }); }); + +test("what a machine may say of itself: a name fit to show, and lists of kinds", () => { + expect( + machineReport({ name: "nixos", actions: ["task.move", "ask.send", "task.move"], sections: ["board"] }), + ).toEqual({ + name: "nixos", + actions: ["ask.send", "task.move"], + sections: ["board"], + }); + expect(machineReport({ name: "Drew's laptop", actions: [], sections: [] })).toBeNull(); + expect(machineReport({ name: "amd.local", actions: [], sections: ["questionCount"] })).toEqual({ + name: "amd.local", + actions: [], + sections: ["questionCount"], + }); + for (const bad of [ + null, + "nixos", + { name: "nixos" }, + { name: "nixos", actions: "task.move", sections: [] }, + { name: "nixos", actions: ["Task Move"], sections: [] }, + { name: "nixos", actions: [7], sections: [] }, + { name: "x".repeat(64), actions: [], sections: [] }, + { name: " nixos", actions: [], sections: [] }, + { name: "nixos", actions: Array.from({ length: 201 }, (_, i) => `a.k${i}`), sections: [] }, + ]) { + expect([bad, machineReport(bad)]).toEqual([bad, null]); + } + // A name from whatever the machine is called locally. + expect(machineName("nixos")).toBe("nixos"); + expect(machineName(" Drew's laptop ")).toBe("Drew-s laptop"); + expect(machineName("amd.lan")).toBe("amd.lan"); + expect(machineName("--weird__")).toBe("weird__"); + expect(machineName("x".repeat(100))).toBe("x".repeat(63)); + for (const none of ["", " ", "!!!", undefined, null]) expect([none, machineName(none)]).toEqual([none, ""]); +}); diff --git a/pm-stack/console/test/outbox.test.ts b/pm-stack/console/test/outbox.test.ts index d28dbfea0e..22147bd91e 100644 --- a/pm-stack/console/test/outbox.test.ts +++ b/pm-stack/console/test/outbox.test.ts @@ -141,6 +141,13 @@ test("each action is said in a line the owner will know it by", () => { expect(O.sayOf("ask.close")).toBe("Mark prompt #undefined done"); }); +test("the platform's own second half of something it filed is said in words too, where what waits for a machine is listed", () => { + expect(O.sayOf("prompt.enqueue", { issue: 201, text: "x" })).toBe("File the queue task for prompt #201"); + expect(O.sayOf("triage.enqueue", { issue: 301 })).toBe("File the triage task for #301"); + // Neither is ever kept on the device: only the platform makes them. + expect([O.rule("prompt.enqueue"), O.rule("triage.enqueue"), O.rule("held.drop")]).toEqual(["now", "now", "now"]); +}); + 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); diff --git a/pm-stack/console/test/work.test.ts b/pm-stack/console/test/work.test.ts index 61f12a12f0..a2dea85554 100644 --- a/pm-stack/console/test/work.test.ts +++ b/pm-stack/console/test/work.test.ts @@ -1185,6 +1185,31 @@ describe("the interface's endpoints", () => { expect(Object.keys(JSON.parse(kept[kept.length - 1]))).toEqual(["x", "y"]); }); + test("asked which machines there are, a machine serving the app by itself answers with itself: nothing is in front of it, and nothing waits", async () => { + const { d } = deps(); + d.self = { name: "nixos", version: "0123abcd4567" }; + await handle(get("/console/api/doc/core"), d); + const answer = (await (await handle(get("/console/api/machines"), d)).json()) as { + served: string; + platform: unknown; + machines: { name: string; quiet: boolean; version: string | null; actions: string[]; sections: string[] }[]; + held: unknown[]; + }; + expect([answer.served, answer.platform, answer.held]).toEqual(["machine", null, []]); + expect(answer.machines).toHaveLength(1); + const [self] = answer.machines; + expect([self.name, self.quiet, self.version]).toEqual(["nixos", false, "0123abcd4567"]); + // What it can do is what it has: its actions by kind, and every section it reads. + expect(self.actions).toEqual(Object.keys(d.actions ?? {}).sort()); + expect(self.actions).toContain("task.cancel"); + expect(self.sections).toContain("questions"); + expect(self.sections).toEqual([...self.sections].sort()); + // With no name given it, it is still a machine. + d.self = undefined; + const unnamed = (await (await handle(get("/console/api/machines"), d)).json()) as typeof answer; + expect([unnamed.machines[0].name, unnamed.machines[0].version]).toEqual(["this machine", null]); + }); + 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,