diff --git a/nixos/services/pm-stack/default.nix b/nixos/services/pm-stack/default.nix index 721b26bf7b..bdc6472741 100644 --- a/nixos/services/pm-stack/default.nix +++ b/nixos/services/pm-stack/default.nix @@ -248,6 +248,10 @@ in }; Service = { Type = "simple"; + # The management plane has to answer while the fleet is + # compiling (load average 75 on 16 cores, 2026-11-22): under + # contention this unit gets nine times a default unit's share. + CPUWeight = 900; # Every state file is env-pinned below or in the .env # file; the state dir as cwd makes any unpinned cwd # default in the config land in state too, never in a @@ -329,6 +333,10 @@ in }; Service = { Type = "simple"; + # The management plane has to answer while the fleet is + # compiling (load average 75 on 16 cores, 2026-11-22): under + # contention this unit gets nine times a default unit's share. + CPUWeight = 900; # The app has no cwd-relative access of its own (its # paths come from the env files below); the deployment # dir stays as cwd because that is where its rendered @@ -513,6 +521,10 @@ in }; Service = { Type = "simple"; + # The management plane has to answer while the fleet is + # compiling (load average 75 on 16 cores, 2026-11-22): under + # contention this unit gets nine times a default unit's share. + CPUWeight = 900; WorkingDirectory = "${stackDir}"; # tunnel.token is rendered by the pm-kaneo deploy flow # (deploy.sh) from the same SOPS secret as the old diff --git a/pm-stack/console/install.sh b/pm-stack/console/install.sh index dd5991d361..8aed7a24c2 100755 --- a/pm-stack/console/install.sh +++ b/pm-stack/console/install.sh @@ -31,9 +31,15 @@ if [ ! -f "$STATE/.env" ]; then printf 'PM_CONSOLE_PORT=4872\nPM_CONSOLE_OWNER_EMAILS=\n' >"$STATE/.env" fi install -m 644 "$UNIT_SRC" "$UNIT_DST" +# The timer keeps the public address as declared, and turns Google +# sign-in on by itself once its two secrets exist. +for unit in pm-console-expose.service pm-console-expose.timer; do + install -m 644 "$(dirname "$SRC")/systemd/$unit" "$(dirname "$UNIT_DST")/$unit" +done systemctl --user daemon-reload systemctl --user enable pm-console.service >/dev/null systemctl --user restart pm-console.service +systemctl --user enable --now pm-console-expose.timer >/dev/null # systemd strips one pair of quotes from an EnvironmentFile value, so # PM_CONSOLE_PORT="4872" is a valid line: read it the same way. diff --git a/pm-stack/console/public/app.css b/pm-stack/console/public/app.css index 0486aba26a..22e9749a7d 100644 --- a/pm-stack/console/public/app.css +++ b/pm-stack/console/public/app.css @@ -1,153 +1,311 @@ :root { - color-scheme: light dark; - --bg: #f6f7f9; - --panel: #ffffff; - --ink: #171a1f; - --muted: #5b6472; - --line: #d9dde3; - --accent: #1f6feb; - --accent-ink: #ffffff; - --good: #1a7f37; - --warn: #9a6700; - --bad: #cf222e; - --radius: 10px; - font: - 16px / 1.45 system-ui, - -apple-system, - "Segoe UI", - Roboto, - sans-serif; -} -@media (prefers-color-scheme: dark) { + color-scheme: dark light; + --bg: #0b0f14; + --panel: #151b23; + --panel-2: #1c2430; + --line: #2a3441; + --text: #e6edf3; + --quiet: #8b98a8; + --accent: #4c9aff; + --accent-ink: #06121f; + --good: #3fb950; + --warn: #d29922; + --bad: #f85149; + --tab-h: 62px; + --top-h: 52px; + font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + font-size: 16px; + line-height: 1.4; +} +@media (prefers-color-scheme: light) { :root { - --bg: #12151a; - --panel: #1b2027; - --ink: #e8ebf0; - --muted: #9aa4b2; - --line: #2d343e; - --accent: #4c8dff; - --accent-ink: #0b0d10; - --good: #3fb950; - --warn: #d29922; - --bad: #f85149; + --bg: #f4f6f9; + --panel: #ffffff; + --panel-2: #eef1f5; + --line: #d5dbe3; + --text: #17202b; + --quiet: #5b6777; + --accent: #0b63ce; + --accent-ink: #ffffff; } } * { box-sizing: border-box; } +html, body { margin: 0; background: var(--bg); - color: var(--ink); - padding-bottom: env(safe-area-inset-bottom); + color: var(--text); +} +body { + padding: calc(var(--top-h) + env(safe-area-inset-top)) 0 calc(var(--tab-h) + env(safe-area-inset-bottom) + 12px); + -webkit-tap-highlight-color: transparent; } a { color: var(--accent); + text-decoration: none; } -h2 { - font-size: 1.05rem; - margin: 0 0 0.5rem; -} -h3 { - font-size: 0.95rem; - margin: 0; - overflow-wrap: anywhere; -} -p { - margin: 0.25rem 0; +[hidden] { + display: none !important; } -.bar { + +/* ---- frame ---------------------------------------------------------- */ +.top { + position: fixed; + inset: 0 0 auto 0; + height: calc(var(--top-h) + env(safe-area-inset-top)); + padding: env(safe-area-inset-top) 12px 0 16px; display: flex; - gap: 0.9rem; align-items: center; - padding: 0.7rem 1rem; - padding-top: calc(0.7rem + env(safe-area-inset-top)); - background: var(--panel); + gap: 8px; + background: var(--bg); border-bottom: 1px solid var(--line); + z-index: 5; } -.brand { - font-weight: 700; - color: var(--ink); - text-decoration: none; +.top h1 { + margin: 0; + font-size: 1.25rem; + font-weight: 650; } .grow { flex: 1; } -.quiet { - color: var(--muted); - font-size: 0.875rem; +.fresh { + font-size: 0.78rem; + color: var(--quiet); +} +.fresh.stale { + color: var(--warn); +} +.fresh.down { + color: var(--bad); +} +main { + max-width: 760px; + margin: 0 auto; + padding: 12px; + outline: none; } .tabs { + position: fixed; + inset: auto 0 0 0; + height: calc(var(--tab-h) + env(safe-area-inset-bottom)); + padding-bottom: env(safe-area-inset-bottom); display: flex; - gap: 0.25rem; - overflow-x: auto; - padding: 0.5rem 0.75rem; background: var(--panel); - border-bottom: 1px solid var(--line); - position: sticky; - top: 0; - z-index: 2; + border-top: 1px solid var(--line); + z-index: 5; } .tabs button { + flex: 1; background: none; - color: var(--muted); border: 0; - border-radius: 999px; - padding: 0.45rem 0.9rem; + border-radius: 0; + color: var(--quiet); font: inherit; - white-space: nowrap; - min-height: 2.5rem; + font-size: 0.72rem; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 3px; + min-height: 0; + padding: 0; + position: relative; } .tabs button[aria-current="page"] { - background: var(--accent); - color: var(--accent-ink); + color: var(--accent); +} +.tabs svg { + width: 24px; + height: 24px; + fill: none; + stroke: currentColor; + stroke-width: 1.9; + stroke-linecap: round; + stroke-linejoin: round; +} +.badge { + position: absolute; + top: 6px; + left: calc(50% + 6px); + min-width: 18px; + padding: 0 5px; + border-radius: 9px; + background: var(--bad); + color: #fff; + font-size: 0.68rem; + font-weight: 700; + line-height: 18px; +} +@media (min-width: 900px) { + body { + padding-left: 96px; + padding-bottom: 24px; + } + .top { + left: 96px; + } + .tabs { + inset: 0 auto 0 0; + width: 96px; + height: auto; + flex-direction: column; + justify-content: flex-start; + padding-top: 12px; + border-top: 0; + border-right: 1px solid var(--line); + } + .tabs button { + flex: 0 0 72px; + } +} + +/* ---- pieces --------------------------------------------------------- */ +h2 { + margin: 20px 4px 8px; + font-size: 0.8rem; + font-weight: 650; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--quiet); +} +h2:first-child { + margin-top: 4px; +} +h3 { + margin: 0 0 4px; + font-size: 1rem; font-weight: 600; + overflow-wrap: anywhere; } -main { - max-width: 62rem; - margin: 0 auto; - padding: 1rem; - display: grid; - gap: 0.75rem; - outline: none; +p { + margin: 4px 0; + overflow-wrap: anywhere; } .card { background: var(--panel); border: 1px solid var(--line); - border-radius: var(--radius); - padding: 0.85rem 1rem; - display: grid; - gap: 0.4rem; + border-radius: 12px; + padding: 12px 14px; + margin-bottom: 10px; } -.grid { - display: grid; - gap: 0.75rem; - grid-template-columns: repeat(auto-fit, minmax(9.5rem, 1fr)); +.card.flag { + border-left: 4px solid var(--warn); } -.stat b { +.card.hot { + border-left: 4px solid var(--accent); +} +.meta { + color: var(--quiet); + font-size: 0.82rem; +} +.step { + margin-top: 8px; + padding: 8px 10px; + background: var(--panel-2); + border-radius: 8px; + font-size: 0.9rem; +} +.step b { display: block; - font-size: 1.7rem; - line-height: 1.1; - font-variant-numeric: tabular-nums; + font-size: 0.72rem; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--quiet); + margin-bottom: 2px; +} +.why { + color: var(--warn); +} +.bad { + color: var(--bad); +} +.empty { + padding: 28px 16px; + text-align: center; + color: var(--quiet); } .row { display: flex; - gap: 0.5rem; - align-items: center; flex-wrap: wrap; + gap: 8px; + align-items: center; } .row.end { justify-content: flex-end; + margin-top: 10px; } -.meta { - color: var(--muted); - font-size: 0.85rem; - overflow-wrap: anywhere; +.chip { + display: inline-block; + padding: 1px 8px; + border-radius: 999px; + background: var(--panel-2); + border: 1px solid var(--line); + font-size: 0.74rem; + color: var(--quiet); + white-space: nowrap; } -.why { - font-size: 0.9rem; - overflow-wrap: anywhere; +.chip.good { + color: var(--good); + border-color: var(--good); +} +.chip.warn { + color: var(--warn); + border-color: var(--warn); +} +.chip.accent { + color: var(--accent); + border-color: var(--accent); +} +.stats { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 8px; + margin-bottom: 4px; +} +.stat { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 12px; + padding: 10px 6px; + text-align: center; + color: var(--text); + min-height: 0; + display: block; +} +.stat b { + display: block; + font-size: 1.35rem; +} +.stat span { + font-size: 0.72rem; + color: var(--quiet); +} +.num { + flex: 0 0 26px; + height: 26px; + border-radius: 13px; + background: var(--panel-2); + color: var(--quiet); + font-size: 0.8rem; + font-weight: 700; + display: flex; + align-items: center; + justify-content: center; +} +.lead { + display: flex; + gap: 10px; + align-items: flex-start; } +.lead > div { + flex: 1; + min-width: 0; +} + +/* ---- controls ------------------------------------------------------- */ button, select, input, @@ -156,114 +314,267 @@ textarea { color: inherit; } button { + min-height: 42px; + padding: 8px 14px; + border-radius: 10px; + border: 1px solid var(--accent); background: var(--accent); color: var(--accent-ink); - border: 1px solid transparent; - border-radius: 8px; - padding: 0.45rem 0.85rem; - min-height: 2.5rem; + font-weight: 600; cursor: pointer; } button.ghost { background: transparent; - color: var(--ink); + color: var(--text); border-color: var(--line); + font-weight: 500; } button.danger { background: var(--bad); + border-color: var(--bad); color: #fff; } +button.small { + min-height: 34px; + padding: 4px 10px; + font-size: 0.85rem; +} +button.icon { + min-height: 40px; + width: 40px; + padding: 0; + background: transparent; + border-color: transparent; + color: var(--text); + font-size: 1.3rem; +} button:disabled { - opacity: 0.55; - cursor: progress; + opacity: 0.5; + cursor: default; } -input, select, +input, textarea { - background: var(--bg); - border: 1px solid var(--line); - border-radius: 8px; - padding: 0.5rem 0.6rem; width: 100%; - min-height: 2.5rem; + min-height: 42px; + padding: 8px 10px; + border-radius: 10px; + border: 1px solid var(--line); + background: var(--panel-2); } select.narrow { width: auto; } -label { - font-size: 0.85rem; - color: var(--muted); - display: grid; - gap: 0.25rem; +textarea { + resize: vertical; } -.badge { - font-size: 0.75rem; - border: 1px solid var(--line); +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} +.seg { + display: flex; + gap: 6px; + overflow-x: auto; + padding-bottom: 6px; + margin-bottom: 6px; +} +.seg button { + flex: 0 0 auto; + min-height: 36px; + padding: 4px 12px; border-radius: 999px; - padding: 0.1rem 0.55rem; - white-space: nowrap; + background: var(--panel); + border-color: var(--line); + color: var(--text); + font-weight: 500; + font-size: 0.9rem; } -.badge.good { - color: var(--good); - border-color: var(--good); +.seg button[aria-pressed="true"] { + background: var(--accent); + border-color: var(--accent); + color: var(--accent-ink); } -.badge.warn { - color: var(--warn); - border-color: var(--warn); + +/* ---- questions ------------------------------------------------------ */ +.options { + display: grid; + gap: 8px; + margin-top: 10px; } -.badge.bad { - color: var(--bad); - border-color: var(--bad); +.option { + text-align: left; + background: var(--panel-2); + border-color: var(--line); + color: var(--text); + font-weight: 500; } -pre { +.option.rec { + border-color: var(--accent); +} +.option[aria-pressed="true"] { + border-color: var(--accent); + background: color-mix(in srgb, var(--accent) 18%, var(--panel-2)); +} +.option small { + display: block; + color: var(--accent); + font-size: 0.72rem; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; +} +details { + margin-top: 6px; +} +summary { + cursor: pointer; + color: var(--accent); + font-size: 0.86rem; + padding: 6px 0; +} +.set { + display: flex; + align-items: center; + gap: 8px; + margin: 18px 4px 8px; +} +.set h2 { margin: 0; - padding: 0.75rem; - background: var(--bg); + flex: 1; +} + +/* ---- ask ------------------------------------------------------------ */ +.composer { + position: sticky; + top: calc(var(--top-h) + env(safe-area-inset-top) + 8px); + z-index: 2; +} +.bubble { + margin-top: 8px; + padding: 8px 10px; + border-radius: 10px; + background: var(--panel-2); + font-size: 0.92rem; + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.bubble.you { + background: transparent; border: 1px solid var(--line); +} +.bubble b { + display: block; + font-size: 0.72rem; + color: var(--quiet); + letter-spacing: 0.04em; + text-transform: uppercase; +} +.listening { + border-color: var(--bad) !important; + color: var(--bad) !important; +} + +/* ---- more ----------------------------------------------------------- */ +.tiles { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); + gap: 10px; +} +.tile { + display: block; + text-align: left; + background: var(--panel); + border: 1px solid var(--line); + border-radius: 12px; + padding: 12px; + color: var(--text); + font-weight: 600; + min-height: 74px; +} +.tile span { + display: block; + margin-top: 4px; + font-weight: 400; + font-size: 0.8rem; + color: var(--quiet); +} +.link { + display: block; + padding: 12px 14px; + background: var(--panel); + border: 1px solid var(--line); + border-radius: 12px; + margin-bottom: 8px; + color: var(--text); +} +.link span { + display: block; + font-size: 0.8rem; + color: var(--quiet); +} +pre { + margin: 8px 0 0; + padding: 10px; + background: var(--panel-2); border-radius: 8px; - overflow: auto; - max-height: 55vh; - font-size: 0.78rem; + font-size: 0.74rem; + overflow-x: auto; white-space: pre-wrap; overflow-wrap: anywhere; } + +/* ---- overlays ------------------------------------------------------- */ .toast { position: fixed; - left: 50%; - bottom: calc(1rem + env(safe-area-inset-bottom)); - transform: translateX(-50%); - background: var(--ink); - color: var(--bg); - padding: 0.6rem 1rem; - border-radius: 999px; - max-width: 92vw; - z-index: 5; - font-size: 0.9rem; + left: 12px; + right: 12px; + bottom: calc(var(--tab-h) + env(safe-area-inset-bottom) + 12px); + max-width: 560px; + margin: 0 auto; + padding: 12px 14px; + border-radius: 12px; + background: var(--good); + color: #04130a; + font-weight: 600; + z-index: 20; } .toast.bad { background: var(--bad); color: #fff; } dialog { + width: min(92vw, 520px); border: 1px solid var(--line); - border-radius: var(--radius); + border-radius: 14px; background: var(--panel); - color: var(--ink); - width: min(32rem, 92vw); - padding: 1rem; + color: var(--text); + padding: 16px; } dialog::backdrop { - background: rgb(0 0 0 / 0.5); + background: rgb(0 0 0 / 0.6); } -dialog form { - display: grid; - gap: 0.6rem; -} -.empty { - color: var(--muted); - text-align: center; - padding: 1.5rem 0; +dialog h2 { + margin: 0 0 6px; + font-size: 1.05rem; + text-transform: none; + letter-spacing: 0; + color: var(--text); } -[hidden] { - display: none !important; +dialog label { + display: block; + margin: 10px 0 4px; + font-size: 0.85rem; + color: var(--quiet); +} + +.check { + padding: 8px 0; + flex-wrap: nowrap; +} +.check input { + flex: 0 0 22px; + width: 22px; + min-height: 22px; + height: 22px; } diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 953a9d0d4e..2a0af5783d 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -1,239 +1,1204 @@ -// Console front end. No framework and no markup strings: every node is -// built with h(), and text from the fleet only ever becomes text. +// The PM app: what is in progress, what is next, what needs you, and a +// place to say what you want in your own words. Everything else is +// under More. +// +// The page draws from three documents the server keeps ready (core, +// questions, ops), so moving between sections never waits on a fetch. const API = "/console/api/"; -const view = document.getElementById("view"); -const tabs = document.getElementById("tabs"); -const toastEl = document.getElementById("toast"); +const $ = (id) => document.getElementById(id); +const view = $("view"); +const tabsEl = $("tabs"); +const toastEl = $("toast"); +const freshEl = $("fresh"); -function h(tag, attrs, ...children) { +// ---- small helpers ----------------------------------------------------- + +function h(tag, attrs, ...kids) { const el = document.createElement(tag); for (const [k, v] of Object.entries(attrs || {})) { if (v === false || v === null || v === undefined) continue; - if (k === "class") el.className = v; - else if (k.startsWith("on")) el.addEventListener(k.slice(2), v); - else if (k === "value") el.value = v; - else el.setAttribute(k, v === true ? "" : v); + if (k.startsWith("on")) el.addEventListener(k.slice(2), v); + else if (k === "class") el.className = v; + else if (v === true) el.setAttribute(k, ""); + else el.setAttribute(k, v); + } + for (const kid of kids.flat(Infinity)) { + if (kid === null || kid === undefined || kid === false) continue; + el.append(kid.nodeType ? kid : document.createTextNode(String(kid))); } - for (const c of children.flat()) if (c !== null && c !== undefined && c !== false) el.append(c); return el; } -async function api(path, body) { - const init = body === undefined ? {} : { method: "POST", headers: { "Content-Type": "application/json", "X-PM-Console": "1" }, body: JSON.stringify(body) }; - const res = await fetch(API + path, init); - let data = null; - try { - data = await res.json(); - } catch { - // A sign-in page instead of JSON means the edge session ended. - if (res.redirected || res.status === 401 || res.status === 403) location.reload(); - } - if (!res.ok) throw new Error((data && data.error) || `http ${res.status}`); - return data; +function icon(d) { + const NS = "http://www.w3.org/2000/svg"; + const s = document.createElementNS(NS, "svg"); + s.setAttribute("viewBox", "0 0 24 24"); + s.setAttribute("aria-hidden", "true"); + const p = document.createElementNS(NS, "path"); + p.setAttribute("d", d); + s.append(p); + return s; +} + +/** "12 min", "3 h", "2 d" since an ISO time (times without a zone are UTC). */ +export function ago(iso, now = Date.now()) { + if (!iso) return ""; + const t = Date.parse(/[zZ]$|[+-]\d\d:?\d\d$/.test(iso) ? iso : `${iso}Z`); + if (Number.isNaN(t)) return ""; + const s = Math.max(0, (now - t) / 1000); + if (s < 90) return "just now"; + if (s < 5400) return `${Math.round(s / 60)} min`; + if (s < 129600) return `${Math.round(s / 3600)} h`; + return `${Math.round(s / 86400)} d`; +} + +/** The queue's priority bands, in words. */ +export function band(priority) { + const p = Number(priority); + if (!priority && priority !== 0) return "Normal"; + if (p <= 10) return "Top"; + if (p <= 20) return "High"; + if (p <= 30) return "Normal"; + if (p <= 50) return "Low"; + return "Later"; } +const card = (...kids) => h("div", { class: "card" }, ...kids); +const empty = (text) => h("div", { class: "empty" }, text); +const chip = (text, tone) => h("span", { class: `chip${tone ? ` ${tone}` : ""}` }, text); +const ext = (href, text) => h("a", { href, target: "_blank", rel: "noopener" }, text); + let toastTimer; -function toast(message, bad) { - toastEl.textContent = message; +function toast(message, bad, undo) { + toastEl.replaceChildren(message); + if (undo) toastEl.append(" ", h("button", { class: "small ghost", onclick: undo }, "Undo")); toastEl.className = bad ? "toast bad" : "toast"; toastEl.hidden = false; clearTimeout(toastTimer); - toastTimer = setTimeout(() => (toastEl.hidden = true), bad ? 7000 : 3500); + toastTimer = setTimeout(() => { + toastEl.hidden = true; + }, bad ? 8000 : undo ? 5000 : 3500); } /** Ask before acting. Resolves to the typed text ("" when none is asked * for), or null when the person backs out. */ -function ask({ title, text, label, okLabel, danger, required }) { - const dialog = document.getElementById("ask"); - const input = document.getElementById("ask-input"); - const ok = document.getElementById("ask-ok"); - document.getElementById("ask-title").textContent = title; - document.getElementById("ask-text").textContent = text || ""; - document.getElementById("ask-label").textContent = label || ""; +function ask({ title, text, label, okLabel, danger, required, value }) { + const dialog = $("ask"); + const input = $("ask-input"); + const ok = $("ask-ok"); + $("ask-title").textContent = title; + $("ask-text").textContent = text || ""; + $("ask-label").textContent = label || ""; input.hidden = !label; - input.value = ""; + input.value = value || ""; input.required = Boolean(required); ok.textContent = okLabel || "Confirm"; ok.className = danger ? "danger" : ""; return new Promise((resolve) => { - dialog.addEventListener("close", () => resolve(dialog.returnValue === "ok" ? input.value.trim() : null), { once: true }); + dialog.addEventListener("close", () => resolve(dialog.returnValue === "ok" ? input.value.trim() : null), { + once: true, + }); + // A dialog keeps its last return value: clear it, or Escape after an + // earlier confirmation would confirm again. dialog.returnValue = ""; dialog.showModal(); if (label) input.focus(); }); } -/** Run one action from a button: disable it, report, then redraw. - * `done` is the message, or a function from the result to the message. */ -async function act(button, path, body, done) { - button.disabled = true; +// ---- state ------------------------------------------------------------- + +const docs = { core: null, questions: null, ops: null }; +const etags = {}; +const asOf = {}; +let me = {}; +let signedOut = false; + +async function api(path, body) { + const init = + body === undefined + ? {} + : { + method: "POST", + headers: { "Content-Type": "application/json", "X-PM-Console": "1" }, + body: JSON.stringify(body), + }; + let res; + try { + res = await fetch(API + path, init); + } catch { + // A sign-in that has run out answers with a redirect to another site, + // which a fetch may not follow. + signedOut = navigator.onLine !== false; + throw new Error(signedOut ? "Your sign-in may have run out. Reload to sign in again." : "You are offline."); + } + let data = null; + try { + data = await res.json(); + } catch { + if (res.status === 401 || res.status === 403) signedOut = true; + } + if (!res.ok) throw new Error((data && data.error) || `http ${res.status}`); + return data; +} + +/** Fetch one document if it changed. Returns true when it did. */ +async function loadDoc(name) { + let res; try { - const { result } = await api(path, body); + res = await fetch(`${API}doc/${name}`, { headers: etags[name] ? { "If-None-Match": etags[name] } : {} }); + } catch { + signedOut = navigator.onLine !== false; + throw new Error(signedOut ? "Your sign-in may have run out. Reload to sign in again." : "You are offline."); + } + if (res.headers.get("x-as-of")) asOf[name] = Number(res.headers.get("x-as-of")); + if (res.status === 304) return false; + if (!res.ok) { + if (res.status === 401 || res.status === 403) signedOut = true; + throw new Error(`could not load (${res.status})`); + } + docs[name] = await res.json(); + etags[name] = res.headers.get("etag"); + return true; +} + +/** Run one action, say how it went, and draw what changed. */ +async function act(kind, args, done, button) { + if (button) button.disabled = true; + try { + const { result } = await api("act", { kind, args }); toast(typeof done === "function" ? done(result) : done); - await show(current); + await refresh(true); + return result; } catch (error) { toast(error.message, true); - button.disabled = false; + if (button) button.disabled = false; + return null; } } -const badge = (text, kind) => h("span", { class: `badge ${kind || ""}` }, text); -const empty = (text) => h("p", { class: "empty" }, text); -const card = (...children) => h("section", { class: "card" }, ...children); +// ---- now --------------------------------------------------------------- -// ---- views --------------------------------------------------------------- +function taskCard(t, extra) { + const who = [t.worker, t.lane, t.model].filter(Boolean).join(" · "); + const when = t.claimed ? `claimed ${ago(t.claimed)} ago` : `queued ${ago(t.created)} ago`; + return card( + h( + "div", + { class: "row" }, + t.kind ? chip(String(t.kind).replace(/_/g, " ")) : null, + t.issue && t.url ? ext(t.url, `#${t.issue}`) : null, + Number(t.attempts) > 1 ? chip(`attempt ${t.attempts}`, "warn") : null, + ), + h("h3", {}, t.title), + h("p", { class: "meta" }, [who, when].filter(Boolean).join(" · ")), + t.step || t.goal + ? h("div", { class: "step" }, h("b", {}, t.step ? "Next step" : "Goal"), t.step || t.goal) + : null, + extra, + ); +} -async function overview() { - const o = await api("overview"); - const stat = (label, value, tab) => h("button", { class: "card stat ghost", onclick: () => show(tab) }, h("b", {}, String(value)), h("span", { class: "meta" }, label)); - const q = o.queue.error ? {} : o.queue; +function notices(doc) { + const out = []; + for (const [name, s] of Object.entries(doc?.health || {})) { + if (!s.ok && s.error) { + out.push( + h("div", { class: "card flag" }, h("p", { class: "meta" }, `Could not read ${name} just now: ${s.error}. Showing the last good copy.`)), + ); + } + } + return out; +} + +function viewNow() { + const c = docs.core; + const b = c.board || { counts: {}, now: [], next: [], blockedWhy: [] }; + const s = c.sessions || { moving: [], waiting: [] }; + const needs = needCounts(); + const stat = (value, label, to) => + h("button", { class: "stat", onclick: () => go(to) }, h("b", {}, String(value ?? "–")), h("span", {}, label)); const out = [ - h("div", { class: "grid" }, - stat("queued", q.queued ?? "–", "queue"), stat("claimed", q.claimed ?? "–", "queue"), stat("blocked", q.blocked ?? "–", "queue"), stat("parked", q.parked ?? "–", "queue"), - stat("PRs ready", o.prs.error ? "–" : o.prs.ready, "prs"), stat("agents", o.agents.error ? "–" : o.agents.registered, "agents"), - stat("units failed", o.services.error ? "–" : o.services.failed.length, "services")), + h( + "div", + { class: "stats" }, + stat(b.counts.claimed ?? 0, "in progress", "now"), + stat(b.counts.queued ?? 0, "queued", "next"), + stat(needs.total, "need you", "needs"), + stat(b.counts.blocked ?? 0, "blocked", "more/queue"), + ), + ...notices(c), + h("h2", {}, "In progress"), + ...(b.now.length ? b.now.map((t) => taskCard(t)) : [empty("No task is claimed right now.")]), ]; - for (const [name, part] of Object.entries(o)) if (part.error) out.push(card(h("h3", {}, `${name}: unavailable`), h("p", { class: "why" }, part.error))); - if (!o.services.error && o.services.failed.length) out.push(card(h("h3", {}, "Failed units"), h("p", { class: "why" }, o.services.failed.join(", ")))); + if (s.moving.length) { + out.push( + h("h2", {}, "Agent sessions moving"), + ...s.moving.map((m) => + card( + h("h3", {}, m.title || "(untitled session)"), + h( + "p", + { class: "meta" }, + [m.agent, m.model, m.where, m.last ? `active ${ago(m.last)} ago` : "", m.tools ? `${m.tools} tool calls running` : ""] + .filter(Boolean) + .join(" · "), + ), + ), + ), + ); + } + if ((b.counts.blocked ?? 0) > 0 && b.blockedWhy?.length) { + out.push( + h("h2", {}, `Why ${b.counts.blocked} tasks are blocked`), + card( + ...b.blockedWhy.map((w) => h("p", {}, h("b", {}, `${w.n} `), h("span", { class: "meta" }, String(w.why)))), + h("div", { class: "row end" }, h("button", { class: "ghost small", onclick: () => go("more/queue") }, "Open blocked tasks")), + ), + ); + } + if (c.acts?.length) { + out.push( + h("h2", {}, "What you did"), + card( + ...c.acts.slice(0, 6).map((a) => + h( + "p", + { class: "meta" }, + `${ago(a.at)} ago · ${a.kind} · `, + h("span", { class: a.status === "failed" ? "bad" : "" }, a.status + (a.note ? `: ${a.note}` : "")), + ), + ), + ), + ); + } return out; } -let queueStatus = "blocked"; -let queueSearch = ""; -async function queue() { - const data = await api(`queue?status=${queueStatus}&limit=100&q=${encodeURIComponent(queueSearch)}`); - const pick = h("select", { class: "narrow", "aria-label": "Status", onchange: (e) => { queueStatus = e.target.value; show("queue"); } }, - ["queued", "claimed", "blocked", "parked"].map((s) => h("option", { value: s, selected: s === queueStatus }, `${s} (${data.counts[s] ?? 0})`))); - const search = h("input", { type: "search", placeholder: "Filter by title", value: queueSearch, "aria-label": "Filter by title", onchange: (e) => { queueSearch = e.target.value; show("queue"); } }); - const rows = data.tasks.map((t) => card( - h("h3", {}, `${t.id} · ${t.title}`), - h("p", { class: "meta" }, `priority ${t.priority ?? "–"} · updated ${t.updated ?? "–"} · ${t.dedupe_key ?? ""}`), - t.why ? h("p", { class: "why" }, t.why) : null, - h("div", { class: "row end" }, - t.status === "blocked" ? h("button", { onclick: async (e) => { - const reason = await ask({ title: `Unblock task ${t.id}`, text: t.title, label: "Why it can proceed", okLabel: "Unblock", required: true }); - if (reason) act(e.target, `queue/${t.id}/unblock`, { reason }, `Task ${t.id} unblocked`); - } }, "Unblock") : null, - h("button", { class: "ghost", onclick: async (e) => { - const reason = await ask({ title: `Cancel task ${t.id}`, text: t.title, label: "Why it is cancelled", okLabel: "Cancel task", danger: true, required: true }); - if (reason) act(e.target, `queue/${t.id}/cancel`, { reason }, `Task ${t.id} cancelled`); - } }, "Cancel")))); - return [card(h("div", { class: "row" }, pick, h("span", { class: "grow" }), search)), ...(rows.length ? rows : [empty("No tasks in this state.")])]; +// ---- next -------------------------------------------------------------- + +function viewNext() { + const b = docs.core.board || { counts: {}, next: [] }; + const out = [...notices(docs.core), h("h2", {}, "Queued next, in the order it will be picked up")]; + if (!b.next.length) out.push(empty("Nothing is queued. Blocked and parked tasks are under More, Queue.")); + b.next.forEach((t, i) => { + const moves = h( + "div", + { class: "row end" }, + chip(band(t.priority), Number(t.priority) <= 10 ? "accent" : ""), + h("span", { class: "grow" }), + Number(t.priority) > 10 + ? h("button", { class: "small", onclick: (e) => act("task.move", { task: t.id, to: "first" }, "Moved to the top band", e.target) }, "Do first") + : null, + h("button", { class: "small ghost", onclick: (e) => act("task.move", { task: t.id, to: "sooner" }, "Moved sooner", e.target) }, "Sooner"), + h("button", { class: "small ghost", onclick: (e) => act("task.move", { task: t.id, to: "later" }, "Moved later", e.target) }, "Later"), + h( + "button", + { + class: "small ghost", + onclick: async (e) => { + const why = await ask({ title: "Cancel this task?", text: t.title, label: "Why", okLabel: "Cancel task", danger: true, required: true }); + if (why) act("task.cancel", { task: t.id, reason: why }, "Cancelled", e.target); + }, + }, + "Cancel", + ), + ); + out.push(h("div", { class: "lead" }, h("span", { class: "num" }, String(i + 1)), h("div", {}, taskCard(t, moves)))); + }); + const ranked = docs.ops?.priorities?.issues; + out.push(h("h2", {}, "Ranked issues")); + if (!ranked) out.push(empty("Loading…")); + else { + out.push(...ranked.slice(0, 12).map(issueCard)); + if (ranked.length > 12) out.push(h("button", { class: "ghost", onclick: () => go("more/issues") }, `All ${ranked.length} ranked issues`)); + } + return out; } const RANKS = ["expedite", "priority/critical", "now", "priority/high", "next", "none"]; -async function priorities() { - const { issues: list, truncated } = await api("priorities"); - const title = h("input", { placeholder: "A new idea or piece of work", "aria-label": "Title" }); - const body = h("textarea", { rows: 3, placeholder: "What you want, in your words (optional)", "aria-label": "Details" }); - const rank = h("select", { class: "narrow", "aria-label": "Rank" }, RANKS.map((r) => h("option", { value: r, selected: r === "next" }, r))); - const file = card(h("h2", {}, "File work"), title, body, h("div", { class: "row end" }, rank, - h("button", { onclick: (e) => title.value.trim() ? act(e.target, "ideas", { title: title.value, body: body.value, rank: rank.value }, (r) => (r.queued ? `Filed #${r.issue} and queued it` : `Filed #${r.issue}. ${r.note || "It is not queued yet."}`)) : toast("Give it a title", true) }, "File issue"))); - const rows = list.map((i) => card( - h("h3", {}, h("a", { href: i.url, target: "_blank", rel: "noopener" }, `#${i.number}`), ` ${i.title}`), - h("p", { class: "meta" }, `updated ${i.updated} · ${i.comments} comments · ${i.labels.filter((l) => !RANKS.includes(l)).slice(0, 6).join(", ")}`), - h("div", { class: "row end" }, - h("select", { class: "narrow", "aria-label": `Rank for #${i.number}`, onchange: (e) => act(e.target, `priorities/${i.number}/rank`, { rank: e.target.value }, `#${i.number} is now ${e.target.value}`) }, - RANKS.map((r) => h("option", { value: r, selected: r === i.rank }, r))), - h("button", { class: "ghost", onclick: async (e) => { - const text = await ask({ title: `Comment on #${i.number}`, text: i.title, label: "Comment", okLabel: "Post", required: true }); - if (text) act(e.target, `issues/${i.number}/comment`, { body: text }, "Comment posted"); - } }, "Comment")))); - const more = truncated ? [empty("There are more ranked issues than this list reads. The most urgent may not all be here.")] : []; - return [file, ...more, ...(rows.length ? rows : [empty("No ranked issues.")])]; -} - -async function agents() { - const [list, log] = await Promise.all([api("agents"), api("messages?limit=20")]); - const groups = [...new Set(list.flatMap((a) => a.groups || []))].sort(); - const target = h("select", { "aria-label": "Send to" }, - h("option", { value: "all" }, "everyone"), - groups.map((g) => h("option", { value: `group:${g}` }, `group: ${g}`)), - list.map((a) => h("option", { value: `agent:${a.name}` }, a.name))); - const kind = h("select", { class: "narrow", "aria-label": "Kind" }, h("option", { value: "message" }, "idea / message"), h("option", { value: "command" }, "command")); - const body = h("textarea", { rows: 4, placeholder: "The idea, in your words", "aria-label": "Text" }); - const send = card(h("h2", {}, "Send to agents"), target, body, h("div", { class: "row end" }, kind, - h("button", { onclick: (e) => body.value.trim() ? act(e.target, "messages", { to: [target.value], text: body.value, command: kind.value === "command" }, "Sent") : toast("Write something to send", true) }, "Send"))); - const roster = card(h("h2", {}, `Agents (${list.length})`), ...list.map((a) => h("div", { class: "row" }, - h("strong", {}, a.name), h("span", { class: "meta" }, (a.groups || []).join(", ")), h("span", { class: "grow" }), - a.unread_commands ? badge(`${a.unread_commands} unread commands`, "warn") : null, a.unread_messages ? badge(`${a.unread_messages} unread`, "warn") : null, - h("span", { class: "meta" }, (a.last_seen || "").slice(0, 16))))); - const recent = card(h("h2", {}, "Recent messages"), ...(log.length ? log.map((m) => h("div", {}, - h("p", { class: "meta" }, `${(m.ts || "").slice(0, 16)} · ${m.direction} · ${m.agent} · ${m.kind}`), h("p", { class: "why" }, (m.body || "").slice(0, 400)))) : [empty("Nothing sent yet.")])); - return [send, roster, recent]; -} - -async function services() { - const list = await api("services"); - const state = (u) => badge(`${u.active} · ${u.sub}`, u.active === "failed" ? "bad" : u.active === "active" ? "good" : "warn"); - return list.map((u) => { - const logs = h("pre", { hidden: true }); - const run = (action, danger) => h("button", { class: danger ? "danger" : "ghost", onclick: async (e) => { - const yes = await ask({ title: `${action} ${u.unit}`, text: u.description, okLabel: action, danger }); - if (yes !== null) act(e.target, `services/${encodeURIComponent(u.unit)}/${action}`, {}, `${u.unit}: ${action} requested`); - } }, action); - return card(h("div", { class: "row" }, h("h3", {}, u.unit), h("span", { class: "grow" }), state(u)), h("p", { class: "meta" }, u.description), - h("div", { class: "row end" }, - h("button", { class: "ghost", onclick: async () => { - if (!logs.hidden) return (logs.hidden = true); - try { logs.textContent = (await api(`services/${encodeURIComponent(u.unit)}/logs?lines=120`)).log || "(no output)"; logs.hidden = false; } catch (error) { toast(error.message, true); } - } }, "Logs"), - run("restart"), u.active === "active" ? run("stop", true) : run("start")), logs); +function issueCard(i) { + return card( + h("h3", {}, ext(i.url, `#${i.number}`), ` ${i.title}`), + h("p", { class: "meta" }, `updated ${i.updated?.replace("T", " ")} · ${i.comments} comments`), + h( + "div", + { class: "row end" }, + h( + "select", + { + class: "narrow", + "aria-label": `Rank for #${i.number}`, + onchange: (e) => act("issue.rank", { issue: i.number, rank: e.target.value }, `#${i.number} is now ${e.target.value}`, e.target), + }, + RANKS.map((r) => h("option", { value: r, selected: r === i.rank }, r)), + ), + h( + "button", + { + class: "small ghost", + onclick: async (e) => { + const text = await ask({ title: `Comment on #${i.number}`, text: i.title, label: "Comment", okLabel: "Post", required: true }); + if (text) act("issue.comment", { issue: i.number, text }, "Comment posted", e.target); + }, + }, + "Comment", + ), + ), + ); +} + +// ---- needs me ---------------------------------------------------------- + +function needCounts() { + const c = docs.core || {}; + const census = c.census || { hands: [], reviews: [], other: [] }; + const waiting = c.sessions?.waiting || []; + const questions = docs.questions ? docs.questions.questions?.total : c.questionCount?.total; + const counts = { + questions: questions ?? 0, + hands: census.hands.length + waiting.length, + reviews: census.reviews.length, + other: census.other.length, + }; + // What needs the owner is what only he can do or answer; the + // escalated-with-no-action list is the fleet's to decide. + counts.total = counts.questions + counts.hands + counts.reviews; + return counts; +} + +let shown = 12; +const pending = new Map(); + +/** Answer after a short pause, so a slip of the thumb can be undone. */ +function later(key, label, send) { + const timer = setTimeout(() => { + pending.delete(key); + send(); + }, 4500); + pending.set(key, { timer, send }); + draw(); + toast(label, false, () => { + clearTimeout(timer); + pending.delete(key); + toastEl.hidden = true; + draw(); }); } -async function prs() { - const list = await api("prs"); - if (!list.length) return [empty("No open pull requests.")]; - return list.map((p) => { - const detail = h("div", { class: "meta" }); - const merge = h("button", { disabled: true, onclick: async (e) => { - const yes = await ask({ title: `Merge #${p.number}`, text: p.title, okLabel: "Merge" }); - if (yes !== null) act(e.target, `prs/${p.number}/merge`, {}, `#${p.number} merged`); - } }, "Merge"); - const check = h("button", { class: "ghost", onclick: async (e) => { - e.target.disabled = true; - try { - const d = await api(`prs/${p.number}`); - detail.textContent = `+${d.additions} −${d.deletions} in ${d.changed_files} files · ${d.review_comments} review comments · ${d.mergeable === true ? "mergeable" : d.mergeable === false ? "conflicts" : "mergeability pending"} (${d.mergeable_state})`; - merge.disabled = d.mergeable !== true || d.draft; - } catch (error) { toast(error.message, true); } +function flushPending() { + for (const [key, p] of pending) { + clearTimeout(p.timer); + pending.delete(key); + p.send(); + } +} + +async function sendAnswer(kind, args, key) { + try { + const { result } = await api("act", { kind, args }); + if (result?.refused?.length) toast(`Not recorded: ${result.refused[0].why}`, true); + if (docs.questions?.questions) { + const open = docs.questions.questions.open.filter((q) => `${q.set}|${q.ledger}|${q.qid}` !== key); + docs.questions.questions.total = open.length; + docs.questions.questions.open = open; + } + } catch (error) { + toast(error.message, true); + } + // The list above is already right; only the counts need reading again. + await loadDoc("core").catch(() => {}); + draw(); +} + +/** A line of background, and the rest of it when the question is opened. */ +function background(q) { + const body = h("div", {}, q.context ? h("p", {}, q.context) : null); + let asked = false; + return h( + "details", + { + ontoggle: async (e) => { + if (!e.target.open || asked || !q.more) return; + asked = true; + try { + const full = await api(`question?set=${encodeURIComponent(q.set)}&ledger=${encodeURIComponent(q.ledger)}&qid=${encodeURIComponent(q.qid)}`); + body.replaceChildren(full.context ? h("p", {}, full.context) : null, full.detail ? h("p", { class: "meta" }, full.detail) : null); + } catch { + asked = false; + } + }, + }, + h("summary", {}, "Background"), + body, + ); +} + +function questionCard(q) { + const key = `${q.set}|${q.ledger}|${q.qid}`; + if (pending.has(key)) return null; + const id = { set: q.set, ledger: q.ledger, qid: q.qid }; + const picked = new Set(); + const choose = (o) => later(key, `Answered: ${o.label.slice(0, 60)}`, () => sendAnswer("question.answer", { ...id, option: o.id }, key)); + const options = q.options.map((o) => { + const rec = q.recommended.includes(o.id); + return h( + "button", + { + class: `option${rec ? " rec" : ""}`, + "aria-pressed": q.multi ? "false" : null, + onclick: (e) => { + if (!q.multi) return choose(o); + const b = e.currentTarget; + const on = b.getAttribute("aria-pressed") !== "true"; + b.setAttribute("aria-pressed", String(on)); + b.classList.toggle("hot", on); + if (on) picked.add(o.id); + else picked.delete(o.id); + }, + }, + rec ? h("small", {}, "Recommended") : null, + o.label, + o.tags?.filter((t) => t !== "recommended").length ? h("span", { class: "meta" }, ` · ${o.tags.filter((t) => t !== "recommended").join(", ")}`) : null, + ); + }); + return card( + h("p", { class: "meta" }, q.item, ...q.links.slice(0, 2).map((l) => [" · ", ext(l, `#${l.split("/").pop()}`)])), + h("h3", {}, q.q), + q.context || q.more ? background(q) : null, + h("div", { class: "options" }, options), + h( + "div", + { class: "row end" }, + q.multi + ? h( + "button", + { + class: "small", + onclick: () => + picked.size + ? later(key, `Answered with ${picked.size} choices`, () => sendAnswer("question.answer", { ...id, options: [...picked] }, key)) + : toast("Choose at least one option", true), + }, + "Submit choices", + ) + : null, + h( + "button", + { + class: "small ghost", + onclick: async () => { + const text = await ask({ title: "Your own answer", text: q.q, label: "Answer", okLabel: "Send", required: true }); + if (text) sendAnswer("question.answer", { ...id, text }, key); + }, + }, + "Write an answer", + ), + h( + "button", + { class: "small ghost", onclick: () => later(key, "Handed back: decide for me", () => sendAnswer("question.defer", { ...id, lean: "approve" }, key)) }, + "Decide for me", + ), + ), + ); +} + +function viewQuestions() { + const doc = docs.questions; + if (!doc) return [empty("Loading the questions…")]; + const all = doc.questions?.open || []; + const out = [...notices(doc)]; + if (!all.length) return [...out, empty("No open questions.")]; + let lastSet = null; + for (const q of all.slice(0, shown)) { + if (q.set !== lastSet) { + lastSet = q.set; + const inSet = all.filter((x) => x.set === q.set); + const withRec = inSet.filter((x) => x.recommended.length).length; + out.push( + h( + "div", + { class: "set" }, + h("h2", {}, `${q.setTitle} · ${inSet.length} open`), + withRec + ? h( + "button", + { + class: "small", + onclick: async (e) => { + const yes = await ask({ + title: `Accept ${withRec} recommended answers?`, + text: `${q.setTitle}: every open question that has a recommendation gets the recommended option.`, + okLabel: "Accept all", + }); + if (yes !== null) { + await act("questions.accept", { set: q.set }, (r) => `${r.applied} answered`, e.target); + await loadDoc("questions").catch(() => {}); + draw(); + } + }, + }, + `Accept ${withRec} recommended`, + ) + : null, + ), + ); + } + out.push(questionCard(q)); + } + if (all.length > shown) { + out.push( + h( + "button", + { + class: "ghost", + onclick: () => { + shown += 20; + draw(); + }, + }, + `Show more (${all.length - shown} left)`, + ), + ); + } + return out; +} + +function needCard(i, kind) { + const reply = h( + "button", + { + class: "small ghost", + onclick: async (e) => { + const text = await ask({ title: `Reply on ${i.ref}`, text: i.title, label: "Reply", okLabel: "Post", required: true }); + if (text) act("need.comment", { ref: i.ref, text }, "Reply posted", e.target); + }, + }, + "Reply", + ); + return card( + h("div", { class: "row" }, kind ? chip(kind.replace("-", " "), "warn") : null, i.url ? ext(i.url, i.ref) : h("span", { class: "meta" }, i.ref || "")), + i.action ? h("h3", {}, i.action) : h("h3", {}, i.title), + i.action ? h("p", { class: "meta" }, i.title) : null, + i.why ? h("p", { class: "meta" }, i.why) : null, + i.updated ? h("p", { class: "meta" }, `updated ${ago(i.updated)} ago`) : null, + i.ref && /#\d+$/.test(i.ref) + ? h( + "div", + { class: "row end" }, + reply, + kind + ? h( + "button", + { + class: "small", + onclick: async (e) => { + const note = await ask({ + title: "Mark this as done?", + text: i.action || i.title, + label: "Anything the agents should know (optional)", + okLabel: "I did it", + }); + if (note !== null) act("hands.done", { ref: i.ref, note }, "Marked done; the fleet carries on", e.target); + }, + }, + "I did it", + ) + : null, + ) + : null, + ); +} + +function viewNeeds(sub) { + const counts = needCounts(); + const census = docs.core.census || { hands: [], reviews: [], other: [] }; + const waiting = (docs.core.sessions?.waiting || []).map((w) => ({ ref: w.ref.replace(/^gh:/, ""), title: w.title, why: w.why, action: w.title, url: null })); + const which = sub || (counts.questions ? "questions" : counts.hands ? "hands" : counts.reviews ? "reviews" : "questions"); + const seg = (name, label, n) => + h("button", { "aria-pressed": String(which === name), onclick: () => go(`needs/${name}`) }, `${label} ${n}`); + const out = [ + h( + "div", + { class: "seg" }, + seg("questions", "Questions", counts.questions), + seg("hands", "Only you can do", counts.hands), + seg("reviews", "Reviews", counts.reviews), + seg("other", "Escalated", counts.other), + ), + ...notices(docs.core).slice(0, 2), + ]; + if (which === "questions") out.push(...viewQuestions()); + else if (which === "hands") { + const items = [...census.hands.map((i) => needCard(i, i.kind)), ...waiting.map((i) => needCard(i, "by hand"))]; + out.push(...(items.length ? items : [empty("Nothing needs your hands.")])); + } else if (which === "reviews") { + out.push(...(census.reviews.length ? census.reviews.map((i) => needCard(i)) : [empty("Nothing is waiting for your review.")])); + } else { + out.push( + h("p", { class: "meta" }, "Escalated without a stated action. These are the fleet's to decide; they are listed so nothing is hidden."), + ...(census.other.length ? census.other.map((i) => needCard(i)) : [empty("Nothing here.")]), + ); + } + return out; +} + +// ---- ask --------------------------------------------------------------- + +const STATUS = { + queued: ["Queued", ""], + waiting: ["Waiting for a worker", "warn"], + working: ["Being worked on", "accent"], + answered: ["Answered", "good"], + done: ["Done", "good"], +}; +let draft = ""; + +function viewAsk() { + const box = h("textarea", { + rows: 3, + placeholder: "Say what you want, in your own words. An agent picks it up, does it, and reports back here.", + "aria-label": "Your instruction", + oninput: (e) => { + draft = e.target.value; + }, + }); + box.value = draft; + const Speech = window.SpeechRecognition || window.webkitSpeechRecognition; + let listening = null; + const mic = Speech + ? h( + "button", + { + class: "ghost", + "aria-label": "Dictate", + onclick: (e) => { + const b = e.currentTarget; + if (listening) return listening.stop(); + listening = new Speech(); + listening.interimResults = false; + listening.onresult = (ev) => { + const said = Array.from(ev.results, (r) => r[0].transcript).join(" "); + box.value = `${box.value} ${said}`.trim(); + draft = box.value; + }; + listening.onend = () => { + listening = null; + b.classList.remove("listening"); + b.textContent = "Dictate"; + }; + b.classList.add("listening"); + b.textContent = "Listening…"; + listening.start(); + }, + }, + "Dictate", + ) + : null; + const send = h( + "button", + { + onclick: async (e) => { + const text = box.value.trim(); + if (!text) return toast("Write what you want first", true); + const r = await act("ask.send", { text }, (x) => (x.queued ? `Sent as #${x.issue}; first in the queue` : `Filed as #${x.issue}. ${x.note || ""}`), e.target); + if (r) { + draft = ""; + draw(); + } + }, + }, + "Send", + ); + const asks = docs.core.asks || []; + return [ + h("div", { class: "card composer" }, box, h("div", { class: "row end" }, mic, send)), + ...notices(docs.core).slice(0, 1), + h("h2", {}, "What you have asked"), + ...(asks.length + ? asks.map((a) => { + const [label, tone] = STATUS[a.status] || [a.status, ""]; + return card( + h("div", { class: "row" }, chip(label, tone), ext(a.url, `#${a.issue}`), h("span", { class: "meta" }, `${ago(a.updated)} ago`), a.worker ? h("span", { class: "meta" }, `· ${a.worker}`) : null), + h("div", { class: "bubble you" }, h("b", {}, "You"), a.text), + ...a.replies.map((r) => h("div", { class: `bubble${r.you ? " you" : ""}` }, h("b", {}, `${r.you ? "You" : "Fleet"} · ${ago(r.at)} ago`), r.text)), + h( + "div", + { class: "row end" }, + a.status !== "done" + ? h("button", { class: "small ghost", onclick: (e) => act("ask.close", { issue: a.issue }, "Closed", e.target) }, "Mark done") + : null, + h( + "button", + { + class: "small", + onclick: async (e) => { + const text = await ask({ title: `Reply on #${a.issue}`, label: "Reply", okLabel: "Send", required: true }); + if (text) act("ask.reply", { issue: a.issue, text }, "Sent; the fleet is woken for it", e.target); + }, + }, + "Reply", + ), + ), + ); + }) + : [empty("Nothing yet. Anything you send here becomes the first thing in the queue.")]), + ]; +} + +// ---- more -------------------------------------------------------------- + +function viewMore() { + const ops = docs.ops || {}; + const b = docs.core.board || { counts: {} }; + const tile = (to, title, sub) => h("button", { class: "tile", onclick: () => go(to) }, title, h("span", {}, sub)); + const out = [ + h("h2", {}, "Operations"), + h( + "div", + { class: "tiles" }, + tile("more/queue", "Queue", `${b.counts.blocked ?? "–"} blocked · ${b.counts.parked ?? "–"} parked`), + tile("more/prs", "Pull requests", ops.prs ? `${ops.prs.filter((p) => !p.draft).length} ready of ${ops.prs.length}` : "open and ready to merge"), + tile("more/issues", "Ranked issues", ops.priorities ? `${ops.priorities.issues.length} ranked` : "change what matters most"), + tile("more/agents", "Agents", ops.agents ? `${ops.agents.length} registered` : "message one or all"), + tile("more/services", "Services", ops.services ? `${ops.services.filter((u) => u.active === "failed").length} failed of ${ops.services.length}` : "start, stop, logs"), + tile("more/notify", "Notifications", "choose what reaches this device"), + ), + ]; + for (const g of ops.more || []) { + out.push(h("h2", {}, `Dashboard: ${g.group}`), ...g.pages.map((p) => h("a", { class: "link", href: p.route }, p.title, h("span", {}, p.blurb)))); + } + out.push( + h("h2", {}, "This app"), + h("p", { class: "meta" }, `Signed in as ${me.email || me.certName || me.via || "…"}`), + me.androidApp ? h("a", { class: "link", href: "/console/pm-console.apk" }, "Android app", h("span", {}, "Download the signed build for this phone")) : null, + h("a", { class: "link", href: "/cdn-cgi/access/logout" }, "Sign out"), + ); + return out; +} + +const NOTICE = { + replies: "The fleet replied to something you asked", + needs: "Something new needs you", + questions: "New questions for you", + trouble: "A unit failed", +}; + +function keyBytes(b64) { + const text = atob((b64 + "=".repeat((4 - (b64.length % 4)) % 4)).replace(/-/g, "+").replace(/_/g, "/")); + return Uint8Array.from(text, (c) => c.charCodeAt(0)); +} + +async function viewNotify() { + if (!("serviceWorker" in navigator) || !("PushManager" in window) || !("Notification" in window)) { + return [empty("This browser cannot receive notifications. On Android, use Chrome or the app.")]; + } + const status = await api("push"); + const reg = await navigator.serviceWorker.getRegistration("/console/"); + const sub = reg ? await reg.pushManager.getSubscription() : null; + const on = Boolean(sub) && Notification.permission === "granted"; + const turnOn = async (e) => { + e.target.disabled = true; + try { + if ((await Notification.requestPermission()) !== "granted") { + throw new Error("Notifications are blocked for this site. Allow them in the browser's site settings, then try again."); + } + const r = await navigator.serviceWorker.register("/console/sw.js", { scope: "/console/" }); + await navigator.serviceWorker.ready; + const s = await r.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(status.key) }); + await act("push.on", { subscription: s.toJSON(), label: navigator.userAgent.replace(/^.*\((.*?)\).*$/, "$1").slice(0, 60) }, "Notifications are on for this device"); + } catch (error) { + toast(error.message, true); e.target.disabled = false; - } }, "Check"); - return card(h("h3", {}, h("a", { href: p.url, target: "_blank", rel: "noopener" }, `#${p.number}`), ` ${p.title}`), - h("p", { class: "meta" }, `${p.author} · ${p.branch} · opened ${p.created}`), detail, - h("div", { class: "row end" }, p.draft ? badge("draft", "warn") : null, check, merge)); + } + }; + const turnOff = async (e) => { + const endpoint = sub.endpoint; + await sub.unsubscribe().catch(() => {}); + act("push.off", { endpoint }, "Turned off for this device", e.target); + }; + return [ + card( + h("h3", {}, on ? "On for this device" : "Off for this device"), + h("p", { class: "meta" }, `${status.devices} device${status.devices === 1 ? "" : "s"} subscribed in all.`), + Notification.permission === "denied" ? h("p", { class: "why" }, "This browser is set to block notifications from this site.") : null, + h( + "div", + { class: "row end" }, + on ? h("button", { class: "small ghost", onclick: turnOff }, "Turn off") : null, + on ? h("button", { class: "small ghost", onclick: (e) => act("push.test", {}, (r) => (r.sent ? `Test sent to ${r.sent} device${r.sent === 1 ? "" : "s"}` : "No device took the test"), e.target) }, "Send a test") : null, + on ? null : h("button", { onclick: turnOn }, "Turn on for this device"), + ), + ), + h("h2", {}, "Tell me when"), + card( + ...Object.entries(NOTICE).map(([cls, label]) => + h( + "label", + { class: "row check" }, + h("input", { type: "checkbox", checked: status.classes[cls], onchange: (e) => act("push.class", { class: cls, on: e.target.checked }, e.target.checked ? "On" : "Off") }), + label, + ), + ), + ), + ]; +} + +const QUEUE_STATES = ["blocked", "queued", "claimed", "parked"]; +let queueState = { status: "blocked", q: "" }; +async function viewQueue() { + const data = await api(`queue?status=${queueState.status}&q=${encodeURIComponent(queueState.q)}`); + const pick = h( + "select", + { + class: "narrow", + "aria-label": "State", + onchange: (e) => { + queueState.status = e.target.value; + draw(); + }, + }, + QUEUE_STATES.map((s) => h("option", { value: s, selected: s === queueState.status }, `${s} (${data.counts[s] ?? 0})`)), + ); + const search = h("input", { + type: "search", + placeholder: "Filter by title", + "aria-label": "Filter by title", + value: queueState.q, + onchange: (e) => { + queueState.q = e.target.value; + draw(); + }, }); + const reason = async (t, verb, danger) => ask({ title: `${verb} this task?`, text: t.title, label: "Why", okLabel: verb, danger, required: true }); + return [ + card(h("div", { class: "row" }, pick, h("span", { class: "grow" }), search)), + ...(data.tasks.length + ? data.tasks.map((t) => + card( + h("h3", {}, t.title), + h("p", { class: "meta" }, `${band(t.priority)} · updated ${String(t.updated ?? "").replace("T", " ")}`), + t.why ? h("p", { class: "why" }, String(t.why)) : null, + h( + "div", + { class: "row end" }, + t.status === "blocked" + ? h( + "button", + { + class: "small", + onclick: async (e) => { + const why = await reason(t, "Unblock", false); + if (why) act("task.unblock", { task: t.id, reason: why }, "Unblocked", e.target); + }, + }, + "Unblock", + ) + : null, + h( + "button", + { + class: "small ghost", + onclick: async (e) => { + const why = await reason(t, "Cancel", true); + if (why) act("task.cancel", { task: t.id, reason: why }, "Cancelled", e.target); + }, + }, + "Cancel", + ), + ), + ), + ) + : [empty("No tasks in this state.")]), + ]; } -// ---- shell ----------------------------------------------------------------- +function viewPrs() { + const prs = docs.ops?.prs; + if (!prs) return [empty("Loading…")]; + const row = (p) => { + const detail = h("div", {}); + return card( + h("h3", {}, ext(p.url, `#${p.number}`), ` ${p.title}`), + h("p", { class: "meta" }, `${p.draft ? "draft · " : ""}${p.author} · ${p.branch} · opened ${ago(p.created)} ago`), + detail, + h( + "div", + { class: "row end" }, + h( + "button", + { + class: "small ghost", + onclick: async (e) => { + e.target.disabled = true; + try { + const d = await api(`prs/${p.number}`); + detail.replaceChildren( + h("p", { class: d.mergeable ? "meta" : "why" }, `${d.mergeable === null ? "mergeability not known yet" : d.mergeable ? "can merge" : "cannot merge"} (${d.mergeable_state}) · +${d.additions} −${d.deletions} in ${d.changed_files} files · ${d.review_comments} review comments`), + ); + } catch (error) { + toast(error.message, true); + } + e.target.disabled = false; + }, + }, + "Check", + ), + p.draft + ? null + : h( + "button", + { + class: "small", + onclick: async (e) => { + const yes = await ask({ title: `Merge #${p.number}?`, text: p.title, okLabel: "Merge" }); + if (yes !== null) act("pr.merge", { pr: p.number }, `#${p.number} merged`, e.target); + }, + }, + "Merge", + ), + ), + ); + }; + const ready = prs.filter((p) => !p.draft); + const drafts = prs.filter((p) => p.draft); + return [ + h("h2", {}, `Ready (${ready.length})`), + ...(ready.length ? ready.map(row) : [empty("No pull request is ready.")]), + drafts.length ? h("h2", {}, `Drafts (${drafts.length})`) : null, + ...drafts.map(row), + ]; +} -const VIEWS = { overview: ["Overview", overview], queue: ["Queue", queue], priorities: ["Priorities", priorities], agents: ["Agents", agents], services: ["Services", services], prs: ["Pull requests", prs] }; -let current = "overview"; -let showSeq = 0; +function viewIssues() { + const list = docs.ops?.priorities; + if (!list) return [empty("Loading…")]; + return [ + list.truncated ? empty("There are more ranked issues than this list reads. The most urgent may not all be here.") : null, + ...(list.issues.length ? list.issues.map(issueCard) : [empty("No ranked issues.")]), + ]; +} -async function show(name) { - // Views load at different speeds. Only the latest call may draw, or a - // slow earlier view would land on top of the one now selected. - const seq = ++showSeq; - current = VIEWS[name] ? name : "overview"; - history.replaceState(null, "", `#${current}`); - for (const b of tabs.children) b.toggleAttribute("aria-current", false); - const active = tabs.querySelector(`[data-view="${current}"]`); - if (active) active.setAttribute("aria-current", "page"); - view.replaceChildren(empty("Loading…")); +async function viewAgents() { + const agents = docs.ops?.agents || []; + const to = h("select", { "aria-label": "To" }, h("option", { value: "all" }, "Everyone"), agents.map((a) => h("option", { value: `agent:${a.name}` }, a.name))); + const text = h("textarea", { rows: 3, placeholder: "A message, or a command to act on", "aria-label": "Message" }); + const command = h("input", { type: "checkbox", id: "cmd" }); + const compose = card( + to, + text, + h( + "div", + { class: "row end" }, + h("label", { for: "cmd", class: "row meta" }, command, "Send as a command"), + h( + "button", + { + onclick: (e) => + text.value.trim() ? act("message.send", { to: [to.value], text: text.value, command: command.checked }, "Sent", e.target) : toast("Write a message first", true), + }, + "Send", + ), + ), + ); + let recent = []; try { - const drawn = await VIEWS[current][1](); - if (seq === showSeq) view.replaceChildren(...drawn); + recent = await api("messages?limit=15"); + } catch { + // the roster below is still useful without the log + } + return [ + compose, + h("h2", {}, `Agents (${agents.length})`), + ...agents.map((a) => + card(h("h3", {}, a.name), h("p", { class: "meta" }, `${(a.groups || []).join(", ")} · seen ${ago(a.last_seen) || "never"} ago · ${a.unread_commands ?? 0} commands and ${a.unread_messages ?? 0} messages unread`)), + ), + h("h2", {}, "Recent messages"), + ...(recent.length + ? recent.map((m) => card(h("p", { class: "meta" }, `${ago(m.ts)} ago · ${m.direction} · ${m.agent} · ${m.kind}`), h("p", {}, String(m.body ?? "").slice(0, 600)))) + : [empty("No messages.")]), + ]; +} + +function viewServices() { + const units = docs.ops?.services; + if (!units) return [empty("Loading…")]; + const row = (u) => { + const log = h("div", {}); + const doit = (action, danger) => + h( + "button", + { + class: `small${danger ? " ghost" : ""}`, + onclick: async (e) => { + const yes = await ask({ title: `${action} ${u.unit}?`, okLabel: action, danger }); + if (yes !== null) act("unit.act", { unit: u.unit, action }, `${u.unit}: ${action} done`, e.target); + }, + }, + action, + ); + return h( + "div", + { class: `card${u.active === "failed" ? " flag" : ""}` }, + h("div", { class: "row" }, h("h3", {}, u.unit), chip(`${u.active} · ${u.sub}`, u.active === "active" ? "good" : u.active === "failed" ? "warn" : "")), + h("p", { class: "meta" }, u.description), + log, + h( + "div", + { class: "row end" }, + h( + "button", + { + class: "small ghost", + onclick: async (e) => { + e.target.disabled = true; + try { + const d = await api(`services/${encodeURIComponent(u.unit)}/logs?lines=40`); + log.replaceChildren(h("pre", {}, d.log || "(no log lines)")); + } catch (error) { + toast(error.message, true); + } + e.target.disabled = false; + }, + }, + "Logs", + ), + u.active === "active" ? doit("restart") : doit("start"), + u.active === "active" ? doit("stop", true) : null, + ), + ); + }; + const failed = units.filter((u) => u.active === "failed"); + const rest = units.filter((u) => u.active !== "failed"); + return [failed.length ? h("h2", {}, `Failed (${failed.length})`) : null, ...failed.map(row), h("h2", {}, `All units (${units.length})`), ...rest.map(row)]; +} + +// ---- shell ------------------------------------------------------------- + +const TABS = [ + ["now", "Now", "M3 12h4l3-8 4 16 3-8h4"], + ["next", "Next", "M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01"], + ["needs", "Needs me", "M12 8v5M12 16.5h.01M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z"], + ["ask", "Ask", "M21 15a2 2 0 0 1-2 2H8l-5 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"], + ["more", "More", "M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z"], +]; +const VIEWS = { + now: ["Now", viewNow], + next: ["Next", viewNext, "ops"], + needs: ["Needs me", viewNeeds, "questions"], + ask: ["Ask", viewAsk], + more: ["More", viewMore, "ops"], + "more/queue": ["Queue", viewQueue], + "more/prs": ["Pull requests", viewPrs, "ops"], + "more/issues": ["Ranked issues", viewIssues, "ops"], + "more/agents": ["Agents", viewAgents, "ops"], + "more/services": ["Services", viewServices, "ops"], + "more/notify": ["Notifications", viewNotify], +}; +let route = "now"; +let drawSeq = 0; + +function parse(hash) { + const r = hash.replace(/^#/, ""); + if (VIEWS[r]) return [r, undefined]; + const [top, sub] = r.split("/"); + return VIEWS[top] ? [top, sub] : ["now", undefined]; +} + +function go(to) { + if (location.hash === `#${to}`) draw(); + else location.hash = to; +} + +function drawTabs() { + const n = needCounts(); + const fresh = (docs.core?.asks || []).filter((a) => a.status === "answered").length; + tabsEl.replaceChildren( + ...TABS.map(([name, label, d]) => { + const count = name === "needs" ? n.total : name === "ask" ? fresh : 0; + return h( + "button", + { "aria-current": route.split("/")[0] === name ? "page" : null, onclick: () => go(name) }, + icon(d), + label, + count ? h("span", { class: "badge" }, count > 99 ? "99+" : String(count)) : null, + ); + }), + ); +} + +function drawFresh() { + const t = asOf.core; + const age = t ? (Date.now() - t) / 1000 : null; + freshEl.className = `fresh${signedOut ? " down" : age !== null && age > 180 ? " stale" : ""}`; + freshEl.textContent = signedOut ? "signed out" : age === null ? "" : age < 45 ? "live" : `as of ${ago(new Date(t).toISOString())} ago`; +} + +/** Draw the current section from what is already loaded. Only the latest + * call may draw, so a slow section never lands on top of a newer one. */ +async function draw() { + const seq = ++drawSeq; + const [name, sub] = parse(location.hash); + route = sub ? `${name}/${sub}` : name; + const [title, render, extra] = VIEWS[name]; + $("title").textContent = title; + $("back").hidden = !name.includes("/"); + drawTabs(); + drawFresh(); + if (!docs.core) return view.replaceChildren(empty("Loading…")); + if (extra && !docs[extra]) loadDoc(extra).then(() => seq === drawSeq && draw()).catch(() => {}); + try { + const nodes = await render(sub); + if (seq === drawSeq) view.replaceChildren(...nodes.filter(Boolean)); + } catch (error) { + if (seq !== drawSeq) return; + view.replaceChildren( + card(h("h3", {}, "This section could not load"), h("p", { class: "why" }, error.message), h("div", { class: "row end" }, h("button", { onclick: () => (signedOut ? location.reload() : draw()) }, signedOut ? "Reload" : "Try again"))), + ); + } +} + +/** Read the documents again; draw only if something changed, or if asked. */ +async function refresh(force) { + const [name] = parse(location.hash); + const extra = VIEWS[name][2]; + let changed = false; + try { + changed = await loadDoc("core"); + if (extra) changed = (await loadDoc(extra)) || changed; } catch (error) { - if (seq !== showSeq) return; - view.replaceChildren(card(h("h3", {}, "This section could not load"), h("p", { class: "why" }, error.message), h("div", { class: "row end" }, h("button", { onclick: () => show(current) }, "Try again")))); + if (!docs.core) view.replaceChildren(card(h("h3", {}, "Could not load"), h("p", { class: "why" }, error.message), h("div", { class: "row end" }, h("button", { onclick: () => location.reload() }, "Reload")))); + } + // An open dialog or a half-typed answer is not redrawn from under the reader. + const busy = $("ask").open || pending.size > 0 || (document.activeElement && ["TEXTAREA", "INPUT", "SELECT"].includes(document.activeElement.tagName)); + if (force || (changed && !busy)) draw(); + else { + drawTabs(); + drawFresh(); } } -for (const [name, [label]] of Object.entries(VIEWS)) tabs.append(h("button", { "data-view": name, onclick: () => show(name) }, label)); -api("me").then((me) => { - document.getElementById("who").textContent = me.email || me.certName || me.via; - document.getElementById("apk").hidden = !me.androidApp; -}).catch(() => {}); -show(location.hash.slice(1)); +if (typeof document !== "undefined" && view) { + $("refresh").addEventListener("click", () => refresh(true)); + $("back").addEventListener("click", () => go(route.split("/")[0])); + addEventListener("hashchange", () => { + shown = 12; + draw(); + }); + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "hidden") flushPending(); + else refresh(false); + }); + addEventListener("pagehide", flushPending); + setInterval(() => document.visibilityState === "visible" && refresh(false), 20_000); + setInterval(drawFresh, 10_000); + api("me") + .then((m) => { + me = m; + }) + .catch(() => {}); + // The worker shows notifications and opens the right screen when one is tapped. + if ("serviceWorker" in navigator) navigator.serviceWorker.register("/console/sw.js", { scope: "/console/" }).catch(() => {}); + draw(); + refresh(true); +} diff --git a/pm-stack/console/public/index.html b/pm-stack/console/public/index.html index fc072f8465..9c60003158 100644 --- a/pm-stack/console/public/index.html +++ b/pm-stack/console/public/index.html @@ -2,43 +2,36 @@ - - - Console · PM stack - + + + PM + -
- Console - Dashboard - +
+ +

Now

- + +
-
+ -
+

- - + +
- + diff --git a/pm-stack/console/public/sw.js b/pm-stack/console/public/sw.js new file mode 100644 index 0000000000..cb7f646694 --- /dev/null +++ b/pm-stack/console/public/sw.js @@ -0,0 +1,40 @@ +// The app's service worker: it shows a notification when one is pushed, +// and opens the right screen when it is tapped. +self.addEventListener("install", () => self.skipWaiting()); +self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim())); + +self.addEventListener("push", (event) => { + let data = {}; + try { + data = event.data ? event.data.json() : {}; + } catch { + data = {}; + } + event.waitUntil( + self.registration.showNotification(data.title || "PM", { + body: data.body || "", + tag: data.tag || undefined, + renotify: Boolean(data.tag), + icon: "/icons/icon-192.png", + badge: "/icons/icon-192.png", + data: { url: data.url || "/console/" }, + }), + ); +}); + +self.addEventListener("notificationclick", (event) => { + event.notification.close(); + const url = event.notification.data?.url || "/console/"; + event.waitUntil( + (async () => { + const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true }); + for (const client of windows) { + if (new URL(client.url).pathname.startsWith("/console")) { + await client.focus(); + return client.navigate ? client.navigate(url) : undefined; + } + } + return self.clients.openWindow(url); + })(), + ); +}); diff --git a/pm-stack/console/scripts/demo.ts b/pm-stack/console/scripts/demo.ts new file mode 100644 index 0000000000..9ceacbe78d --- /dev/null +++ b/pm-stack/console/scripts/demo.ts @@ -0,0 +1,371 @@ +// Run the interface against canned state, to look at it without a fleet. +// +// bun run scripts/demo.ts [port] then open http://127.0.0.1:/console/ +// +// The real server code answers; only the sources are canned, and every +// action succeeds and is listed under "What you did". +import { readConfig } from "../src/config.ts"; +import { Docs } from "../src/docs.ts"; +import { Ops } from "../src/ops.ts"; +import { Push } from "../src/push.ts"; +import { handle } from "../src/server.ts"; + +const iso = (minutesAgo: number) => new Date(Date.now() - minutesAgo * 60_000).toISOString().slice(0, 19); +const task = (id: number, title: string, extra: Record) => ({ + id, + title, + priority: 30, + status: "queued", + attempts: 1, + claimed: "", + lease: "", + created: iso(300), + worker: null, + lane: null, + model: null, + kind: "small_fix", + issue: 9000 + id, + pr: null, + step: "", + goal: "The fix lands with a test that fails without it", + url: `https://github.com/developing-today/code/issues/${9000 + id}`, + ...extra, +}); +const question = (set: string, n: number, extra: Record = {}) => ({ + set, + setTitle: `Pending questions — ${set}`, + created: iso(60 * 24 * n), + ledger: `ledger-${set}-${n}`, + item: `PM-stack S${n} attachments (#1003${n}): where do attachments live`, + links: [`https://github.com/developing-today/code/issues/1003${n}`], + qid: `q${n}`, + q: `For S${n} attachments and multimedia, build new storage, or reuse a mechanism outside pm-stack that you name?`, + context: "Attachments today are pasted links. The dashboard has no storage of its own, and three pages want one.", + detail: + "Building new keeps the stack self-contained. Reusing means one fewer store to run, but ties the release to another project.", + multi: false, + recommended: ["opt-1"], + options: [ + { id: "opt-1", label: "Build new attachment storage", tags: ["recommended", "simpler"] }, + { id: "opt-2", label: "Reuse a mechanism outside pm-stack (name it in your answer)", tags: [] }, + { id: "opt-3", label: "Build new now; migrate storage refs later", tags: ["reversible"] }, + ], + ...extra, +}); + +const state = { + board: { + counts: { claimed: 3, queued: 4, blocked: 474, parked: 58 }, + now: [ + task(1, "Fix #9075: session state — session id in env and a resume path", { + status: "claimed", + claimed: iso(14), + worker: "repo-worker-code", + lane: "oc-code-02", + model: "workhorse", + attempts: 8, + step: "Write the failing test for resume after a crash, then wire the env var through the launcher.", + }), + task(2, "Implement mcpx Roc script support after the Python parity gate", { + status: "claimed", + claimed: iso(41), + worker: "repo-worker-code", + lane: "code-h", + priority: 20, + step: "Resume only when a compatible docs build is available.", + }), + task(3, "Fix #2723 phase 3: PendingHold post and void lifecycle", { + status: "claimed", + claimed: iso(3), + worker: "repo-worker-code", + lane: "code-j", + goal: "Posting and voiding a hold are covered by the ledger property tests", + }), + ], + next: [ + task(4, "Owner prompt developing-today/code#12501: make the join-at-admission slice the top priority", { + priority: 10, + kind: "triage", + }), + task(5, "Triage developing-today/code#12416: link from the dashboard to the console", { + priority: 30, + kind: "triage", + }), + task(6, "Merge-watch developing-today/code#12240: recheck fix PR for issue #12230", { + priority: 30, + kind: "pr_shepherd", + }), + task(7, "Fix #11350: toolchain file drift between crates", { priority: 50 }), + ], + blockedWhy: [ + { why: "waits on #9106 (open, all PRs merged)", n: 212 }, + { why: "no reason recorded", n: 140 }, + { why: '{"kind":"time","until":"2026-11-19T14:02:00Z"}', n: 4 }, + ], + }, + sessions: { + moving: [ + { + id: "s1", + title: "F12.11 binary frames: fuzz the decoder", + agent: "build", + model: "gpt-5.2-codex", + where: "git/code-j", + last: iso(1), + tools: 2, + messages: 141, + }, + { + id: "s2", + title: "Triage sweep: opencode", + agent: "triage", + model: "workhorse", + where: "git/opencode", + last: iso(6), + tools: 0, + messages: 37, + }, + ], + waiting: [ + { + id: "porkbun", + title: "Porkbun: log into the main account and enter the password in the staged modal", + ref: "gh:developing-today/code#902", + why: "", + }, + ], + }, + census: { + at: iso(1), + complete: true, + hands: [ + { + ref: "developing-today/code#12417", + title: "Google sign-in for pm.security.cab: create the OAuth client", + url: "https://github.com/developing-today/code/issues/12417", + pr: false, + updated: iso(50), + kind: "interactive-login", + action: + "Create a Google OAuth web client with the redirect URI in the issue and save its ID and secret in Bitwarden.", + }, + { + ref: "developing-today/code#1080", + title: "epic(cluster): hardware inventory and first-node selection", + url: "https://github.com/developing-today/code/issues/1080", + pr: false, + updated: iso(60 * 24 * 9), + kind: "physical", + action: "Power on one Threadripper host and make its BMC reachable to the worker.", + }, + ], + reviews: [ + { + ref: "developing-today/code#24", + title: "Dependency Dashboard", + url: "https://github.com/developing-today/code/issues/24", + pr: false, + updated: iso(60 * 30), + }, + ], + other: [ + { + ref: "developing-today/code#1086", + title: "epic(cluster): TALM and Talos bootstrap", + url: "https://github.com/developing-today/code/issues/1086", + pr: false, + updated: iso(60 * 24 * 20), + why: "", + }, + ], + }, + asks: [ + { + issue: 12501, + url: "https://github.com/developing-today/code/issues/12501", + text: "Make the join-at-admission slice the top priority and tell me what is in its way.", + created: iso(30), + updated: iso(4), + status: "answered", + worker: null, + replies: [ + { + you: false, + at: iso(4), + text: "Done. #12279 is ranked expedite and its task is first in the queue. In its way: #12230 (36 test files in no registry row) fails the lint the slice's PR will run. I queued that ahead of it.", + }, + ], + }, + { + issue: 12499, + url: "https://github.com/developing-today/code/issues/12499", + text: "What is blocked and why? One paragraph.", + created: iso(200), + updated: iso(180), + status: "done", + worker: null, + replies: [ + { + you: false, + at: iso(180), + text: "474 tasks are blocked. 212 wait on #9106, which is open although every PR for it is merged; closing it frees them.", + }, + ], + }, + { + issue: 12502, + url: "https://github.com/developing-today/code/issues/12502", + text: "Add a dark and light theme switch to the app.", + created: iso(2), + updated: iso(2), + status: "queued", + worker: null, + replies: [], + }, + ], + questionCount: { total: 6, sets: 2 }, + questions: { + total: 6, + sets: 2, + open: [ + question("2026-11-17", 7), + question("2026-11-17", 8, { + q: "Which checks must pass before a batch merges?", + multi: true, + recommended: ["opt-1", "opt-3"], + options: [ + { id: "opt-1", label: "Unit tests of the crates the batch touches", tags: ["recommended"] }, + { id: "opt-2", label: "The whole workspace", tags: ["safer"] }, + { id: "opt-3", label: "The module reach check", tags: ["recommended"] }, + ], + }), + question("2026-11-17", 9, { recommended: [], context: "", detail: "" }), + question("2026-11-16", 4), + question("2026-11-16", 5), + question("2026-11-16", 6), + ], + }, + prs: [ + { + number: 12240, + title: "ci(id): register the 36 unwired suites", + draft: false, + url: "https://github.com/developing-today/code/pull/12240", + created: iso(60 * 20), + author: "dezren39", + branch: "task/suite-registry", + }, + { + number: 12241, + title: "feat(id): F12.11 binary frames, encoder", + draft: false, + url: "https://github.com/developing-today/code/pull/12241", + created: iso(60 * 19), + author: "dezren39", + branch: "task/f12-11-frames", + }, + { + number: 12390, + title: "wip: talos bootstrap notes", + draft: true, + url: "https://github.com/developing-today/code/pull/12390", + created: iso(60 * 3), + author: "dezren39", + branch: "wip/talos", + }, + ], + priorities: { + truncated: false, + issues: [ + { + number: 4000, + title: "id: Phase 12 exit", + url: "https://github.com/developing-today/code/issues/4000", + updated: iso(90), + comments: 14, + labels: ["expedite"], + rank: "expedite", + order: 0, + }, + { + number: 12279, + title: "id: join at admission (slice 3)", + url: "https://github.com/developing-today/code/issues/12279", + updated: iso(300), + comments: 2, + labels: ["now"], + rank: "now", + order: 2, + }, + ], + }, + agents: [ + { name: "conductor", groups: ["opencode"], last_seen: iso(2), unread_commands: 0, unread_messages: 1 }, + { name: "muse", groups: ["research"], last_seen: iso(400), unread_commands: 2, unread_messages: 0 }, + ], + services: [ + { unit: "pm-aggregator.service", load: "loaded", active: "active", sub: "running", description: "PM dashboard" }, + { + unit: "opencode-go-seating-guard.service", + load: "loaded", + active: "failed", + sub: "failed", + description: "OpenCode Go seating guard", + }, + { + unit: "queue-broker.service", + load: "loaded", + active: "active", + sub: "running", + description: "Repo queue broker", + }, + ], + more: [ + { + group: "Overview", + pages: [ + { + title: "Overview", + route: "/?dashboard", + blurb: "The stack front door: needs-you, projects, quotas and health at a glance.", + }, + { title: "Today", route: "/today", blurb: "What changed today." }, + ], + }, + { group: "Work", pages: [{ title: "Roadmap", route: "/roadmap", blurb: "Phases and what is in each." }] }, + ], +}; + +const cfg = readConfig({ HOME: "/tmp", PM_CONSOLE_DASHBOARD_URL: "" }); +const docs = new Docs( + Object.fromEntries(Object.entries(state).map(([name, data]) => [name, { ttlMs: 3_600_000, load: async () => data }])), +); +const done = (result: unknown) => ({ run: async () => result, touch: [] as string[], audit: () => ({}) }); +const table = new Proxy({} as Record>, { + get: (_t, kind) => + done( + kind === "ask.send" + ? { issue: 12503, queued: true } + : kind === "questions.accept" + ? { applied: 2, refused: [] } + : { ok: true }, + ), + has: () => true, + getOwnPropertyDescriptor: () => ({ configurable: true, enumerable: true, value: done({}) }), +}); +const port = Number(process.argv[2] ?? 4899); +Bun.serve({ + hostname: "127.0.0.1", + port, + fetch: (req) => + handle(req, { + cfg, + ops: new Ops(cfg, async () => ({ code: 0, stdout: "[]", stderr: "" })), + docs, + push: new Push("/tmp/pm-console-demo-push.json", "mailto:you@example.com", async () => ({ status: 201 })), + actions: table, + identify: async () => ({ via: "demo", email: "you@example.com" }), + audit: async () => {}, + }), +}); +console.log(`demo: http://127.0.0.1:${port}/console/`); diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py index 468b4e08ce..2c156d4179 100755 --- a/pm-stack/console/scripts/expose.py +++ b/pm-stack/console/scripts/expose.py @@ -50,10 +50,12 @@ CONSOLE = "http://localhost:4872" UNIT = "pm-console.service" # The sign-in cookie is not sent on another site's requests, and page -# scripts cannot read it. +# scripts cannot read it. A sign-in lasts a month, so signing in is a +# rare event and not a daily one. APP_SETTINGS = { "same_site_cookie_attribute": "lax", "http_only_cookie_attribute": True, + "session_duration": "720h", } PUBLIC_PATHS = ("/.well-known/assetlinks.json", "/manifest.webmanifest", "/icons") GOOGLE_ID = "google.access-sso.client-id" diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py index 5ebf315bf7..9b62a96d03 100755 --- a/pm-stack/console/scripts/test_expose.py +++ b/pm-stack/console/scripts/test_expose.py @@ -165,6 +165,7 @@ def test_the_gate_exists_before_the_route(self): ) self.assertEqual(main["allowed_idps"], ["idp-onetimepin"]) self.assertEqual(main["same_site_cookie_attribute"], "lax") + self.assertEqual(main["session_duration"], "720h") self.assertIs(main["http_only_cookie_attribute"], True) for path in expose.PUBLIC_PATHS: app = next(a for a in account.apps if a["domain"] == HOST + path) diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts new file mode 100644 index 0000000000..da6007338a --- /dev/null +++ b/pm-stack/console/src/actions.ts @@ -0,0 +1,116 @@ +// Everything the owner can do, as one list of named actions. +// +// One endpoint takes `{ kind, args }`. Each action names the sections it +// changes, so the documents are read again before the answer goes back, +// and what it leaves in the audit log, which never includes the text the +// owner typed. +import type { Docs } from "./docs.ts"; +import { OpError, type Ops } from "./ops.ts"; +import type { Push } from "./push.ts"; +import type { Work } from "./work.ts"; + +type Args = Record; +interface Action { + run: (args: Args) => Promise; + /** Sections to read again afterwards. */ + touch: string[]; + /** What the audit log keeps of the arguments. */ + audit: (args: Args) => Args; +} + +const ids = + (...keys: string[]) => + (args: Args) => + Object.fromEntries(keys.map((k) => [k, args[k]])); + +/** A refusal from the push module is the caller's mistake, not a failure of this service. */ +const asked = async (p: Promise): Promise => + p.catch((error: Error) => { + throw error instanceof OpError ? error : new OpError(400, error.message); + }); + +export function actions(ops: Ops, work: Work, push?: Push): Record { + const notify: Record = push + ? { + "push.on": { run: (a) => asked(push.subscribe(a.subscription, a.label)), touch: [], audit: () => ({}) }, + "push.off": { run: (a) => asked(push.unsubscribe(a.endpoint)), touch: [], audit: () => ({}) }, + "push.class": { run: (a) => asked(push.setClass(a.class, a.on)), touch: [], audit: ids("class", "on") }, + "push.test": { + run: () => + push.send("test", { + title: "PM", + body: "Notifications are on for this device.", + url: "/console/", + tag: "test", + }), + touch: [], + audit: () => ({}), + }, + } + : {}; + return { + ...notify, + "ask.send": { run: (a) => work.ask(a), touch: ["asks", "board"], audit: () => ({}) }, + "ask.reply": { run: (a) => work.askReply(a), touch: ["asks", "board"], audit: ids("issue") }, + "ask.close": { run: (a) => work.askClose(a), touch: ["asks"], audit: ids("issue") }, + "question.answer": { + run: (a) => work.answer(a), + touch: ["questions", "questionCount"], + audit: ids("set", "ledger", "qid", "option", "options"), + }, + "question.defer": { + run: (a) => work.defer(a), + touch: ["questions", "questionCount"], + audit: ids("set", "ledger", "qid", "lean"), + }, + "questions.accept": { + run: (a) => work.acceptRecommended(a.set), + touch: ["questions", "questionCount"], + audit: ids("set"), + }, + "hands.done": { run: (a) => work.handsDone(a), touch: [], audit: ids("ref") }, + "need.comment": { run: (a) => work.needComment(a), touch: [], audit: ids("ref") }, + "task.move": { run: (a) => work.moveTask(a), touch: ["board"], audit: ids("task", "to") }, + "task.unblock": { + run: (a) => ops.queueAct("unblock", a.task, a.reason), + touch: ["board"], + audit: ids("task", "reason"), + }, + "task.cancel": { + run: (a) => ops.queueAct("cancel", a.task, a.reason), + touch: ["board"], + audit: ids("task", "reason"), + }, + "issue.rank": { run: (a) => ops.setRank(a.issue, a.rank), touch: ["priorities"], audit: ids("issue", "rank") }, + "issue.comment": { run: (a) => ops.comment(a.issue, a.text), touch: [], audit: ids("issue") }, + "pr.merge": { run: (a) => ops.mergePr(a.pr), touch: ["prs"], audit: ids("pr") }, + "unit.act": { + run: (a) => ops.serviceAct(a.unit, a.action), + touch: ["services"], + audit: ids("unit", "action"), + }, + "message.send": { + run: (a) => ops.send(a.to, a.text, a.command), + touch: [], + audit: (a) => ({ to: a.to, command: a.command === true }), + }, + }; +} + +/** Run one named action and read again what it changed. */ +export async function perform( + table: Record, + docs: Docs, + kind: unknown, + args: unknown, +): Promise { + const action = typeof kind === "string" && Object.hasOwn(table, kind) ? table[kind] : undefined; + if (!action) throw new OpError(400, "kind: not an action this console has"); + if (args === null || typeof args !== "object" || Array.isArray(args)) + throw new OpError(400, "args: expected an object"); + const result = await action.run(args as Args); + // The census is the dashboard's and refreshes on its own clock; for the + // rest, the caller's next read should already show the change. + await docs.touch(action.touch); + return result; +} diff --git a/pm-stack/console/src/config.ts b/pm-stack/console/src/config.ts index 274150780f..d32daa07b0 100644 --- a/pm-stack/console/src/config.ts +++ b/pm-stack/console/src/config.ts @@ -52,6 +52,13 @@ export interface Config { /** The signed APK the console hands to the signed-in owner, if the * file exists. */ androidApk: string; + /** The dashboard's decision-set store: the questions waiting on the + * owner, and the per-set tokens that authorise an answer. */ + decisionsFile: string; + /** Label on an issue that is an instruction from the owner. */ + promptLabel: string; + /** Repositories whose issues may be answered from "Needs me". */ + needsRepos: string[]; } export class ConfigError extends Error {} @@ -211,5 +218,13 @@ export function readConfig( androidPackage: env.PM_CONSOLE_ANDROID_PACKAGE ?? "today.developing.pmconsole", androidFingerprints: fingerprints, androidApk: env.PM_CONSOLE_ANDROID_APK ?? `${home}/.local/state/pm-console/android/pm-console.apk`, + 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", [ + "developing-today/code", + "developing-today/opencode", + "developing-today/openchamber", + "dezren39/nix", + ]), }; } diff --git a/pm-stack/console/src/docs.ts b/pm-stack/console/src/docs.ts new file mode 100644 index 0000000000..56cb9cd2be --- /dev/null +++ b/pm-stack/console/src/docs.ts @@ -0,0 +1,175 @@ +// The state the interface draws, kept ready. +// +// A page never waits on a live fan-out to GitHub, the queue store or the +// dashboard: each source is a section that is refreshed in the +// background and served from memory, with the time it was last read and +// the error if the last read failed. Three documents are built from the +// sections, sized for a phone on a poor link: +// +// core what is in progress, what is next, what needs the owner, +// what he has asked for (small, polled) +// questions every open question waiting on him (large, read on demand) +// ops pull requests, ranked issues, agents, units, other pages +// +// The same documents can be stored and served somewhere else: nothing in +// them depends on this process. +import { createHash } from "node:crypto"; + +export type DocName = "core" | "questions" | "ops"; +export const DOC_NAMES: DocName[] = ["core", "questions", "ops"]; + +interface Section { + /** Refresh when older than this while someone is looking. */ + ttlMs: number; + load: () => Promise; + at: number; + /** When it was last read successfully. */ + goodAt: number; + ok: boolean; + error: string | null; + data: unknown; + loading: Promise | null; +} + +export interface Act { + id: string; + kind: string; + at: string; + by: string; + status: "running" | "done" | "failed"; + note: string; +} + +/** Which sections each document is built from. */ +const DOCS: Record = { + core: ["board", "sessions", "census", "asks", "questionCount"], + questions: ["questions"], + ops: ["prs", "priorities", "agents", "services", "more"], +}; +/** Stop refreshing when nobody has asked for this long. */ +const WATCH_MS = 10 * 60_000; +const FIRST_LOAD_MS = 25_000; +const ACTS_KEPT = 30; + +export class Docs { + private sections = new Map(); + private asked = 0; + private acts: Act[] = []; + private timer: ReturnType | null = null; + + constructor( + loaders: Record Promise }>, + private now: () => number = Date.now, + ) { + for (const [name, l] of Object.entries(loaders)) { + this.sections.set(name, { ...l, at: 0, goodAt: 0, ok: false, error: null, data: null, loading: null }); + } + for (const names of Object.values(DOCS)) { + for (const name of names) { + if (!this.sections.has(name)) throw new Error(`no loader for section ${name}`); + } + } + } + + /** Read one section again. Concurrent callers share the read. A failed + * read keeps the last good data and records why. */ + refresh(name: string): Promise { + const s = this.sections.get(name); + if (!s) return Promise.resolve(); + if (s.loading) return s.loading; + s.loading = (async () => { + try { + s.data = await s.load(); + s.ok = true; + s.error = null; + s.goodAt = this.now(); + } catch (error) { + s.ok = false; + s.error = (error as Error).message.slice(0, 300); + } finally { + s.at = this.now(); + s.loading = null; + } + })(); + return s.loading; + } + + /** After an action: read the sections it changed, so the next document shows it. */ + async touch(names: string[]): Promise { + await Promise.all(names.map((n) => this.refresh(n))); + } + + private stale(s: Section): boolean { + return this.now() - s.at > s.ttlMs; + } + + /** One pass of the background loop: refresh what is stale, if anyone is looking. */ + tick(): void { + if (this.now() - this.asked > WATCH_MS) return; + for (const [name, s] of this.sections) { + if (this.stale(s)) void this.refresh(name); + } + } + + start(everyMs = 5_000): void { + this.timer ??= setInterval(() => this.tick(), everyMs); + } + + stop(): void { + if (this.timer) clearInterval(this.timer); + this.timer = null; + } + + /** The last good copy of one section, or null if it has never been read. */ + good(name: string): unknown { + const s = this.sections.get(name); + return s && s.goodAt > 0 ? s.data : null; + } + + logAct(act: Act): void { + this.acts = [act, ...this.acts.filter((a) => a.id !== act.id)].slice(0, ACTS_KEPT); + } + + /** The document, at once. Only a section that has never been read is + * waited for, and only so long. `asOf` is now when every section has + * been read within its own interval, and earlier by however far the + * most overdue section is behind: how stale the document really is. */ + async doc(name: DocName): Promise<{ etag: string; body: string; asOf: number }> { + this.asked = this.now(); + const names = DOCS[name]; + const section = (n: string) => this.sections.get(n) as Section; + const never = names.filter((n) => section(n).at === 0); + if (never.length > 0) { + let timer: ReturnType | undefined; + await Promise.race([ + Promise.all(never.map((n) => this.refresh(n))), + new Promise((resolve) => { + timer = setTimeout(resolve, FIRST_LOAD_MS); + }), + ]); + clearTimeout(timer); + } + const out: Record = { v: 1, doc: name }; + const health: Record = {}; + for (const n of names) { + const s = section(n); + if (this.stale(s)) void this.refresh(n); + out[n] = s.data; + health[n] = { ok: s.ok, error: s.error }; + } + out.health = health; + if (name === "core") out.acts = this.acts; + // The tag covers the content and not the times it was read, so a + // document that has not changed costs the phone nothing. The read + // times travel beside it. + const etag = `"${createHash("sha1").update(JSON.stringify(out)).digest("base64url")}"`; + const now = this.now(); + const overdue = names + .map((n) => section(n)) + .filter((s) => s.goodAt > 0) + .map((s) => Math.max(0, now - s.goodAt - s.ttlMs)); + const asOf = now - Math.max(0, ...overdue); + out.read = Object.fromEntries(names.map((n) => [n, section(n).at ? new Date(section(n).at).toISOString() : null])); + return { etag, body: JSON.stringify(out), asOf }; + } +} diff --git a/pm-stack/console/src/notify.ts b/pm-stack/console/src/notify.ts new file mode 100644 index 0000000000..0a42981d6b --- /dev/null +++ b/pm-stack/console/src/notify.ts @@ -0,0 +1,163 @@ +// What is worth interrupting the owner for, and only once each. +// +// The state documents say how things stand; this compares them with what +// he has already been told and sends the difference: the fleet answered +// one of his prompts, something new needs his hands, new questions +// arrived, a unit failed. The first pass only takes stock, so turning +// notifications on never sets off a flood about things already there. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import type { Docs } from "./docs.ts"; +import type { Class, Push } from "./push.ts"; + +export interface Seen { + primed: boolean; + /** issue number -> time of the last fleet reply already announced */ + asks: Record; + hands: string[]; + questions: number; + failed: string[]; +} +export const NOTHING_SEEN: Seen = { primed: false, asks: {}, hands: [], questions: 0, failed: [] }; + +export interface Message { + cls: Class; + title: string; + body: string; + url: string; + tag: string; +} + +interface State { + asks?: { issue: number; replies: { you: boolean; at: string; text: string }[] }[] | null; + census?: { hands: { ref: string; title: string; action?: string }[] } | null; + sessions?: { waiting: { id: string; title: string }[] } | null; + questionCount?: { total: number } | null; + services?: { unit: string; active: string }[] | null; +} + +const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s); + +/** The messages owed for `now`, and what will have been seen once they + * are sent. A section that could not be read (null) changes nothing. */ +export function changes(seen: Seen, now: State): { messages: Message[]; seen: Seen } { + const next: Seen = { + primed: true, + asks: { ...seen.asks }, + hands: seen.hands, + questions: seen.questions, + failed: seen.failed, + }; + const messages: Message[] = []; + for (const ask of now.asks ?? []) { + const last = ask.replies[ask.replies.length - 1]; + if (!last || last.you || next.asks[ask.issue] === last.at) continue; + next.asks[ask.issue] = last.at; + messages.push({ + cls: "replies", + title: `The fleet replied on #${ask.issue}`, + body: clip(last.text, 180), + url: "/console/#ask", + tag: `ask-${ask.issue}`, + }); + } + if (now.census || now.sessions) { + const hands = [ + ...(now.census?.hands ?? []).map((i) => ({ key: i.ref, text: i.action || i.title })), + ...(now.sessions?.waiting ?? []).map((w) => ({ key: `session:${w.id}`, text: w.title })), + ]; + for (const item of hands) { + if (seen.hands.includes(item.key)) continue; + messages.push({ + cls: "needs", + title: "Something needs you", + body: clip(item.text, 180), + url: "/console/#needs/hands", + tag: `hands-${item.key}`, + }); + } + next.hands = hands.map((i) => i.key); + } + if (now.questionCount) { + const total = now.questionCount.total; + if (total > seen.questions) { + const more = total - seen.questions; + messages.push({ + cls: "questions", + title: more === 1 ? "1 new question for you" : `${more} new questions for you`, + body: `${total} open in all.`, + url: "/console/#needs/questions", + tag: "questions", + }); + } + next.questions = total; + } + if (now.services) { + const failed = now.services.filter((u) => u.active === "failed").map((u) => u.unit); + for (const unit of failed) { + if (seen.failed.includes(unit)) continue; + messages.push({ + cls: "trouble", + title: "A unit failed", + body: unit, + url: "/console/#more/services", + tag: `unit-${unit}`, + }); + } + next.failed = failed; + } + return { messages: seen.primed ? messages : [], seen: next }; +} + +/** Sections the notifier reads, whether or not anyone is looking. */ +const WATCHED = ["asks", "census", "sessions", "questionCount", "services"]; + +export class Notifier { + private seen: Seen | null = null; + private timer: ReturnType | null = null; + private busy = false; + + constructor( + private docs: Docs, + private push: Push, + private file: string, + ) {} + + private async load(): Promise { + if (this.seen) return this.seen; + try { + this.seen = { ...NOTHING_SEEN, ...(JSON.parse(await readFile(this.file, "utf8")) as Seen) }; + } catch { + this.seen = NOTHING_SEEN; + } + return this.seen; + } + + /** One pass. Does nothing while no device is subscribed. */ + async tick(): Promise { + if (this.busy) return 0; + this.busy = true; + try { + if ((await this.push.status()).devices === 0) return 0; + await this.docs.touch(WATCHED); + const now = Object.fromEntries(WATCHED.map((n) => [n, this.docs.good(n)])) as State; + const { messages, seen } = changes(await this.load(), now); + for (const m of messages) await this.push.send(m.cls, m); + this.seen = seen; + await mkdir(dirname(this.file), { recursive: true, mode: 0o700 }); + const tmp = `${this.file}.tmp-${process.pid}`; + await writeFile(tmp, JSON.stringify(seen), { mode: 0o600 }); + await rename(tmp, this.file); + return messages.length; + } finally { + this.busy = false; + } + } + + start(everyMs = 60_000): void { + this.timer ??= setInterval( + () => void this.tick().catch((e) => console.error(`pm-console: notify: ${e.message}`)), + everyMs, + ); + } +} diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts index 29a2a06607..59751a99cb 100644 --- a/pm-stack/console/src/ops.ts +++ b/pm-stack/console/src/ops.ts @@ -17,8 +17,11 @@ export interface RunResult { export type Run = (argv: string[], opts?: { stdin?: string; timeoutMs?: number }) => Promise; export type Fetch = ( url: string, - init: { method: string; headers: Record; body: string }, + init: { method: string; headers: Record; body?: string; signal?: AbortSignal }, ) => Promise<{ ok: boolean; status: number; json(): Promise }>; +export type Row = Record; +/** Queue priorities, most urgent first (the queue's design scale). */ +export const PRIORITY_SCALE = [10, 20, 30, 40, 50, 70, 90] as const; export class OpError extends Error { constructor( @@ -171,12 +174,12 @@ export class Ops { private queueToken: string | null = null; constructor( - private cfg: Config, - private run: Run = realRun, - private fetchImpl: Fetch = fetch as unknown as Fetch, + readonly cfg: Config, + readonly run: Run = realRun, + readonly fetchImpl: Fetch = fetch as unknown as Fetch, ) {} - private async must(argv: string[], opts?: { stdin?: string; timeoutMs?: number }): Promise { + async must(argv: string[], opts?: { stdin?: string; timeoutMs?: number }): Promise { const r = await this.run(argv, opts); if (r.code !== 0) { const detail = (r.stderr || r.stdout).trim().split("\n").slice(-3).join(" ").slice(0, 400); @@ -185,7 +188,7 @@ export class Ops { return r.stdout; } - private async gh(args: string[], body?: unknown): Promise { + async gh(args: string[], body?: unknown): Promise { const argv = [this.cfg.fleetBin, "gh", "api", ...args]; const out = await this.must( body === undefined ? argv : [...argv, "--input", "-"], @@ -196,19 +199,19 @@ export class Ops { // ---- queue ----------------------------------------------------------- - private async sql(statement: string, args: (string | number)[]): Promise[]> { - if (!/^\s*select\b/i.test(statement)) throw new Error("the console only reads the queue store"); + /** One request to the queue store carrying `statements` in order. */ + private async pipeline(statements: { sql: string; args: (string | number)[] }[]) { const body = { requests: [ - { + ...statements.map((st) => ({ type: "execute", stmt: { - sql: statement, - args: args.map((a) => + sql: st.sql, + args: st.args.map((a) => typeof a === "number" ? { type: "integer", value: String(a) } : { type: "text", value: a }, ), }, - }, + })), { type: "close" }, ], }; @@ -229,17 +232,60 @@ export class Ops { res = await ask(); } if (!res.ok) throw new OpError(502, `queue store answered http ${res.status}`); - const first = ( - (await res.json()) as { - results?: { - type?: string; - response?: { result?: { cols: { name: string }[]; rows: { value?: string | number | null }[][] } }; - }[]; - } - ).results?.[0]; - const result = first?.type === "ok" ? first.response?.result : undefined; - if (!result) throw new OpError(502, "queue store refused the query"); - return result.rows.map((row) => Object.fromEntries(result.cols.map((c, i) => [c.name, row[i]?.value ?? null]))); + const results = + ( + (await res.json()) as { + results?: { + type?: string; + response?: { + result?: { + cols: { name: string }[]; + rows: { value?: string | number | null }[][]; + affected_row_count?: number; + }; + }; + }[]; + } + ).results ?? []; + return statements.map((_, i) => { + const result = results[i]?.type === "ok" ? results[i].response?.result : undefined; + if (!result) throw new OpError(502, "queue store refused the query"); + return result; + }); + } + + /** Several reads in one round trip. Reads only: anything else throws. */ + async reads(statements: { sql: string; args: (string | number)[] }[]): Promise { + for (const st of statements) { + if (!/^\s*select\b/i.test(st.sql)) throw new Error("the console only reads the queue store"); + } + return (await this.pipeline(statements)).map((result) => + result.rows.map((row) => Object.fromEntries(result.cols.map((c, i) => [c.name, row[i]?.value ?? null]))), + ); + } + + async sql(statement: string, args: (string | number)[]): Promise { + return (await this.reads([{ sql: statement, args }]))[0]; + } + + /** + * Move a queued task along the priority scale. The one write this + * service makes to the queue store, because the queue has no verb for + * it: one column, on one row, and only while the task is still queued. + */ + async setTaskPriority(task: unknown, priority: unknown) { + const t = id(task, "task"); + if (!PRIORITY_SCALE.includes(priority as (typeof PRIORITY_SCALE)[number])) { + throw new OpError(400, `priority: one of ${PRIORITY_SCALE.join(", ")}`); + } + const [result] = await this.pipeline([ + { + sql: "UPDATE tasks SET priority = ? WHERE id = ? AND queue = ? AND status = 'queued'", + args: [priority as number, t, this.cfg.queue], + }, + ]); + if (!result.affected_row_count) throw new OpError(409, `task ${t} is not queued, so its place cannot change`); + return { task: t, priority }; } async queueCounts(): Promise> { @@ -352,6 +398,19 @@ export class Ops { return { issue: n, url: made.html_url }; } + /** Hand one packet to the queue. `fleet queue enqueue` reads a packet + * file, not stdin, so the packet lives in a private file for the call. */ + async enqueue(packet: unknown): Promise { + const dir = mkdtempSync(join(tmpdir(), "pm-console-")); + const file = join(dir, "packet.json"); + try { + writeFileSync(file, JSON.stringify(packet), { mode: 0o600 }); + return await this.run([this.cfg.fleetBin, "queue", "enqueue", file, "--queue", this.cfg.queue]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + } + /** * File an idea as an issue and enqueue its triage task in the same * pass (doc/agents/one-queue-claiming-work.md): an issue with no queue @@ -376,16 +435,7 @@ export class Ops { rank as Rank, new Date().toISOString(), ); - // `fleet queue enqueue` reads a packet file, not stdin. - const dir = mkdtempSync(join(tmpdir(), "pm-console-")); - const file = join(dir, "packet.json"); - let queued: RunResult; - try { - writeFileSync(file, JSON.stringify(packet), { mode: 0o600 }); - queued = await this.run([this.cfg.fleetBin, "queue", "enqueue", file, "--queue", this.cfg.queue]); - } finally { - rmSync(dir, { recursive: true, force: true }); - } + const queued = await this.enqueue(packet); return { issue: made.number, url: made.html_url, diff --git a/pm-stack/console/src/push.ts b/pm-stack/console/src/push.ts new file mode 100644 index 0000000000..3686f318b8 --- /dev/null +++ b/pm-stack/console/src/push.ts @@ -0,0 +1,247 @@ +// Web Push, with nothing but the platform's own cryptography. +// +// A notification reaches the phone through the browser vendor's push +// service. The message is encrypted for the one browser that subscribed +// (RFC 8291, aes128gcm), and the request is signed with this server's +// own key pair so the push service knows who is sending (RFC 8292, +// VAPID). The key pair is made here on first use and kept in this +// service's state directory; nobody ever handles it. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; + +const enc = new TextEncoder(); +const b64u = (bytes: Uint8Array | ArrayBuffer) => Buffer.from(bytes as ArrayBuffer).toString("base64url"); +const unb64u = (text: string) => new Uint8Array(Buffer.from(text, "base64url")); +const concat = (...parts: Uint8Array[]) => { + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let at = 0; + for (const p of parts) { + out.set(p, at); + at += p.length; + } + return out; +}; + +/** Push services a subscription may name. This server posts to the + * endpoint a browser gives it, so the endpoint has to be one of these. */ +const PUSH_HOSTS = [ + /^fcm\.googleapis\.com$/, + /^([a-z0-9-]+\.)*push\.services\.mozilla\.com$/, + /^([a-z0-9-]+\.)*notify\.windows\.com$/, + /^([a-z0-9-]+\.)*push\.apple\.com$/, +]; + +export interface Subscription { + endpoint: string; + keys: { p256dh: string; auth: string }; + at?: string; + label?: string; +} + +/** Notification classes the owner can switch off one by one. */ +export const CLASSES = ["replies", "needs", "questions", "trouble"] as const; +export type Class = (typeof CLASSES)[number]; + +interface PushFile { + vapid: { publicKey: string; privateJwk: JsonWebKey } | null; + subscriptions: Subscription[]; + off: Class[]; +} + +export function validSubscription(value: unknown): Subscription | null { + const v = value as { endpoint?: unknown; keys?: { p256dh?: unknown; auth?: unknown } } | null; + if (!v || typeof v.endpoint !== "string" || typeof v.keys?.p256dh !== "string" || typeof v.keys?.auth !== "string") { + return null; + } + let url: URL; + try { + url = new URL(v.endpoint); + } catch { + return null; + } + if (url.protocol !== "https:" || url.username || url.password || !PUSH_HOSTS.some((h) => h.test(url.hostname))) { + return null; + } + // An uncompressed P-256 point is 65 bytes; the auth secret is 16. + if (unb64u(v.keys.p256dh).length !== 65 || unb64u(v.keys.auth).length !== 16) return null; + return { endpoint: url.href, keys: { p256dh: v.keys.p256dh, auth: v.keys.auth } }; +} + +async function hkdf(salt: Uint8Array, ikm: Uint8Array, info: Uint8Array, length: number): Promise { + const key = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]); + return new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info }, key, length * 8)); +} + +/** Encrypt one message for one subscription (RFC 8291). */ +export async function encrypt(sub: Subscription, plaintext: Uint8Array): Promise { + const uaPublic = unb64u(sub.keys.p256dh); + const authSecret = unb64u(sub.keys.auth); + const local = (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [ + "deriveBits", + ])) as CryptoKeyPair; + const localPublic = new Uint8Array(await crypto.subtle.exportKey("raw", local.publicKey)); + const peer = await crypto.subtle.importKey("raw", uaPublic, { name: "ECDH", namedCurve: "P-256" }, false, []); + const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: peer }, local.privateKey, 256)); + const ikm = await hkdf(authSecret, shared, concat(enc.encode("WebPush: info\0"), uaPublic, localPublic), 32); + const salt = crypto.getRandomValues(new Uint8Array(16)); + const cek = await hkdf(salt, ikm, enc.encode("Content-Encoding: aes128gcm\0"), 16); + const nonce = await hkdf(salt, ikm, enc.encode("Content-Encoding: nonce\0"), 12); + const key = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); + // One record: the message, then the delimiter that marks the last record. + const sealed = new Uint8Array( + await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, key, concat(plaintext, new Uint8Array([2]))), + ); + const header = new Uint8Array(16 + 4 + 1 + localPublic.length); + header.set(salt, 0); + new DataView(header.buffer).setUint32(16, 4096); + header[20] = localPublic.length; + header.set(localPublic, 21); + return concat(header, sealed); +} + +type Poster = ( + url: string, + init: { method: string; headers: Record; body: Uint8Array; signal?: AbortSignal }, +) => Promise<{ status: number }>; + +export class Push { + private state: PushFile | null = null; + private signer: CryptoKey | null = null; + + constructor( + private file: string, + private subject: string, + private post: Poster = (url, init) => fetch(url, init as RequestInit), + private now: () => number = Date.now, + ) {} + + private async load(): Promise { + if (this.state) return this.state; + try { + this.state = JSON.parse(await readFile(this.file, "utf8")) as PushFile; + } catch { + this.state = { vapid: null, subscriptions: [], off: [] }; + } + if (!this.state.vapid) { + const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [ + "sign", + "verify", + ])) as CryptoKeyPair; + this.state.vapid = { + publicKey: b64u(await crypto.subtle.exportKey("raw", pair.publicKey)), + privateJwk: await crypto.subtle.exportKey("jwk", pair.privateKey), + }; + await this.save(); + } + return this.state; + } + + private async save(): Promise { + if (!this.state) return; + await mkdir(dirname(this.file), { recursive: true, mode: 0o700 }); + const tmp = `${this.file}.tmp-${process.pid}`; + await writeFile(tmp, JSON.stringify(this.state), { mode: 0o600 }); + await rename(tmp, this.file); + } + + /** What the page needs to subscribe, and what is switched on. */ + async status() { + const s = await this.load(); + return { + key: s.vapid?.publicKey ?? "", + devices: s.subscriptions.length, + classes: Object.fromEntries(CLASSES.map((c) => [c, !s.off.includes(c)])), + }; + } + + async subscribe(value: unknown, label: unknown) { + const sub = validSubscription(value); + if (!sub) throw new Error("subscription: not a push subscription from a known push service"); + const s = await this.load(); + s.subscriptions = [ + ...s.subscriptions.filter((x) => x.endpoint !== sub.endpoint), + { ...sub, at: new Date(this.now()).toISOString(), label: typeof label === "string" ? label.slice(0, 80) : "" }, + ].slice(-20); + await this.save(); + return { devices: s.subscriptions.length }; + } + + async unsubscribe(endpoint: unknown) { + const s = await this.load(); + const before = s.subscriptions.length; + s.subscriptions = s.subscriptions.filter((x) => x.endpoint !== endpoint); + if (s.subscriptions.length !== before) await this.save(); + return { devices: s.subscriptions.length }; + } + + async setClass(cls: unknown, on: unknown) { + if (!CLASSES.includes(cls as Class)) throw new Error(`class: one of ${CLASSES.join(", ")}`); + const s = await this.load(); + s.off = s.off.filter((c) => c !== cls); + if (on !== true) s.off.push(cls as Class); + await this.save(); + return (await this.status()).classes; + } + + private async vapid(endpoint: string): Promise { + const s = await this.load(); + const v = s.vapid as NonNullable; + this.signer ??= await crypto.subtle.importKey("jwk", v.privateJwk, { name: "ECDSA", namedCurve: "P-256" }, false, [ + "sign", + ]); + const head = b64u(enc.encode(JSON.stringify({ typ: "JWT", alg: "ES256" }))); + const body = b64u( + enc.encode( + JSON.stringify({ + aud: new URL(endpoint).origin, + exp: Math.floor(this.now() / 1000) + 12 * 3600, + sub: this.subject, + }), + ), + ); + const sig = await crypto.subtle.sign( + { name: "ECDSA", hash: "SHA-256" }, + this.signer, + enc.encode(`${head}.${body}`), + ); + return `vapid t=${head}.${body}.${b64u(sig)}, k=${v.publicKey}`; + } + + /** Send one notification to every subscribed device, unless its class + * is switched off. A subscription the push service says is gone is + * forgotten. Returns how many devices took it. */ + async send(cls: Class | "test", message: { title: string; body: string; url: string; tag?: string }) { + const s = await this.load(); + if (cls !== "test" && s.off.includes(cls)) return { sent: 0, gone: 0, failed: 0 }; + const payload = enc.encode(JSON.stringify({ ...message, class: cls })); + let sent = 0; + let failed = 0; + const gone: string[] = []; + for (const sub of s.subscriptions) { + try { + const res = await this.post(sub.endpoint, { + method: "POST", + headers: { + Authorization: await this.vapid(sub.endpoint), + "Content-Encoding": "aes128gcm", + "Content-Type": "application/octet-stream", + TTL: "86400", + Urgency: "high", + }, + body: await encrypt(sub, payload), + signal: AbortSignal.timeout(15_000), + }); + if (res.status === 404 || res.status === 410) gone.push(sub.endpoint); + else if (res.status >= 200 && res.status < 300) sent++; + else failed++; + } catch { + failed++; + } + } + if (gone.length) { + s.subscriptions = s.subscriptions.filter((x) => !gone.includes(x.endpoint)); + await this.save(); + } + return { sent, gone: gone.length, failed }; + } +} diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index a6fef3e7a3..3270bd6651 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -10,9 +10,14 @@ import { mkdirSync, readFileSync } from "node:fs"; import { appendFile } from "node:fs/promises"; import { dirname, join } from "node:path"; +import { actions, perform } from "./actions.ts"; import { AuthError, type Identity, identify } from "./auth.ts"; import { type Config, readConfig } from "./config.ts"; +import { DOC_NAMES, type DocName, Docs } from "./docs.ts"; +import { Notifier } from "./notify.ts"; import { OpError, Ops } from "./ops.ts"; +import { Push } from "./push.ts"; +import { Work } from "./work.ts"; const BASE = "/console"; const PUBLIC_DIR = join(import.meta.dir, "..", "public"); @@ -20,7 +25,32 @@ const STATIC = new Map([ ["app.js", "text/javascript; charset=utf-8"], ["app.css", "text/css; charset=utf-8"], ["icon.svg", "image/svg+xml"], + ["sw.js", "text/javascript; charset=utf-8"], ]); + +/** The install manifest of the app at this origin. The home-screen icon + * opens the app, and a long press offers its four primary screens. */ +const MANIFEST = { + name: "PM", + short_name: "PM", + description: "What the fleet is doing, what is next, what needs you, and a place to say what you want.", + start_url: "/console/", + scope: "/", + display: "standalone", + background_color: "#0b0f14", + theme_color: "#11161d", + icons: [ + { src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" }, + { src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" }, + { src: "/icons/icon-maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" }, + ], + shortcuts: [ + { name: "Ask the fleet", short_name: "Ask", url: "/console/#ask" }, + { name: "Needs me", short_name: "Needs me", url: "/console/#needs" }, + { name: "In progress", short_name: "Now", url: "/console/#now" }, + { name: "Queued next", short_name: "Next", url: "/console/#next" }, + ], +}; const APK_NAME = "pm-console.apk"; const SECURITY = { "Content-Security-Policy": @@ -30,8 +60,7 @@ const SECURITY = { }; /** The dashboard's files that are public, matched against the parsed * path in full. They say nothing about the fleet. */ -const PUBLIC_DASHBOARD = - /^\/(manifest\.webmanifest|icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png)$/; +const PUBLIC_DASHBOARD = /^\/icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png$/; /** Headers that belong to one connection, not to the request or response. */ const HOP_BY_HOP = new Set([ "connection", @@ -95,6 +124,27 @@ export interface Deps { audit: (entry: Record) => Promise; /** Reaches the dashboard. Injected so tests can stand in for it. */ upstream?: (url: string, init: RequestInit) => Promise; + /** The interface's state, kept ready, and the actions it can take. */ + docs?: Docs; + actions?: ReturnType; + work?: Work; + push?: Push; +} + +/** Text that shrinks well. The dashboard's fragments run to a megabyte + * each, and the link to a phone is the slow part. */ +const COMPRESSIBLE = /^(text\/|application\/(json|javascript|manifest\+json|xml)|image\/svg\+xml)/; +const COMPRESS_FROM_BYTES = 1024; + +function wantsGzip(req: Request): boolean { + return /\bgzip\b/.test(req.headers.get("accept-encoding") ?? ""); +} + +function gzipped(req: Request, bytes: Uint8Array, headers: Headers): Response | null { + if (!wantsGzip(req) || bytes.byteLength < COMPRESS_FROM_BYTES) return null; + headers.set("content-encoding", "gzip"); + headers.append("vary", "accept-encoding"); + return new Response(Bun.gzipSync(bytes), { headers }); } /** A write must come from this site. A browser sends Origin on every @@ -155,6 +205,15 @@ async function toDashboard(req: Request, url: URL, deps: Deps, open: boolean): P for (const [name, value] of res.headers) { if (!HOP_BY_HOP.has(name) && name !== "content-length" && name !== "content-encoding") out.append(name, value); } + // A page or a fragment is finite: read it and send it compressed. An + // event stream that stays open (anything but a fragment) is passed + // through as it comes, since compressing would hold its events back. + const type = res.headers.get("content-type") ?? ""; + const finite = type.startsWith("text/event-stream") ? url.pathname.startsWith("/frag/") : COMPRESSIBLE.test(type); + if (req.method !== "HEAD" && res.status === 200 && finite && wantsGzip(req)) { + const bytes = new Uint8Array(await res.arrayBuffer()); + return gzipped(req, bytes, out) ?? new Response(bytes, { status: res.status, headers: out }); + } return new Response(req.method === "HEAD" ? null : res.body, { status: res.status, headers: out }); } @@ -179,6 +238,11 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul // Public, unauthenticated: nothing here says anything about the fleet. if (path === "/.well-known/assetlinks.json" && method === "GET") return json(assetLinks(deps.cfg)); if (path === `${BASE}/health` && method === "GET") return json({ ok: true }); + if (path === "/manifest.webmanifest" && method === "GET") { + return new Response(JSON.stringify(MANIFEST), { + headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-cache", ...SECURITY }, + }); + } const ours = path === BASE || path.startsWith(`${BASE}/`); if (!ours) { if (deps.cfg.dashboardUrl === null) return json({ error: "not found" }, 404); @@ -195,6 +259,9 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul } if (!ours) { if (crossSiteWrite(req)) return json({ error: "this request did not come from this site" }, 403); + // The front door is the app. The dashboard's own home stays one + // link away, under More, at /?dashboard. + if (method === "GET" && path === "/" && url.search === "") return Response.redirect(`${BASE}/`, 302); return toDashboard(req, url, deps, false); } @@ -259,6 +326,22 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul return json(await ops.prs()); } } + if (seg.length === 2 && seg[0] === "doc" && deps.docs && DOC_NAMES.includes(seg[1] as DocName)) { + const doc = await deps.docs.doc(seg[1] as DocName); + const headers = new Headers({ + "Content-Type": "application/json; charset=utf-8", + "Cache-Control": "no-cache", + ETag: doc.etag, + "X-As-Of": String(doc.asOf), + ...SECURITY, + }); + if (req.headers.get("if-none-match") === doc.etag) return new Response(null, { status: 304, headers }); + return gzipped(req, new TextEncoder().encode(doc.body), headers) ?? new Response(doc.body, { headers }); + } + if (seg.length === 1 && seg[0] === "push" && deps.push) return json(await deps.push.status()); + if (seg.length === 1 && seg[0] === "question" && deps.work) { + return json(await deps.work.question(query.get("set"), query.get("ledger"), query.get("qid"))); + } if (seg.length === 2 && seg[0] === "prs") return json(await ops.pr(seg[1])); if (seg.length === 3 && seg[0] === "services" && seg[2] === "logs") { return json(await ops.serviceLogs(seg[1], query.get("lines"))); @@ -315,6 +398,33 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul } }; + if (seg.length === 1 && seg[0] === "act" && deps.docs && deps.actions) { + const { docs, actions: table } = deps; + const kind = typeof body.kind === "string" ? body.kind : ""; + const args = body.args ?? {}; + const kept = + Object.hasOwn(table, kind) && args !== null && typeof args === "object" + ? table[kind].audit(args as Record) + : {}; + const entry = { + id: crypto.randomUUID(), + kind, + at: new Date().toISOString(), + by: who.email ?? who.certName ?? who.sub ?? who.via, + note: "", + }; + return await act(kind || "unknown", kept, async () => { + docs.logAct({ ...entry, status: "running" }); + try { + const result = await perform(table, docs, kind, args); + docs.logAct({ ...entry, status: "done" }); + return result; + } catch (error) { + docs.logAct({ ...entry, status: "failed", note: (error as Error).message.slice(0, 200) }); + throw error; + } + }); + } if (seg.length === 3 && seg[0] === "queue") { return await act(`queue.${seg[2]}`, { task: seg[1], reason: body.reason }, () => ops.queueAct(seg[2], seg[1], body.reason), @@ -350,13 +460,75 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul } } +/** How often each source is read again while someone is looking. */ +export function loaders( + ops: Ops, + work: Work, + more: unknown, +): Record Promise }> { + return { + board: { ttlMs: 10_000, load: () => work.board() }, + sessions: { ttlMs: 20_000, load: () => work.sessions() }, + census: { ttlMs: 60_000, load: () => work.census() }, + asks: { ttlMs: 20_000, load: () => work.asks() }, + questionCount: { + ttlMs: 15_000, + load: async () => { + const q = await work.questions(); + return { total: q.total, sets: q.sets }; + }, + }, + questions: { ttlMs: 15_000, load: () => work.questions() }, + prs: { ttlMs: 45_000, load: () => ops.prs() }, + priorities: { ttlMs: 120_000, load: () => ops.priorities() }, + agents: { ttlMs: 30_000, load: () => ops.agents() }, + services: { ttlMs: 20_000, load: () => ops.services() }, + more: { ttlMs: 3_600_000, load: async () => more }, + }; +} + +/** The dashboard's own pages, grouped as it groups them, for the list + * under More. Read from the dashboard's manifest beside this package; + * if that is not there, the list is simply empty. */ +export async function morePages(): Promise< + { group: string; pages: { title: string; route: string; blurb: string }[] }[] +> { + try { + const manifest = (await import("../../aggregator/src/pages.ts")) as { + PAGE_GROUPS: { id: string; title: string }[]; + PAGES: { title: string; route: string; blurb: string; group: string }[]; + }; + return manifest.PAGE_GROUPS.map((g) => ({ + group: g.title, + pages: manifest.PAGES.filter((pg) => pg.group === g.id).map((pg) => ({ + title: pg.title, + // The dashboard's home is at /, which is now the app's front door. + route: pg.route === "/" ? "/?dashboard" : pg.route, + blurb: pg.blurb, + })), + })).filter((g) => g.pages.length > 0); + } catch { + return []; + } +} + if (import.meta.main) { const cfg = readConfig(); const ops = new Ops(cfg); mkdirSync(dirname(cfg.auditFile), { recursive: true, mode: 0o700 }); + const work = new Work(ops); + const docs = new Docs(loaders(ops, work, await morePages())); + docs.start(); + const state = dirname(cfg.auditFile); + const push = new Push(join(state, "push.json"), `mailto:${cfg.owners[0] ?? "owner@invalid.example"}`); + new Notifier(docs, push, join(state, "notified.json")).start(); const deps: Deps = { cfg, ops, + docs, + work, + push, + actions: actions(ops, work, push), identify: (req, peer) => identify(req, cfg, { peer }), audit: (entry) => appendFile(cfg.auditFile, `${JSON.stringify(entry)}\n`, { mode: 0o600 }), }; diff --git a/pm-stack/console/src/work.ts b/pm-stack/console/src/work.ts new file mode 100644 index 0000000000..a679676914 --- /dev/null +++ b/pm-stack/console/src/work.ts @@ -0,0 +1,597 @@ +// What the owner looks at first: the work in progress, what comes next, +// what is waiting on him, and what he has asked for. +// +// Reads come from the queue store, the dashboard's own data and GitHub. +// Every write is something the fleet already understands: an answer to a +// decision set through the dashboard's own endpoint, an issue and a +// queue task, a comment, a label. +import { readFile } from "node:fs/promises"; +import { OpError, type Ops, PRIORITY_SCALE, type Row } from "./ops.ts"; + +const P = "CASE WHEN json_valid(payload) THEN payload ELSE '{}' END"; +const G = "CASE WHEN json_valid(progress) THEN progress ELSE '{}' END"; +const TASK_COLS = `id, title, priority, status, attempts, + substr(coalesce(claimed_at,''),1,19) AS claimed, substr(coalesce(lease_until,''),1,19) AS lease, + substr(created_at,1,19) AS created, worker_id AS worker, lane_id AS lane, claim_model AS model, + json_extract(${P},'$.kind') AS kind, json_extract(${P},'$.issue.number') AS issue, + json_extract(${P},'$.pr.number') AS pr, + substr(coalesce(json_extract(${G},'$.next'), json_extract(${G},'$.last_checkpoint.progress'), + json_extract(${G},'$.last_checkpoint.stage'), ''),1,400) AS step, + substr(coalesce(json_extract(${P},'$.acceptance[0]'),''),1,300) AS goal`; + +const OWNER_PROMPT_MARK = ""; +const OWNER_REPLY_MARK = ""; +const ASK_NOTE = + "This is an instruction from the owner, in his own words, sent from the PM console. Work out what he wants and do it with the fleet's own verbs; if it is a question, answer it here. Say on this issue what you did, with links, and close it when nothing is left."; +const SET_ID = /^[A-Za-z0-9._:-]{1,160}$/; +const REF = /^([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)#([1-9][0-9]{0,8})$/; +const LEANS = ["none", "skeptical", "approve"] as const; + +function clip(value: unknown, max: number): string { + const s = typeof value === "string" ? value : ""; + return s.length > max ? `${s.slice(0, max - 1)}…` : s; +} + +function words(value: unknown, name: string, max: number): string { + if (typeof value !== "string" || value.trim() === "") throw new OpError(400, `${name}: required`); + if (value.length > max) throw new OpError(400, `${name}: at most ${max} characters`); + return value.trim(); +} + +export interface DecisionOption { + id: string; + label: string; + tags?: string[]; +} +interface DecisionQuestion { + qid: string; + question: string; + context?: string; + description?: string; + mode?: string; + order?: number; + recommendedOptionIds?: string[]; + options: DecisionOption[]; + resolution?: unknown; +} +interface DecisionItem { + ledgerId: string; + title: string; + order?: number; + group?: string; + links?: string[]; + questions: DecisionQuestion[]; +} +interface DecisionSet { + setId: string; + title: string; + token: string; + createdAt: string; + items: DecisionItem[]; +} +export interface Submission { + ledgerId: string; + qid: string; + kind: "answered" | "deferred"; + optionId?: string; + optionIds?: string[]; + freeText?: string; + comment?: string; + lean?: (typeof LEANS)[number]; +} + +/** The task that carries out an owner prompt. Top band: the owner asked. + * It takes the issue's triage key, the one key the queue has for "someone + * must look at this issue", so an issue never has two tasks: a reply on a + * prompt whose task is still live joins it, and one whose task has + * finished gets a new one. */ +export function promptPacket(repo: string, queue: string, number: number, text: string, at: string) { + const url = `https://github.com/${repo}/issues/${number}`; + const first = text.split("\n")[0].trim(); + return { + title: `Owner prompt ${repo}#${number}: ${first}`.slice(0, 180), + body: `Instruction from the owner, sent from the PM console: ${url}`, + priority: 10, + dedupe_key: `repo-health:v1:triage:${repo}:issue:${number}`, + payload: { + schema: "repo-task/v1", + kind: "triage", + repo, + queue, + issue: { number, url, title: `Owner: ${first}`.slice(0, 120), state_checked_at: at }, + problem: + "The owner wrote this instruction in his own words from the PM console. It is not a report to classify: it is something he wants done, or a question he wants answered.", + evidence: [`Sent from the PM console at ${at}`, url], + acceptance: [ + "What the owner asked for is done with the fleet's own verbs, or answered if it is a question", + "A comment on the issue says in plain words what was done, with links, or what could not be done and why", + "The issue is closed when nothing is left; work that outlasts this task is filed, enqueued and linked from the issue", + ], + tests: ["The issue carries the report comment and is closed, or carries the reason it is still open"], + scope: { + include: [`Carry out the owner's instruction on ${repo}#${number}`], + exclude: ["Secrets, credentials or purchases"], + }, + risk: { level: "low", flags: ["owner-prompt"] }, + priority_reason: "Owner prompt from the console: top band (10).", + timebox_minutes: 45, + max_attempts: 1000, + context_refs: [url], + dedupe: { checked_at: at, basis: "Created with its issue, or with the owner's reply, in the same pass." }, + }, + }; +} + +export class Work { + private labelReady = false; + private replies = new Map(); + + constructor( + private ops: Ops, + private read: (path: string) => Promise = (path) => readFile(path, "utf8"), + private clock: () => Date = () => new Date(), + ) {} + + private get repo() { + return this.ops.cfg.repo; + } + + private task = (r: Row) => ({ + ...r, + url: r.issue ? `https://github.com/${this.repo}/issues/${r.issue}` : null, + }); + + /** In progress and next, in the order the queue will hand work out. */ + async board() { + const q = this.ops.cfg.queue; + const [counts, now, next, why] = await this.ops.reads([ + { + sql: "SELECT status, count(*) AS n FROM tasks WHERE queue = ? AND status IN ('queued','claimed','blocked','parked') GROUP BY status", + args: [q], + }, + { + sql: `SELECT ${TASK_COLS} FROM tasks WHERE queue = ? AND status = 'claimed' ORDER BY claimed_at DESC, id DESC LIMIT 60`, + args: [q], + }, + { + sql: `SELECT ${TASK_COLS} FROM tasks WHERE queue = ? AND status = 'queued' ORDER BY (priority IS NULL), priority ASC, created_at ASC, id ASC LIMIT 60`, + args: [q], + }, + { + sql: `SELECT substr(coalesce(json_extract(${G},'$.reason'), json_extract(${G},'$.blocker'), ready_condition, blocked_deps, 'no reason recorded'),1,140) AS why, count(*) AS n FROM tasks WHERE queue = ? AND status = 'blocked' GROUP BY 1 ORDER BY n DESC LIMIT 6`, + args: [q], + }, + ]); + return { + counts: Object.fromEntries(counts.map((r) => [String(r.status), Number(r.n)])), + now: now.map(this.task), + next: next.map(this.task), + blockedWhy: why, + }; + } + + private async dash(path: string, body?: unknown): Promise { + const base = this.ops.cfg.dashboardUrl; + if (base === null) throw new OpError(502, "no dashboard is configured"); + const res = await this.ops.fetchImpl(`${base}${path}`, { + method: body === undefined ? "GET" : "POST", + headers: { accept: "application/json", ...(body === undefined ? {} : { "content-type": "application/json" }) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + signal: AbortSignal.timeout(20_000), + }); + const data = await res.json().catch(() => null); + if (!res.ok) { + const why = (data as { error?: string } | null)?.error ?? `http ${res.status}`; + throw new OpError( + res.status === 400 || res.status === 403 || res.status === 404 ? 400 : 502, + `dashboard: ${why}`, + ); + } + return data; + } + + /** Agent sessions that are moving, and what the dashboard's own tiers + * say is waiting on the owner. */ + async sessions() { + const all = (await this.dash("/api/attention.json")) as Record[]; + const moving = all + .filter((e) => e.tier === "in-motion") + .map((e) => ({ + id: clip(e.sessionId, 80), + title: clip(e.title, 160), + agent: clip(e.agent, 60), + model: clip(e.model, 60), + where: clip(e.directory, 200).split("/").slice(-2).join("/"), + last: clip(e.lastActivityAt, 30), + tools: Number(e.activeToolCalls) || 0, + messages: Number(e.messageCount) || 0, + })) + .sort((a, b) => b.last.localeCompare(a.last)); + const waiting = all + .filter((e) => e.tier === "needs-drew") + .map((e) => ({ + id: clip(e.id, 120), + title: clip(e.title, 300), + ref: clip(e.ref, 120), + why: clip(e.drewReason, 300), + })); + return { moving, waiting }; + } + + /** Issues and pull requests labelled as waiting on the owner. */ + async census() { + const data = (await this.dash("/api/needs-drew.json")) as { + fetchedAt?: string; + complete?: boolean; + items?: { + ref: string; + kind: string; + title: string; + url: string; + needsLabels: string[]; + reason: string | null; + updatedAt: string; + hands?: { kind: string; action: string | null } | null; + }[]; + }; + const base = (i: NonNullable[number]) => ({ + ref: i.ref, + title: clip(i.title, 200), + url: i.url, + pr: i.kind === "pr", + updated: clip(i.updatedAt, 19), + }); + const items = data.items ?? []; + return { + at: data.fetchedAt ?? null, + complete: data.complete !== false, + // A hands item is one action only a person can do (FDR-0013). + hands: items + .filter((i) => i.hands?.kind) + .map((i) => ({ ...base(i), kind: i.hands?.kind, action: clip(i.hands?.action, 400) })), + reviews: items.filter((i) => !i.hands?.kind && i.needsLabels.includes("user/review")).map(base), + // Escalated with no stated action: the fleet's to decide, listed so nothing is hidden. + other: items + .filter((i) => !i.hands?.kind && !i.needsLabels.includes("user/review")) + .map((i) => ({ ...base(i), why: clip(i.reason, 300) })), + }; + } + + private async sets(): Promise { + let raw: { sets?: DecisionSet[] }; + try { + raw = JSON.parse(await this.read(this.ops.cfg.decisionsFile)); + } catch (error) { + throw new OpError(502, `the questions store could not be read: ${(error as Error).message.slice(0, 120)}`); + } + return Array.isArray(raw.sets) ? raw.sets : []; + } + + /** Every open question, newest set first. The per-set tokens stay here. */ + async questions() { + const sets = (await this.sets()).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt))); + const open = []; + const byOrder = (a: { order?: number }, b: { order?: number }) => (a.order ?? 0) - (b.order ?? 0); + for (const set of sets) { + for (const item of [...(set.items ?? [])].sort(byOrder)) { + for (const q of [...(item.questions ?? [])].sort(byOrder)) { + if (q.resolution) continue; + open.push({ + set: set.setId, + setTitle: clip(set.title, 120), + created: clip(set.createdAt, 19), + ledger: item.ledgerId, + item: clip(item.title, 200), + links: (item.links ?? []).slice(0, 3), + qid: q.qid, + q: clip(q.question, 600), + // The list carries a line of background; the rest is read + // when a question is opened, so 360 questions fit a phone. + context: clip(q.context, 280), + more: (q.context ?? "").length > 280 || Boolean(q.description), + multi: q.mode === "multi", + recommended: q.recommendedOptionIds ?? [], + options: (q.options ?? []).map((o) => ({ id: o.id, label: clip(o.label, 240), tags: o.tags ?? [] })), + }); + } + } + } + return { total: open.length, sets: new Set(open.map((q) => q.set)).size, open }; + } + + /** The full background of one question, read when it is opened. */ + async question(setId: unknown, ledger: unknown, qid: unknown) { + const set = (await this.sets()).find((s) => s.setId === setId); + const q = set?.items?.find((i) => i.ledgerId === ledger)?.questions?.find((x) => x.qid === qid); + if (!q) throw new OpError(404, "that question is not in the store"); + return { context: clip(q.context, 8000), detail: clip(q.description, 8000) }; + } + + /** Answer or hand back questions through the dashboard's own endpoint, + * so everything downstream of an answer happens as it always has. */ + async submit(setId: unknown, submissions: Submission[]) { + if (typeof setId !== "string" || !SET_ID.test(setId)) throw new OpError(400, "set: not a decision set id"); + if (submissions.length === 0) throw new OpError(400, "nothing to submit"); + const set = (await this.sets()).find((s) => s.setId === setId); + if (!set) throw new OpError(404, "that decision set is not in the store"); + const out = (await this.dash(`/api/decisions/${encodeURIComponent(setId)}/submit`, { + token: set.token, + submissions, + })) as { outcomes?: { qid: string; applied: boolean; reason?: string }[] }; + const outcomes = out.outcomes ?? []; + return { + set: setId, + applied: outcomes.filter((o) => o.applied).length, + refused: outcomes.filter((o) => !o.applied).map((o) => ({ qid: o.qid, why: o.reason ?? "not applied" })), + }; + } + + async answer(args: Record) { + const sub: Submission = { + ledgerId: words(args.ledger, "ledger", 300), + qid: words(args.qid, "qid", 300), + kind: "answered", + }; + if (typeof args.option === "string" && args.option !== "") sub.optionId = words(args.option, "option", 200); + if (Array.isArray(args.options) && args.options.length > 0) { + sub.optionIds = args.options.slice(0, 20).map((o) => words(o, "options", 200)); + } + if (typeof args.text === "string" && args.text.trim() !== "") sub.freeText = words(args.text, "text", 4000); + if (typeof args.comment === "string" && args.comment.trim() !== "") + sub.comment = words(args.comment, "comment", 2000); + if (!sub.optionId && !sub.optionIds && !sub.freeText) throw new OpError(400, "choose an option or write an answer"); + return this.submit(args.set, [sub]); + } + + /** "Decide for me": hand the question back with a lean. */ + async defer(args: Record) { + const lean = args.lean === undefined ? "approve" : args.lean; + if (!LEANS.includes(lean as (typeof LEANS)[number])) throw new OpError(400, `lean: one of ${LEANS.join(", ")}`); + return this.submit(args.set, [ + { + ledgerId: words(args.ledger, "ledger", 300), + qid: words(args.qid, "qid", 300), + kind: "deferred", + lean: lean as (typeof LEANS)[number], + }, + ]); + } + + /** Take the recommended option on every open question of one set that has one. */ + async acceptRecommended(setId: unknown) { + const set = (await this.sets()).find((s) => s.setId === setId); + if (!set) throw new OpError(404, "that decision set is not in the store"); + const subs: Submission[] = []; + for (const item of set.items ?? []) { + for (const q of item.questions ?? []) { + const rec = q.recommendedOptionIds ?? []; + if (q.resolution || rec.length === 0) continue; + subs.push( + q.mode === "multi" + ? { ledgerId: item.ledgerId, qid: q.qid, kind: "answered", optionIds: rec } + : { ledgerId: item.ledgerId, qid: q.qid, kind: "answered", optionId: rec[0] }, + ); + } + } + if (subs.length === 0) throw new OpError(409, "no open question in that set has a recommendation"); + return this.submit(setId, subs); + } + + private ref(value: unknown): { repo: string; number: number } { + const m = typeof value === "string" ? REF.exec(value) : null; + if (!m || !this.ops.cfg.needsRepos.includes(m[1])) throw new OpError(400, "ref: not an item on the Needs me list"); + return { repo: m[1], number: Number(m[2]) }; + } + + /** The owner did the one thing only he could: say so and take the item off his list. */ + async handsDone(args: Record) { + const { repo, number } = this.ref(args.ref); + const note = + typeof args.note === "string" && args.note.trim() !== "" ? `\n\n${words(args.note, "note", 4000)}` : ""; + await this.ops.gh(["-X", "POST", `repos/${repo}/issues/${number}/comments`], { + body: `Done by the owner, from the PM console. The step that needed a person is finished; carry on.${note}\n\n${OWNER_REPLY_MARK}`, + }); + await this.ops.gh([ + "-X", + "DELETE", + `repos/${repo}/issues/${number}/labels/${encodeURIComponent("user/escalated")}`, + ]); + return { ref: args.ref, done: true }; + } + + async needComment(args: Record) { + const { repo, number } = this.ref(args.ref); + const made = (await this.ops.gh(["-X", "POST", `repos/${repo}/issues/${number}/comments`], { + body: `${words(args.text, "text", 8000)}\n\n${OWNER_REPLY_MARK}`, + })) as { html_url: string }; + return { ref: args.ref, url: made.html_url }; + } + + // ---- asks: what the owner has told the fleet to do, in his words ------ + + async asks() { + const label = this.ops.cfg.promptLabel; + const found = (await this.ops.gh([ + "-X", + "GET", + "search/issues", + "-f", + `q=repo:${this.repo} is:issue label:"${label}" sort:updated-desc`, + "-f", + "per_page=20", + ])) as { + items: { + number: number; + title: string; + body: string | null; + html_url: string; + state: string; + created_at: string; + updated_at: string; + comments: number; + }[]; + }; + // The newest task for each prompt's issue, by the key the task was filed under. + const keys = found.items.map((i) => `repo-health:v1:triage:${this.repo}:issue:${i.number}`); + const tasks = keys.length + ? await this.ops.sql( + `SELECT dedupe_key, status, worker_id AS worker FROM tasks WHERE queue = ? AND dedupe_key IN (${keys.map(() => "?").join(",")}) ORDER BY id DESC LIMIT 200`, + [this.ops.cfg.queue, ...keys], + ) + : []; + const taskOf = new Map(); + for (const t of tasks) { + const n = Number(/:issue:(\d+)$/.exec(String(t.dedupe_key))?.[1]); + if (n && !taskOf.has(n)) taskOf.set(n, t); + } + const out = []; + for (const i of found.items) { + let thread = this.replies.get(i.number); + if (i.comments > 0 && thread?.updated !== i.updated_at) { + const comments = (await this.ops.gh([`repos/${this.repo}/issues/${i.number}/comments?per_page=100`])) as { + body: string | null; + created_at: string; + }[]; + thread = { + updated: i.updated_at, + replies: comments.slice(-6).map((c) => ({ + you: (c.body ?? "").includes(OWNER_REPLY_MARK), + at: c.created_at.slice(0, 19), + text: clip((c.body ?? "").replace(OWNER_REPLY_MARK, "").trim(), 1500), + })), + }; + this.replies.set(i.number, thread); + } + const replies = i.comments > 0 ? (thread?.replies ?? []) : []; + const task = taskOf.get(i.number); + const answered = replies.length > 0 && !replies[replies.length - 1].you; + out.push({ + issue: i.number, + url: i.html_url, + text: clip((i.body ?? "").split("\n---\n")[0].trim() || i.title, 2000), + created: i.created_at.slice(0, 19), + updated: i.updated_at.slice(0, 19), + // done: closed. working: an agent holds the task. answered: the last word is the fleet's. + status: + i.state === "closed" + ? "done" + : task?.status === "claimed" + ? "working" + : answered + ? "answered" + : task?.status === "queued" + ? "queued" + : "waiting", + worker: task?.status === "claimed" ? task.worker : null, + replies, + }); + } + return out; + } + + private async ensureLabel() { + if (this.labelReady) return; + const made = await this.ops.run( + [this.ops.cfg.fleetBin, "gh", "api", "-X", "POST", `repos/${this.repo}/labels`, "--input", "-"], + { + stdin: JSON.stringify({ + name: this.ops.cfg.promptLabel, + color: "5319e7", + description: "An instruction from the owner, in his words (PM console)", + }), + }, + ); + // Exit 0: created. "already_exists": it was there. Anything else is a real failure. + if (made.code !== 0 && !/already_exists/.test(made.stdout + made.stderr)) { + throw new OpError(502, `could not prepare the ${this.ops.cfg.promptLabel} label`); + } + this.labelReady = true; + } + + /** Turn the owner's words into an issue and a top-band task, in one pass. */ + async ask(args: Record) { + const text = words(args.text, "text", 8000); + await this.ensureLabel(); + const first = text.split("\n")[0].trim(); + const made = (await this.ops.gh(["-X", "POST", `repos/${this.repo}/issues`], { + title: `Owner: ${first}`.slice(0, 120), + body: `${text}\n\n---\n${ASK_NOTE}\n${OWNER_PROMPT_MARK}`, + labels: [this.ops.cfg.promptLabel, "expedite"], + })) as { number: number; html_url: string }; + const queued = await this.ops.enqueue( + promptPacket(this.repo, this.ops.cfg.queue, made.number, text, this.clock().toISOString()), + ); + return { + issue: made.number, + url: made.html_url, + queued: queued.code === 0, + ...(queued.code === 0 + ? {} + : { note: `filed, not queued: ${(queued.stderr || queued.stdout).trim().split("\n").pop()?.slice(0, 200)}` }), + }; + } + + /** The owner answers back on one of his prompts; the fleet is woken for it. */ + async askReply(args: Record) { + const issue = Number(args.issue); + if (!Number.isSafeInteger(issue) || issue <= 0) throw new OpError(400, "issue: a positive whole number"); + const text = words(args.text, "text", 8000); + const current = (await this.ops.gh([`repos/${this.repo}/issues/${issue}`])) as { + state: string; + labels: { name: string }[]; + }; + if (!current.labels.some((l) => l.name === this.ops.cfg.promptLabel)) { + throw new OpError(400, "that issue is not one of the owner's prompts"); + } + await this.ops.gh(["-X", "POST", `repos/${this.repo}/issues/${issue}/comments`], { + body: `${text}\n\n${OWNER_REPLY_MARK}`, + }); + if (current.state === "closed") { + await this.ops.gh(["-X", "PATCH", `repos/${this.repo}/issues/${issue}`], { state: "open" }); + } + const queued = await this.ops.enqueue( + promptPacket(this.repo, this.ops.cfg.queue, issue, text, this.clock().toISOString()), + ); + return { issue, queued: queued.code === 0 }; + } + + /** Nothing is left on a prompt: close it. */ + async askClose(args: Record) { + const issue = Number(args.issue); + if (!Number.isSafeInteger(issue) || issue <= 0) throw new OpError(400, "issue: a positive whole number"); + const current = (await this.ops.gh([`repos/${this.repo}/issues/${issue}`])) as { labels: { name: string }[] }; + if (!current.labels.some((l) => l.name === this.ops.cfg.promptLabel)) { + throw new OpError(400, "that issue is not one of the owner's prompts"); + } + await this.ops.gh(["-X", "PATCH", `repos/${this.repo}/issues/${issue}`], { + state: "closed", + state_reason: "completed", + }); + return { issue, closed: true }; + } + + /** Move a queued task: to the top band, or one step sooner or later. */ + async moveTask(args: Record) { + const task = Number(args.task); + if (!Number.isSafeInteger(task) || task <= 0) throw new OpError(400, "task: a positive whole number"); + if (args.to === "first") return this.ops.setTaskPriority(task, PRIORITY_SCALE[0]); + if (args.to !== "sooner" && args.to !== "later") throw new OpError(400, "to: first, sooner or later"); + const [row] = await this.ops.sql("SELECT priority FROM tasks WHERE id = ? AND queue = ? AND status = 'queued'", [ + task, + this.ops.cfg.queue, + ]); + if (!row) throw new OpError(409, `task ${task} is not queued, so its place cannot change`); + const scale = PRIORITY_SCALE as readonly number[]; + const current = Number(row.priority ?? 30); + // The nearest step on the scale in the direction asked. + const target = + args.to === "sooner" ? [...scale].reverse().find((p) => p < current) : scale.find((p) => p > current); + if (target === undefined) { + throw new OpError( + 409, + `task ${task} is already ${args.to === "sooner" ? "in the top band" : "in the last band"}`, + ); + } + return this.ops.setTaskPriority(task, target); + } +} diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts index 82637ac9d0..ba2ed260b5 100644 --- a/pm-stack/console/test/console.test.ts +++ b/pm-stack/console/test/console.test.ts @@ -977,7 +977,6 @@ describe("HTTP surface", () => { }); const PUBLIC = [ - "/manifest.webmanifest", "/icons/icon-192.png", "/icons/icon-512.png", "/icons/icon-maskable-512.png", @@ -1026,6 +1025,11 @@ describe("HTTP surface", () => { expect(call.method).toBe("GET"); expect(call.headers).toEqual({ host: "pm.security.cab", "accept-encoding": "identity" }); } + expect((await handle(post("/icons/icon-192.png", {}), out)).status).toBe(401); + // The install manifest is the app's own: public, and it opens the app. + const manifest = await handle(get("/manifest.webmanifest"), out); + expect(manifest.headers.get("content-type")).toContain("application/manifest+json"); + expect(await manifest.json()).toMatchObject({ start_url: "/console/", scope: "/", display: "standalone" }); expect((await handle(post("/manifest.webmanifest", {}), out)).status).toBe(401); expect(out.sent.length).toBe(PUBLIC.length); }); diff --git a/pm-stack/console/test/push.test.ts b/pm-stack/console/test/push.test.ts new file mode 100644 index 0000000000..68943184ce --- /dev/null +++ b/pm-stack/console/test/push.test.ts @@ -0,0 +1,337 @@ +// Notifications: the message a phone receives, and when one is owed. +// +// Oracles: the test plays the browser. It makes the subscription's key +// pair itself and decrypts what the server sends with the receiving +// half of RFC 8291, written here from the RFC and not shared with the +// code under test; it verifies the VAPID signature with the server's +// public key. "Owed" is decided by a table of before and after states. +import { describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Docs } from "../src/docs.ts"; +import { changes, NOTHING_SEEN, Notifier, type Seen } from "../src/notify.ts"; +import { encrypt, Push, validSubscription } from "../src/push.ts"; + +const b64u = (b: ArrayBuffer | Uint8Array) => Buffer.from(b as ArrayBuffer).toString("base64url"); +const raw = (s: string) => new Uint8Array(Buffer.from(s, "base64url")); + +async function browser(host = "fcm.googleapis.com") { + const pair = (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [ + "deriveBits", + ])) as CryptoKeyPair; + const auth = crypto.getRandomValues(new Uint8Array(16)); + const p256dh = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey)); + const hkdf = async (salt: Uint8Array, ikm: Uint8Array, info: Uint8Array, n: number) => + new Uint8Array( + await crypto.subtle.deriveBits( + { name: "HKDF", hash: "SHA-256", salt, info }, + await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]), + n * 8, + ), + ); + const cat = (...p: Uint8Array[]) => new Uint8Array(p.flatMap((x) => [...x])); + const t = new TextEncoder(); + return { + subscription: { endpoint: `https://${host}/fcm/send/abc123`, keys: { p256dh: b64u(p256dh), auth: b64u(auth) } }, + /** RFC 8291 section 3.4 and RFC 8188: what a user agent does with the body. */ + async open(body: Uint8Array): Promise { + const salt = body.slice(0, 16); + const rs = new DataView(body.buffer, body.byteOffset).getUint32(16); + const idlen = body[20]; + const sender = body.slice(21, 21 + idlen); + const sealed = body.slice(21 + idlen); + expect(rs).toBe(4096); + expect(idlen).toBe(65); + const shared = new Uint8Array( + await crypto.subtle.deriveBits( + { + name: "ECDH", + public: await crypto.subtle.importKey("raw", sender, { name: "ECDH", namedCurve: "P-256" }, false, []), + }, + pair.privateKey, + 256, + ), + ); + const ikm = await hkdf(auth, shared, cat(t.encode("WebPush: info\0"), p256dh, sender), 32); + const cek = await hkdf(salt, ikm, t.encode("Content-Encoding: aes128gcm\0"), 16); + const nonce = await hkdf(salt, ikm, t.encode("Content-Encoding: nonce\0"), 12); + const plain = new Uint8Array( + await crypto.subtle.decrypt( + { name: "AES-GCM", iv: nonce }, + await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]), + sealed, + ), + ); + expect(plain[plain.length - 1]).toBe(2); // the last-record delimiter + return new TextDecoder().decode(plain.slice(0, -1)); + }, + }; +} + +describe("the message a phone receives", () => { + test("only the subscribed browser can read it, and each one is sealed afresh", async () => { + const b = await browser(); + const text = JSON.stringify({ title: "The fleet replied on #12501", body: "Done — and “quoted” ✓" }); + const one = await encrypt(b.subscription, new TextEncoder().encode(text)); + const two = await encrypt(b.subscription, new TextEncoder().encode(text)); + expect(await b.open(one)).toBe(text); + expect(await b.open(two)).toBe(text); + expect(b64u(one)).not.toBe(b64u(two)); // a new salt and a new sender key every time + const other = await browser(); + await expect(other.open(one)).rejects.toThrow(); // not readable by anyone else + const flipped = one.slice(); + flipped[flipped.length - 3] ^= 1; + await expect(b.open(flipped)).rejects.toThrow(); // and not alterable on the way + }); + + test("a send is signed for the push service it goes to, and reaches every device", async () => { + const dir = mkdtempSync(join(tmpdir(), "pm-push-")); + try { + const a = await browser(); + const m = await browser("updates.push.services.mozilla.com"); + const posts: { url: string; headers: Record; body: Uint8Array }[] = []; + const NOW = 1_800_000_000_000; + const push = new Push( + join(dir, "push.json"), + "mailto:owner@example.com", + async (url, init) => (posts.push({ url, headers: init.headers, body: init.body }), { status: 201 }), + () => NOW, + ); + const status = await push.status(); + expect(raw(status.key).length).toBe(65); // an uncompressed P-256 point, as the browser expects + expect(status.devices).toBe(0); + await push.subscribe(a.subscription, "phone"); + await push.subscribe(a.subscription, "phone again"); // the same device is not counted twice + expect((await push.subscribe(m.subscription, "desktop")).devices).toBe(2); + expect(await push.send("replies", { title: "t", body: "b", url: "/console/#ask", tag: "x" })).toEqual({ + sent: 2, + gone: 0, + failed: 0, + }); + expect(posts.map((p) => p.url)).toEqual([a.subscription.endpoint, m.subscription.endpoint]); + expect(JSON.parse(await a.open(posts[0].body))).toEqual({ + title: "t", + body: "b", + url: "/console/#ask", + tag: "x", + class: "replies", + }); + expect(JSON.parse(await m.open(posts[1].body)).class).toBe("replies"); + for (const p of posts) { + expect(p.headers["Content-Encoding"]).toBe("aes128gcm"); + expect(Number(p.headers.TTL)).toBeGreaterThan(0); + const [, jwt, key] = /^vapid t=([^,]+), k=(.+)$/.exec(p.headers.Authorization) ?? []; + expect(key).toBe(status.key); + const [head, body, sig] = jwt.split("."); + expect(JSON.parse(Buffer.from(head, "base64url").toString())).toEqual({ typ: "JWT", alg: "ES256" }); + const claims = JSON.parse(Buffer.from(body, "base64url").toString()); + expect(claims.aud).toBe(new URL(p.url).origin); // signed for this push service and no other + expect(claims.sub).toBe("mailto:owner@example.com"); + expect(claims.exp).toBe(NOW / 1000 + 12 * 3600); // within the 24 hours a push service allows + const pub = await crypto.subtle.importKey("raw", raw(key), { name: "ECDSA", namedCurve: "P-256" }, false, [ + "verify", + ]); + expect( + await crypto.subtle.verify( + { name: "ECDSA", hash: "SHA-256" }, + pub, + raw(sig), + new TextEncoder().encode(`${head}.${body}`), + ), + ).toBe(true); + } + // The key pair and the devices survive a restart; the file is private. + const again = new Push(join(dir, "push.json"), "mailto:owner@example.com", async () => ({ status: 201 })); + expect(await again.status()).toEqual(status.devices === 0 ? { ...status, devices: 2 } : status); + expect((await again.status()).key).toBe(status.key); + expect(JSON.parse(readFileSync(join(dir, "push.json"), "utf8")).vapid.privateJwk.d.length).toBeGreaterThan(20); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("a device that is gone is forgotten, a class switched off sends nothing, a failure is counted", async () => { + const dir = mkdtempSync(join(tmpdir(), "pm-push-")); + try { + const a = await browser(); + const b = await browser("web.push.apple.com"); + let answer = (url: string) => (url === a.subscription.endpoint ? 410 : 201); + let posts = 0; + const push = new Push( + join(dir, "push.json"), + "mailto:o@example.com", + async (url) => (posts++, { status: answer(url) }), + ); + await push.subscribe(a.subscription, ""); + await push.subscribe(b.subscription, ""); + expect(await push.send("needs", { title: "t", body: "b", url: "/" })).toEqual({ sent: 1, gone: 1, failed: 0 }); + expect((await push.status()).devices).toBe(1); + expect(await push.setClass("needs", false)).toEqual({ + replies: true, + needs: false, + questions: true, + trouble: true, + }); + posts = 0; + expect(await push.send("needs", { title: "t", body: "b", url: "/" })).toEqual({ sent: 0, gone: 0, failed: 0 }); + expect(posts).toBe(0); + expect((await push.send("test", { title: "t", body: "b", url: "/" })).sent).toBe(1); // a test ignores the switches + await push.setClass("needs", true); + answer = () => 500; + expect(await push.send("needs", { title: "t", body: "b", url: "/" })).toEqual({ sent: 0, gone: 0, failed: 1 }); + expect((await push.status()).devices).toBe(1); // a failure is not "gone" + await expect(push.setClass("everything", true)).rejects.toThrow(/class/); + expect((await push.unsubscribe(b.subscription.endpoint)).devices).toBe(0); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test("the server only posts to push services", async () => { + const good = (await browser()).subscription; + expect(validSubscription(good)).toEqual(good); + for (const endpoint of [ + "http://fcm.googleapis.com/fcm/send/x", // not https + "https://127.0.0.1:4870/api/alerts", // this machine + "https://fcm.googleapis.com.evil.example/x", + "https://evil.example/fcm.googleapis.com", + "https://user:pw@fcm.googleapis.com/x", + "https://queue-broker.security.cab/enqueue", + "not a url", + ]) { + expect(validSubscription({ ...good, endpoint })).toBeNull(); + } + expect(validSubscription({ ...good, keys: { ...good.keys, p256dh: "AAAA" } })).toBeNull(); + expect(validSubscription({ ...good, keys: { ...good.keys, auth: "AAAA" } })).toBeNull(); + expect(validSubscription({ endpoint: good.endpoint })).toBeNull(); + expect(validSubscription(null)).toBeNull(); + const dir = mkdtempSync(join(tmpdir(), "pm-push-")); + try { + await expect( + new Push(join(dir, "p.json"), "mailto:o@example.com").subscribe( + { ...good, endpoint: "https://127.0.0.1/x" }, + "", + ), + ).rejects.toThrow(/push service/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("when a notification is owed", () => { + const reply = (at: string, you = false) => ({ you, at, text: "Done. #12279 is first in the queue." }); + const state = (over: Record = {}) => ({ + asks: [ + { issue: 12501, replies: [reply("2026-11-22T06:00:00")] }, + { issue: 12502, replies: [] }, + ], + census: { hands: [{ ref: "o/r#1", title: "t1", action: "Power on the host." }] }, + sessions: { waiting: [] }, + questionCount: { total: 360 }, + services: [ + { unit: "a.service", active: "active" }, + { unit: "b.service", active: "failed" }, + ], + ...over, + }); + + test("turning notifications on takes stock and says nothing", () => { + const first = changes(NOTHING_SEEN, state()); + expect(first.messages).toEqual([]); + expect(first.seen).toEqual({ + primed: true, + asks: { "12501": "2026-11-22T06:00:00" }, + hands: ["o/r#1"], + questions: 360, + failed: ["b.service"], + }); + expect(changes(first.seen, state()).messages).toEqual([]); // and nothing is said twice + }); + + test("each new thing is announced once, with where to go", () => { + const seen: Seen = changes(NOTHING_SEEN, state()).seen; + const later = state({ + asks: [ + { issue: 12501, replies: [reply("2026-11-22T06:00:00"), reply("2026-11-22T07:00:00")] }, + { issue: 12502, replies: [reply("2026-11-22T07:05:00", true)] }, + ], + census: { + hands: [ + { ref: "o/r#1", title: "t1", action: "Power on the host." }, + { ref: "o/r#2", title: "Sign the form", action: "" }, + ], + }, + sessions: { waiting: [{ id: "porkbun", title: "Log into the main account" }] }, + questionCount: { total: 363 }, + services: [ + { unit: "a.service", active: "failed" }, + { unit: "b.service", active: "failed" }, + ], + }); + const out = changes(seen, later); + expect(out.messages.map((m) => [m.cls, m.title, m.body, m.url])).toEqual([ + ["replies", "The fleet replied on #12501", "Done. #12279 is first in the queue.", "/console/#ask"], + ["needs", "Something needs you", "Sign the form", "/console/#needs/hands"], + ["needs", "Something needs you", "Log into the main account", "/console/#needs/hands"], + ["questions", "3 new questions for you", "363 open in all.", "/console/#needs/questions"], + ["trouble", "A unit failed", "a.service", "/console/#more/services"], + ]); + expect(changes(out.seen, later).messages).toEqual([]); + // His own reply is not news to him; fewer questions is not news either, + // but it lowers the mark, so the next new one is. + const fewer = changes(out.seen, { ...later, questionCount: { total: 300 } }); + expect(fewer.messages).toEqual([]); + expect(changes(fewer.seen, { ...later, questionCount: { total: 301 } }).messages.map((m) => m.title)).toEqual([ + "1 new question for you", + ]); + // Something that went away and came back needs him again. + const gone = changes(out.seen, { ...later, census: { hands: [] }, sessions: { waiting: [] } }); + expect(changes(gone.seen, later).messages.filter((m) => m.cls === "needs").length).toBe(3); + }); + + test("a source that could not be read changes nothing", () => { + const seen = changes(NOTHING_SEEN, state()).seen; + const blind = changes(seen, { asks: null, census: null, sessions: null, questionCount: null, services: null }); + expect(blind.messages).toEqual([]); + expect(blind.seen).toEqual(seen); // nothing is forgotten, so nothing is announced again when it reads once more + }); + + test("the notifier reads the sources itself, sends what is owed, and remembers across restarts", async () => { + const dir = mkdtempSync(join(tmpdir(), "pm-notify-")); + try { + let now = state(); + const still = { ttlMs: 1e12, load: async () => "x" }; + const sections = { board: still, prs: still, priorities: still, agents: still, more: still, questions: still }; + const live = (name: string) => ({ ttlMs: 1e12, load: async () => (now as Record)[name] }); + const docs = new Docs({ + ...sections, + asks: live("asks"), + census: live("census"), + sessions: live("sessions"), + questionCount: live("questionCount"), + services: live("services"), + }); + const sent: string[] = []; + const b = await browser(); + const push = new Push( + join(dir, "push.json"), + "mailto:o@example.com", + async (_u, init) => (sent.push(JSON.parse(await b.open(init.body)).title), { status: 201 }), + ); + const notifier = new Notifier(docs, push, join(dir, "notified.json")); + expect(await notifier.tick()).toBe(0); // no device: nothing is read, nothing is sent + await push.subscribe(b.subscription, "phone"); + expect(await notifier.tick()).toBe(0); // first pass: take stock + now = state({ questionCount: { total: 361 } }); + expect(await notifier.tick()).toBe(1); + expect(sent).toEqual(["1 new question for you"]); + const restarted = new Notifier(docs, push, join(dir, "notified.json")); + expect(await restarted.tick()).toBe(0); + expect(sent.length).toBe(1); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/pm-stack/console/test/work.test.ts b/pm-stack/console/test/work.test.ts new file mode 100644 index 0000000000..7ae3914020 --- /dev/null +++ b/pm-stack/console/test/work.test.ts @@ -0,0 +1,796 @@ +// The primary screens: what is in progress, what is next, what needs the +// owner, and what he has asked for. +// +// Oracles: the queue store, the dashboard and the fleet's commands are +// recorders, so every read and write is compared with what it should be +// as an exact statement, request or argument vector. The questions store +// is a file written by the test, so "open" and "recommended" are defined +// here and not by the code under test. +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { gunzipSync } from "node:zlib"; +import { actions, perform } from "../src/actions.ts"; +import { readConfig } from "../src/config.ts"; +import { Docs } from "../src/docs.ts"; +import { type Fetch, OpError, Ops, type Run } from "../src/ops.ts"; +import { type Deps, handle, loaders } from "../src/server.ts"; +import { promptPacket, Work } from "../src/work.ts"; + +const CFG = readConfig({ HOME: "/h" }); +const REPO = "developing-today/code"; + +type Sql = { sql: string; args: (string | number)[] }; +/** A queue store and a dashboard in one fetch, both recording. */ +function world(opts: { + rows?: (st: Sql) => Record[] | { affected: number }; + dash?: (path: string, body: unknown) => unknown | { status: number; error: string }; + commands?: (argv: string[], stdin?: string) => string | { code: number; stderr: string }; +}) { + const sqls: Sql[][] = []; + const dashed: { path: string; body: unknown }[] = []; + const calls: { argv: string[]; stdin?: string; packet?: unknown }[] = []; + const fetchImpl: Fetch = async (url, init) => { + if (url.startsWith(CFG.queueDbUrl)) { + const requests = ( + JSON.parse(init.body ?? "{}").requests as { + type: string; + stmt?: { sql: string; args: { value: string; type: string }[] }; + }[] + ).filter((r) => r.type === "execute"); + const batch = requests.map((r) => ({ + sql: r.stmt?.sql ?? "", + args: (r.stmt?.args ?? []).map((a) => (a.type === "integer" ? Number(a.value) : a.value)), + })); + sqls.push(batch); + return { + ok: true, + status: 200, + json: async () => ({ + results: batch.map((st) => { + const out = opts.rows?.(st) ?? []; + if (!Array.isArray(out)) + return { type: "ok", response: { result: { cols: [], rows: [], affected_row_count: out.affected } } }; + const cols = Object.keys(out[0] ?? {}).map((name) => ({ name })); + return { + type: "ok", + response: { result: { cols, rows: out.map((r) => cols.map((c) => ({ value: r[c.name] }))) } }, + }; + }), + }), + }; + } + const path = url.replace(CFG.dashboardUrl ?? "", ""); + const body = init.body ? JSON.parse(init.body) : undefined; + dashed.push({ path, body }); + const out = opts.dash?.(path, body) ?? {}; + const failed = out !== null && typeof out === "object" && "status" in out && "error" in out; + return { ok: !failed, status: failed ? (out as { status: number }).status : 200, json: async () => out }; + }; + const run: Run = async (argv, o) => { + const entry: { argv: string[]; stdin?: string; packet?: unknown } = { argv, stdin: o?.stdin }; + if (argv[1] === "queue" && argv[2] === "enqueue") entry.packet = JSON.parse(readFileSync(argv[3], "utf8")); + calls.push(entry); + if (argv[1] === "secrets") return { code: 0, stdout: "token\n", stderr: "" }; + const a = opts.commands?.(argv, o?.stdin) ?? "{}"; + return typeof a === "string" ? { code: 0, stdout: a, stderr: "" } : { code: a.code, stdout: "", stderr: a.stderr }; + }; + const ops = new Ops(CFG, run, fetchImpl); + return { ops, sqls, dashed, calls, gh: () => calls.filter((c) => c.argv[1] === "gh").map((c) => c.argv.slice(3)) }; +} + +const TOKEN = "set-token-never-leaves-the-host"; +function store(extra: Record = {}) { + const q = (qid: string, more: Record = {}) => ({ + qid, + question: `Question ${qid}?`, + context: "c".repeat(900), + description: "d", + options: [ + { id: "opt-1", label: "First", tags: ["recommended"] }, + { id: "opt-2", label: "Second" }, + ], + recommendedOptionIds: ["opt-1"], + ...more, + }); + return JSON.stringify({ + version: 1, + sets: [ + { + setId: "old-set", + title: "Older", + token: `${TOKEN}-old`, + createdAt: "2026-11-10T00:00:00Z", + items: [{ ledgerId: "L0", title: "Old item", group: "g", links: [], questions: [q("a")] }], + }, + { + setId: "new-set", + title: "Newer", + token: TOKEN, + createdAt: "2026-11-17T00:00:00Z", + items: [ + { + ledgerId: "L1", + title: "Item one", + group: "g", + links: ["https://github.com/developing-today/code/issues/10036"], + questions: [ + q("b", { order: 2 }), + q("c", { order: 1, mode: "multi", recommendedOptionIds: ["opt-1", "opt-2"] }), + q("answered", { resolution: { kind: "answered", at: "x", via: "y" } }), + q("norec", { order: 3, recommendedOptionIds: [] }), + ], + }, + ], + }, + ], + ...extra, + }); +} + +describe("what is in progress and what is next", () => { + test("one round trip, reads only, in the queue's own order", async () => { + const w = world({ + rows: (st) => + st.sql.includes("GROUP BY status") + ? [ + { status: "claimed", n: 3 }, + { status: "blocked", n: 474 }, + ] + : st.sql.includes("'claimed'") + ? [{ id: 7, title: "t", issue: 9075, kind: "small_fix", step: "next thing" }] + : [], + }); + const board = await new Work(w.ops).board(); + expect(w.sqls.length).toBe(1); + expect(w.sqls[0].length).toBe(4); + for (const st of w.sqls[0]) { + expect(st.sql.trimStart().startsWith("SELECT")).toBe(true); + expect(st.args).toEqual(["repo-health-code-pilot"]); + } + // In progress: newest claim first. Next: the claim order the queue itself uses. + expect(w.sqls[0][1].sql).toContain("status = 'claimed' ORDER BY claimed_at DESC"); + expect(w.sqls[0][2].sql).toContain( + "status = 'queued' ORDER BY (priority IS NULL), priority ASC, created_at ASC, id ASC", + ); + // A row whose progress or payload is not JSON must not fail the whole read. + expect(w.sqls[0][1].sql).toContain("json_valid(progress)"); + expect(w.sqls[0][1].sql).toContain("json_valid(payload)"); + expect(board.counts).toEqual({ claimed: 3, blocked: 474 }); + expect(board.now).toEqual([ + { + id: 7, + title: "t", + issue: 9075, + kind: "small_fix", + step: "next thing", + url: `https://github.com/${REPO}/issues/9075`, + }, + ]); + }); + + test("moving a queued task changes one column on one queued row, along the scale", async () => { + const run = async (to: string, current: number | null, affected = 1) => { + const w = world({ + rows: (st) => (st.sql.startsWith("UPDATE") ? { affected } : current === null ? [] : [{ priority: current }]), + }); + const out = await new Work(w.ops).moveTask({ task: 21016, to }).catch((e: OpError) => e.status); + return { out, writes: w.sqls.flat().filter((s) => !s.sql.startsWith("SELECT")) }; + }; + const update = (priority: number) => [ + { + sql: "UPDATE tasks SET priority = ? WHERE id = ? AND queue = ? AND status = 'queued'", + args: [priority, 21016, "repo-health-code-pilot"], + }, + ]; + expect(await run("first", 30)).toEqual({ out: { task: 21016, priority: 10 }, writes: update(10) }); + expect(await run("sooner", 30)).toEqual({ out: { task: 21016, priority: 20 }, writes: update(20) }); + expect(await run("later", 30)).toEqual({ out: { task: 21016, priority: 40 }, writes: update(40) }); + expect(await run("later", 50)).toEqual({ out: { task: 21016, priority: 70 }, writes: update(70) }); + // Off-scale values in the store still move to the nearest step in the direction asked. + expect(await run("sooner", 25)).toEqual({ out: { task: 21016, priority: 20 }, writes: update(20) }); + // Nothing further to move to, a task that is no longer queued, and a bad request: no write. + expect(await run("sooner", 10)).toEqual({ out: 409, writes: [] }); + expect(await run("later", 90)).toEqual({ out: 409, writes: [] }); + expect(await run("sooner", null)).toEqual({ out: 409, writes: [] }); + expect((await run("first", 30, 0)).out).toBe(409); + expect(await run("sideways", 30)).toEqual({ out: 400, writes: [] }); + const w = world({}); + for (const [task, priority] of [ + [1, 25], + [1, 0], + ["1; DROP", 10], + [-1, 10], + ] as const) { + await expect(w.ops.setTaskPriority(task, priority)).rejects.toThrow(OpError); + } + expect(w.sqls).toEqual([]); + await expect(w.ops.reads([{ sql: "UPDATE tasks SET status = 'done'", args: [] }])).rejects.toThrow(/only reads/); + }); +}); + +describe("questions waiting on the owner", () => { + test("only open questions, newest set first, and the answer tokens stay on the host", async () => { + const w = world({}); + const q = await new Work(w.ops, async () => store()).questions(); + expect(q.total).toBe(4); + expect(q.sets).toBe(2); + expect(q.open.map((x) => [x.set, x.qid])).toEqual([ + ["new-set", "c"], + ["new-set", "b"], + ["new-set", "norec"], + ["old-set", "a"], + ]); + expect(q.open[0]).toMatchObject({ multi: true, recommended: ["opt-1", "opt-2"], ledger: "L1", setTitle: "Newer" }); + expect(q.open[0].context.length).toBe(280); + expect(q.open[0].more).toBe(true); + expect(JSON.stringify(q)).not.toContain(TOKEN); + // The rest of the background is read when the question is opened. + const work = new Work(w.ops, async () => store()); + expect(await work.question("new-set", "L1", "b")).toEqual({ context: "c".repeat(900), detail: "d" }); + await expect(work.question("new-set", "L1", "nope")).rejects.toThrow(/not in the store/); + await expect(work.question("__proto__", "L1", "b")).rejects.toThrow(/not in the store/); + await expect(new Work(w.ops, async () => "not json").questions()).rejects.toThrow(/questions store/); + expect((await new Work(w.ops, async () => "{}").questions()).total).toBe(0); + }); + + test("an answer goes through the dashboard's own endpoint with the set's token", async () => { + const w = world({ dash: () => ({ outcomes: [{ qid: "b", applied: true }] }) }); + const work = new Work(w.ops, async () => store()); + expect( + await work.answer({ set: "new-set", ledger: "L1", qid: "b", option: "opt-2", comment: " because " }), + ).toEqual({ set: "new-set", applied: 1, refused: [] }); + expect(w.dashed).toEqual([ + { + path: "/api/decisions/new-set/submit", + body: { + token: TOKEN, + submissions: [{ ledgerId: "L1", qid: "b", kind: "answered", optionId: "opt-2", comment: "because" }], + }, + }, + ]); + await work.answer({ set: "new-set", ledger: "L1", qid: "c", options: ["opt-1", "opt-2"] }); + await work.answer({ set: "new-set", ledger: "L1", qid: "b", text: "my own answer" }); + await work.defer({ set: "new-set", ledger: "L1", qid: "b" }); + expect(w.dashed.slice(1).map((d) => (d.body as { submissions: unknown[] }).submissions[0])).toEqual([ + { ledgerId: "L1", qid: "c", kind: "answered", optionIds: ["opt-1", "opt-2"] }, + { ledgerId: "L1", qid: "b", kind: "answered", freeText: "my own answer" }, + { ledgerId: "L1", qid: "b", kind: "deferred", lean: "approve" }, + ]); + const before = w.dashed.length; + for (const args of [ + { set: "new-set", ledger: "L1", qid: "b" }, // nothing chosen + { set: "../etc", ledger: "L1", qid: "b", option: "opt-1" }, + { set: "missing-set", ledger: "L1", qid: "b", option: "opt-1" }, + { set: "new-set", ledger: "", qid: "b", option: "opt-1" }, + { set: "new-set", ledger: "L1", qid: "b", text: "x".repeat(4001) }, + ]) { + await expect(work.answer(args)).rejects.toThrow(OpError); + } + await expect(work.defer({ set: "new-set", ledger: "L1", qid: "b", lean: "whatever" })).rejects.toThrow(/lean/); + expect(w.dashed.length).toBe(before); + // What the dashboard refuses is reported, not hidden. + const refusing = world({ dash: () => ({ outcomes: [{ qid: "b", applied: false, reason: "already answered" }] }) }); + expect( + await new Work(refusing.ops, async () => store()).answer({ + set: "new-set", + ledger: "L1", + qid: "b", + option: "opt-1", + }), + ).toEqual({ set: "new-set", applied: 0, refused: [{ qid: "b", why: "already answered" }] }); + const down = world({ dash: () => ({ status: 403, error: "unknown set or bad token" }) }); + await expect( + new Work(down.ops, async () => store()).answer({ set: "new-set", ledger: "L1", qid: "b", option: "opt-1" }), + ).rejects.toThrow(/bad token/); + }); + + test("accepting recommendations answers exactly the open questions that have one", async () => { + const w = world({ + dash: (_p, body) => ({ + outcomes: (body as { submissions: { qid: string }[] }).submissions.map((s) => ({ qid: s.qid, applied: true })), + }), + }); + const work = new Work(w.ops, async () => store()); + expect((await work.acceptRecommended("new-set")).applied).toBe(2); + expect((w.dashed[0].body as { submissions: unknown[] }).submissions).toEqual([ + { ledgerId: "L1", qid: "b", kind: "answered", optionId: "opt-1" }, + { ledgerId: "L1", qid: "c", kind: "answered", optionIds: ["opt-1", "opt-2"] }, + ]); + await expect(work.acceptRecommended("nope")).rejects.toThrow(/not in the store/); + const none = JSON.parse(store()); + none.sets[1].items[0].questions = none.sets[1].items[0].questions.filter((q: { qid: string }) => q.qid === "norec"); + await expect(new Work(w.ops, async () => JSON.stringify(none)).acceptRecommended("new-set")).rejects.toThrow( + /no open question/, + ); + }); +}); + +describe("what needs the owner's hands", () => { + test("the census is split into what only he can do, reviews, and the rest", async () => { + const item = (n: number, labels: string[], hands?: unknown) => ({ + ref: `${REPO}#${n}`, + kind: "issue", + title: `t${n}`, + url: `u${n}`, + needsLabels: labels, + reason: n === 3 ? "why" : null, + updatedAt: "2026-11-20T01:02:03Z", + hands, + }); + const w = world({ + dash: (path) => + path === "/api/needs-drew.json" + ? { + fetchedAt: "x", + complete: true, + items: [ + item(1, ["user/escalated"], { kind: "physical", action: "Power on the host." }), + item(2, ["user/review"]), + item(3, ["user/escalated"]), + item(4, ["user/escalated", "user/review"], { kind: "payment", action: null }), + ], + } + : [ + { + tier: "in-motion", + sessionId: "s", + title: "moving", + agent: "build", + model: "m", + directory: "/home/user/git/code-j", + lastActivityAt: "2026-11-22T00:00:00Z", + activeToolCalls: 2, + messageCount: 9, + }, + { tier: "needs-drew", id: "p", title: "log in", ref: "gh:x/y#1", drewReason: null }, + { tier: "needs-orchestrator", title: "not his" }, + ], + }); + const work = new Work(w.ops); + const c = await work.census(); + expect(c.hands.map((i) => [i.ref, i.kind, i.action])).toEqual([ + [`${REPO}#1`, "physical", "Power on the host."], + [`${REPO}#4`, "payment", ""], + ]); + expect(c.reviews.map((i) => i.ref)).toEqual([`${REPO}#2`]); + expect(c.other.map((i) => [i.ref, i.why])).toEqual([[`${REPO}#3`, "why"]]); + const s = await work.sessions(); + expect(s.moving).toEqual([ + { + id: "s", + title: "moving", + agent: "build", + model: "m", + where: "git/code-j", + last: "2026-11-22T00:00:00Z", + tools: 2, + messages: 9, + }, + ]); + expect(s.waiting).toEqual([{ id: "p", title: "log in", ref: "gh:x/y#1", why: "" }]); + }); + + test("done means a comment and the label gone, only for a repository on the list", async () => { + const w = world({}); + const work = new Work(w.ops); + await work.handsDone({ ref: "dezren39/nix#12", note: " the BMC is on " }); + expect(w.gh()).toEqual([ + ["-X", "POST", "repos/dezren39/nix/issues/12/comments", "--input", "-"], + ["-X", "DELETE", "repos/dezren39/nix/issues/12/labels/user%2Fescalated"], + ]); + expect(JSON.parse(w.calls[0].stdin ?? "").body).toContain("the BMC is on"); + await work.needComment({ ref: `${REPO}#5`, text: "go on" }); + expect(w.gh()[2]).toEqual(["-X", "POST", `repos/${REPO}/issues/5/comments`, "--input", "-"]); + const before = w.calls.length; + for (const ref of ["someone/else#1", `${REPO}#0`, `${REPO}#1/labels`, `${REPO}`, "", 7, `../${REPO}#1`]) { + await expect(work.handsDone({ ref })).rejects.toThrow(OpError); + } + await expect(work.needComment({ ref: `${REPO}#5`, text: " " })).rejects.toThrow(OpError); + expect(w.calls.length).toBe(before); + }); +}); + +describe("what the owner asks for in his own words", () => { + test("a prompt becomes a labelled issue and a top-band task in one pass", async () => { + const w = world({ + commands: (argv) => + argv.includes(`repos/${REPO}/issues`) ? JSON.stringify({ number: 12501, html_url: "https://x/12501" }) : "{}", + }); + const work = new Work(w.ops, undefined, () => new Date("2026-11-22T06:00:00Z")); + expect(await work.ask({ text: "Make the join slice the top priority\nand tell me what is in its way." })).toEqual({ + issue: 12501, + url: "https://x/12501", + queued: true, + }); + expect(w.gh()).toEqual([ + ["-X", "POST", `repos/${REPO}/labels`, "--input", "-"], + ["-X", "POST", `repos/${REPO}/issues`, "--input", "-"], + ]); + const issue = JSON.parse(w.calls[1].stdin ?? ""); + expect(issue.title).toBe("Owner: Make the join slice the top priority"); + expect(issue.labels).toEqual(["owner/prompt", "expedite"]); + expect(issue.body.startsWith("Make the join slice the top priority\nand tell me")).toBe(true); + expect(issue.body).toContain(""); + const enqueue = w.calls[2]; + expect(enqueue.argv.slice(0, 3)).toEqual(["fleet", "queue", "enqueue"]); + expect(enqueue.argv.slice(4)).toEqual(["--queue", "repo-health-code-pilot"]); + expect(enqueue.packet).toEqual( + promptPacket( + REPO, + "repo-health-code-pilot", + 12501, + "Make the join slice the top priority\nand tell me what is in its way.", + "2026-11-22T06:00:00.000Z", + ), + ); + expect(enqueue.packet).toMatchObject({ + priority: 10, + dedupe_key: `repo-health:v1:triage:${REPO}:issue:12501`, + payload: { schema: "repo-task/v1", kind: "triage", issue: { number: 12501 } }, + }); + // The label is prepared once per process, and "already there" is success. + await work.ask({ text: "second" }); + expect(w.gh().filter((a) => a[2] === `repos/${REPO}/labels`).length).toBe(1); + const exists = world({ + commands: (argv) => + argv.includes(`repos/${REPO}/labels`) + ? { code: 1, stderr: 'gh: Validation Failed (HTTP 422) {"code":"already_exists"}' } + : JSON.stringify({ number: 1, html_url: "u" }), + }); + expect((await new Work(exists.ops).ask({ text: "x" })).issue).toBe(1); + const denied = world({ + commands: (argv) => + argv.includes(`repos/${REPO}/labels`) ? { code: 1, stderr: "gh: Forbidden (HTTP 403)" } : "{}", + }); + await expect(new Work(denied.ops).ask({ text: "x" })).rejects.toThrow(/label/); + expect(denied.gh().length).toBe(1); // no issue is filed if the label cannot be prepared + // The issue exists either way: a failed enqueue is said, not thrown. + const stuck = world({ + commands: (argv) => + argv[1] === "queue" + ? { code: 1, stderr: "repo-queue: broker unreachable" } + : JSON.stringify({ number: 2, html_url: "u" }), + }); + expect(await new Work(stuck.ops).ask({ text: "x" })).toEqual({ + issue: 2, + url: "u", + queued: false, + note: "filed, not queued: repo-queue: broker unreachable", + }); + for (const text of ["", " ", 5, "x".repeat(8001)]) await expect(work.ask({ text })).rejects.toThrow(OpError); + }); + + test("a reply wakes the fleet again, and only on one of his prompts", async () => { + const issue = (state: string, labels: string[]) => + JSON.stringify({ state, labels: labels.map((name) => ({ name })) }); + const w = world({ + commands: (argv) => + argv.includes("--input") && argv[5].endsWith("/comments") + ? JSON.stringify({ id: 777 }) + : argv[3] === `repos/${REPO}/issues/12501` + ? issue("closed", ["owner/prompt"]) + : "{}", + }); + const work = new Work(w.ops, undefined, () => new Date("2026-11-22T06:00:00Z")); + expect(await work.askReply({ issue: 12501, text: "also do the docs" })).toEqual({ issue: 12501, queued: true }); + expect(w.gh()).toEqual([ + [`repos/${REPO}/issues/12501`], + ["-X", "POST", `repos/${REPO}/issues/12501/comments`, "--input", "-"], + ["-X", "PATCH", `repos/${REPO}/issues/12501`, "--input", "-"], // it was closed: reopened + ]); + expect(JSON.parse(w.calls[1].stdin ?? "").body).toBe("also do the docs\n\n"); + expect(w.calls[3].packet).toMatchObject({ + priority: 10, + dedupe_key: `repo-health:v1:triage:${REPO}:issue:12501`, + }); + const other = world({ commands: () => issue("open", ["bug"]) }); + await expect(new Work(other.ops).askReply({ issue: 5, text: "x" })).rejects.toThrow( + /not one of the owner's prompts/, + ); + await expect(new Work(other.ops).askClose({ issue: 5 })).rejects.toThrow(/not one of the owner's prompts/); + expect(other.calls.length).toBe(2); + await expect(work.askReply({ issue: "12501/comments", text: "x" })).rejects.toThrow(OpError); + }); + + test("each prompt shows where it stands", async () => { + const found = (n: number, state: string, comments: number) => ({ + number: n, + title: `Owner: t${n}`, + body: `words ${n}\n\n---\nnote`, + html_url: `u${n}`, + state, + created_at: "2026-11-22T01:00:00Z", + updated_at: `2026-11-22T0${n}:00:00Z`, + comments, + }); + let commentReads = 0; + const w = world({ + commands: (argv) => { + if (argv.includes("search/issues")) + return JSON.stringify({ + items: [ + found(1, "closed", 1), + found(2, "open", 1), + found(3, "open", 0), + found(4, "open", 2), + found(5, "open", 0), + ], + }); + commentReads++; + const n = Number(/issues\/(\d+)\/comments/.exec(argv[3])?.[1]); + return JSON.stringify( + n === 4 + ? [ + { body: "fleet says", created_at: "2026-11-22T02:00:00Z" }, + { body: "and I say\n\n", created_at: "2026-11-22T03:00:00Z" }, + ] + : [{ body: "fleet says", created_at: "2026-11-22T02:00:00Z" }], + ); + }, + rows: () => [ + { dedupe_key: `repo-health:v1:triage:${REPO}:issue:3`, status: "claimed", worker: "w1" }, + { dedupe_key: `repo-health:v1:triage:${REPO}:issue:4`, status: "queued", worker: null }, + { dedupe_key: `repo-health:v1:triage:${REPO}:issue:4`, status: "done", worker: null }, + ], + }); + const work = new Work(w.ops); + const asks = await work.asks(); + expect(asks.map((a) => [a.issue, a.status, a.worker, a.text, a.replies.map((r) => r.you)])).toEqual([ + [1, "done", null, "words 1", [false]], + [2, "answered", null, "words 2", [false]], + [3, "working", "w1", "words 3", []], + [4, "queued", null, "words 4", [false, true]], // the last word is his: back in the queue + [5, "waiting", null, "words 5", []], + ]); + expect(asks[3].replies[1].text).toBe("and I say"); + // Threads are read again only when the issue has changed. + await work.asks(); + expect(commentReads).toBe(3); + }); +}); + +describe("the state kept ready", () => { + const source = () => { + let n = 0; + let fail = false; + let gate: Promise | null = null; + return { + load: async () => { + n++; + await gate; + if (fail) throw new Error("source is down"); + return { n }; + }, + reads: () => n, + break: (b: boolean) => { + fail = b; + }, + hold: () => { + let open = () => {}; + gate = new Promise((r) => { + open = r; + }); + return () => { + gate = null; + open(); + }; + }, + }; + }; + const all = (board: { ttlMs: number; load: () => Promise }) => { + const still = { ttlMs: 1e12, load: async () => "x" }; + return { + board, + sessions: still, + census: still, + asks: still, + questionCount: still, + questions: still, + prs: still, + priorities: still, + agents: still, + services: still, + more: still, + }; + }; + + test("a page never waits on a source that has been read before", async () => { + let now = 1_000_000; + const s = source(); + const docs = new Docs(all({ ttlMs: 10_000, load: s.load }), () => now); + const first = JSON.parse((await docs.doc("core")).body); + expect(first.board).toEqual({ n: 1 }); // the first read is waited for + expect(first.health.board).toEqual({ ok: true, error: null }); + now += 5_000; + await docs.doc("core"); + expect(s.reads()).toBe(1); // fresh: not read again + now += 6_000; + const release = s.hold(); + const stale = JSON.parse((await docs.doc("core")).body); // answers at once with what it has + expect(stale.board).toEqual({ n: 1 }); + expect(s.reads()).toBe(2); // and a read is under way + await docs.doc("core"); + expect(s.reads()).toBe(2); // one read at a time + release(); + await docs.refresh("board"); + expect(JSON.parse((await docs.doc("core")).body).board).toEqual({ n: 2 }); + }); + + test("a failed read keeps the last good copy and says so", async () => { + let now = 1_000_000; + const s = source(); + const docs = new Docs(all({ ttlMs: 10_000, load: s.load }), () => now); + const good = await docs.doc("core"); + s.break(true); + now += 11_000; + await docs.refresh("board"); + const after = await docs.doc("core"); + const body = JSON.parse(after.body); + expect(body.board).toEqual({ n: 1 }); + expect(body.health.board).toEqual({ ok: false, error: "source is down" }); + expect(after.etag).not.toBe(good.etag); + expect(after.asOf).toBe(now - 1_000); // the board is a second past its interval + }); + + test("an unchanged document keeps its tag, and nothing is read when nobody is looking", async () => { + let now = 1_000_000; + let reads = 0; + const docs = new Docs(all({ ttlMs: 10_000, load: async () => (reads++, { same: true }) }), () => now); + const a = await docs.doc("core"); + now += 11_000; + await docs.refresh("board"); + const b = await docs.doc("core"); + expect(b.etag).toBe(a.etag); + expect(b.asOf).toBeGreaterThan(a.asOf); + expect(reads).toBe(2); + now += 11_000; + docs.tick(); // someone looked 11 seconds ago: refresh + await docs.refresh("board"); + expect(reads).toBe(3); + now += 11 * 60_000; + docs.tick(); // nobody has looked for eleven minutes: leave the sources alone + await docs.refresh("more"); + expect(reads).toBe(3); + expect(() => new Docs({ board: { ttlMs: 1, load: async () => 1 } })).toThrow(/no loader/); + }); +}); + +describe("the interface's endpoints", () => { + function deps(who: "owner" | 401 = "owner") { + const w = world({ + rows: (st) => (st.sql.startsWith("UPDATE") ? { affected: 1 } : [{ priority: 30 }]), + dash: () => [], + }); + const work = new Work(w.ops, async () => store()); + const docs = new Docs(loaders(w.ops, work, [{ group: "Overview", pages: [] }])); + const audited: Record[] = []; + const d: Deps = { + cfg: CFG, + ops: w.ops, + docs, + actions: actions(w.ops, work), + identify: async () => { + if (who === "owner") return { via: "cloudflare-access", email: "drewrypope@gmail.com" }; + throw new (await import("../src/auth.ts")).AuthError(401, "sign-in required"); + }, + audit: async (e) => { + audited.push(e); + }, + }; + return { d, w, audited, docs }; + } + const get = (path: string, headers: Record = {}) => + new Request(`https://pm.security.cab${path}`, { headers: { host: "pm.security.cab", ...headers } }); + const post = (path: string, body: unknown) => + new Request(`https://pm.security.cab${path}`, { + method: "POST", + body: JSON.stringify(body), + headers: { + host: "pm.security.cab", + "content-type": "application/json", + "x-pm-console": "1", + origin: "https://pm.security.cab", + }, + }); + + test("a document comes with a tag, is not sent twice, and is compressed", async () => { + const { d } = deps(); + const res = await handle(get("/console/api/doc/questions"), d); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.questions.total).toBe(4); + expect(JSON.stringify(body)).not.toContain(TOKEN); + const etag = res.headers.get("etag") ?? ""; + expect(etag.length).toBeGreaterThan(10); + expect(Number(res.headers.get("x-as-of"))).toBeGreaterThan(0); + const again = await handle(get("/console/api/doc/questions", { "if-none-match": etag }), d); + expect([again.status, await again.text()]).toEqual([304, ""]); + expect(Number(again.headers.get("x-as-of"))).toBeGreaterThan(0); + const packed = await handle(get("/console/api/doc/questions", { "accept-encoding": "gzip, br" }), d); + expect(packed.headers.get("content-encoding")).toBe("gzip"); + const raw = new Uint8Array(await packed.arrayBuffer()); + expect(JSON.parse(gunzipSync(raw).toString()).questions.total).toBe(4); + expect(raw.byteLength).toBeLessThan(JSON.stringify(body).length / 2); + expect((await handle(get("/console/api/doc/secrets"), d)).status).toBe(404); + expect((await handle(get("/console/api/doc/core"), deps(401).d)).status).toBe(401); + }); + + 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, + // so the next document already shows it. + const boardReads = () => w.sqls.filter((batch) => batch.length === 4).length; + await handle(get("/console/api/doc/core"), d); + const readsBefore = boardReads(); + const res = await handle(post("/console/api/act", { kind: "task.move", args: { task: 21016, to: "first" } }), d); + expect(await res.json()).toEqual({ ok: true, result: { task: 21016, priority: 10 } }); + expect(boardReads()).toBe(readsBefore + 1); + expect(w.sqls.flat().some((s) => s.sql.startsWith("UPDATE tasks SET priority"))).toBe(true); + await handle( + post("/console/api/act", { kind: "need.comment", args: { ref: `${REPO}#5`, text: "private words" } }), + d, + ); + expect(audited.map((e) => [e.action, e.phase, e.args])).toEqual([ + ["task.move", "start", { task: 21016, to: "first" }], + ["task.move", "done", { task: 21016, to: "first" }], + ["need.comment", "start", { ref: `${REPO}#5` }], + ["need.comment", "done", { ref: `${REPO}#5` }], + ]); + expect(JSON.stringify(audited)).not.toContain("private words"); + const core = await (await handle(get("/console/api/doc/core"), d)).json(); + expect(core.acts.map((a: { kind: string; status: string }) => [a.kind, a.status])).toEqual([ + ["need.comment", "done"], + ["task.move", "done"], + ]); + // Unknown actions, inherited names and bad arguments run nothing. + const before = w.calls.length; + for (const body of [ + { kind: "task.delete", args: {} }, + { kind: "constructor", args: {} }, + { kind: "toString", args: {} }, + { args: {} }, + { kind: "task.move", args: [] }, + { kind: "task.move", args: { task: 1, to: "up" } }, + ]) { + expect((await handle(post("/console/api/act", body), d)).status).toBe(400); + } + expect(w.calls.length).toBe(before); + const failed = (await (await handle(get("/console/api/doc/core"), d)).json()).acts[0]; + expect([failed.kind, failed.status]).toEqual(["task.move", "failed"]); + await expect(perform(actions(w.ops, new Work(w.ops)), deps().docs, "__proto__", {})).rejects.toThrow( + /not an action/, + ); + }); + + test("the front door is the app, the dashboard's pages are compressed on the way", async () => { + const { d } = deps(); + const big = "

row

".repeat(2000); + const stream = "data: x\n\n".repeat(500); + d.upstream = async (url) => + new Response(url.includes("/frag/") || url.endsWith("/freshness/stream") ? stream : big, { + headers: { + "content-type": + url.includes("/frag/") || url.endsWith("/stream") ? "text/event-stream" : "text/html; charset=utf-8", + }, + }); + const home = await handle(get("/"), d); + expect([home.status, home.headers.get("location")]).toEqual([302, "/console/"]); + expect((await handle(get("/"), deps(401).d)).status).toBe(401); + // The dashboard's own home is still there, one link away. + expect(await (await handle(get("/?dashboard"), d)).text()).toBe(big); + const gz = { "accept-encoding": "gzip" }; + const page = await handle(get("/attention", gz), d); + expect(page.headers.get("content-encoding")).toBe("gzip"); + expect(gunzipSync(new Uint8Array(await page.arrayBuffer())).toString()).toBe(big); + const frag = await handle(get("/frag/attention/queues", gz), d); + expect(frag.headers.get("content-encoding")).toBe("gzip"); + expect(frag.headers.get("content-type")).toBe("text/event-stream"); + expect(gunzipSync(new Uint8Array(await frag.arrayBuffer())).toString()).toBe(stream); + // A stream that stays open is passed through as it comes. + const live = await handle(get("/freshness/stream", gz), d); + expect(live.headers.get("content-encoding")).toBeNull(); + expect(await live.text()).toBe(stream); + // A client that did not ask for gzip gets the bytes as they are. + expect(await (await handle(get("/attention"), d)).text()).toBe(big); + }); +}); diff --git a/pm-stack/systemd/pm-console-expose.service b/pm-stack/systemd/pm-console-expose.service new file mode 100644 index 0000000000..a455c93d1d --- /dev/null +++ b/pm-stack/systemd/pm-console-expose.service @@ -0,0 +1,12 @@ +[Unit] +Description=PM console — keep the public address as declared (sign-in methods, policy, route) (pm-stack) +Documentation=https://github.com/developing-today/code/tree/main/pm-stack/console +After=network-online.target + +[Service] +Type=oneshot +# Changes only what is not already so. When the Google sign-in secrets +# appear in the secret store, the next run turns Google sign-in on. +ExecStart=/run/current-system/sw/bin/python3 %h/git/code/pm-stack/console/scripts/expose.py +Environment=PATH=%h/.local/bin:/run/current-system/sw/bin:/etc/profiles/per-user/%u/bin:/usr/bin:/bin +TimeoutStartSec=600 diff --git a/pm-stack/systemd/pm-console-expose.timer b/pm-stack/systemd/pm-console-expose.timer new file mode 100644 index 0000000000..3d93f938fd --- /dev/null +++ b/pm-stack/systemd/pm-console-expose.timer @@ -0,0 +1,10 @@ +[Unit] +Description=PM console — re-check the public address every quarter hour (pm-stack) + +[Timer] +OnBootSec=5min +OnUnitActiveSec=15min +RandomizedDelaySec=60 + +[Install] +WantedBy=timers.target diff --git a/pm-stack/systemd/pm-console.service b/pm-stack/systemd/pm-console.service index c62922d647..662a353f15 100644 --- a/pm-stack/systemd/pm-console.service +++ b/pm-stack/systemd/pm-console.service @@ -3,6 +3,9 @@ Description=PM console — queue, priorities, agents, services and pull requests After=network-online.target [Service] +# The management plane has to answer while the fleet is compiling: under +# contention this unit gets nine times the processor share of a default one. +CPUWeight=900 Type=simple WorkingDirectory=%h/git/code/pm-stack/console ExecStart=/run/current-system/sw/bin/bun run src/server.ts