From fc1acb50968bb3ac993ee0fcd040217e6f929393 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 23:31:10 +0200 Subject: [PATCH 01/57] test: each of today's six attention kinds is an Inbox item with today's key and tone (#768) --- ui/src/model/inbox.test.ts | 372 ++++++++++++++++++ .../{attention.test.ts => inbox.test.ts-e} | 0 ui/src/model/inbox.ts | 19 + 3 files changed, 391 insertions(+) create mode 100644 ui/src/model/inbox.test.ts rename ui/src/model/{attention.test.ts => inbox.test.ts-e} (100%) create mode 100644 ui/src/model/inbox.ts diff --git a/ui/src/model/inbox.test.ts b/ui/src/model/inbox.test.ts new file mode 100644 index 000000000..3fd8528a3 --- /dev/null +++ b/ui/src/model/inbox.test.ts @@ -0,0 +1,372 @@ +import { describe, expect, it } from "vitest"; + +import { inboxItems, inboxPageOf } from "./inbox"; +import type { ConsoleEvent } from "./events"; +import type { WorkerDevice, WorkerView } from "./workers"; + +const NOW = Date.parse("2026-10-02T12:00:00Z"); +const GIB = 1024 ** 3; + +function worker(overrides: Partial = {}): WorkerView { + return { + catalog: [], + connection: "connected", + devices: [], + drained: false, + id: "wrk_1", + lastSeenAt: NOW, + leases: [], + ...overrides, + }; +} + +function device(id: string, overrides: Partial = {}): WorkerDevice { + return { + physical: false, + id, + mode: "full", + servesDefaultMode: true, + spec: { physical: false, model: "iPhone 16", osVersion: "18.4", platform: "ios" }, + state: "ready", + ...overrides, + }; +} + +function capacity(ramBudget?: { usedBytes: number; limitBytes: number; overLimit: boolean }) { + const entry = { + atRamBudget: false, + limit: 4, + maxRunning: 4, + overLimit: false, + reserved: 0, + running: 1, + used: 1, + }; + return { + android: { ...entry, warm: 0 }, + global: { maxRunning: 4, overLimit: false, reserved: 0, running: 1, warm: 0 }, + ios: { ...entry, warm: 0 }, + ...(ramBudget === undefined ? {} : { ramBudget }), + }; +} + +function event(seq: number, name: string, at: number, payload: unknown = {}): ConsoleEvent { + return { event: name, id: `e${seq}`, payload, seq, timestamp: at }; +} + +function summary(workers: readonly WorkerView[]): string[] { + return inboxItems(workers).map((item) => + [item.worker.id, "device" in item ? item.device.id : "-", item.condition].join(" "), + ); +} + +function pageOf( + workers: readonly WorkerView[], + key?: string, + events: readonly ConsoleEvent[] = [], +) { + return inboxPageOf({ events, key, now: NOW, workers }); +} + +function shownOf(page: ReturnType) { + if (typeof page.shown !== "object") throw new Error("no item is shown"); + return page.shown; +} + +function factsOf(w: WorkerView, key: string) { + return shownOf(pageOf([w], key)).facts; +} + +describe("the Inbox items", () => { + it("hold a disconnected, an incompatible and a drained worker, one item per condition", () => { + const workers = [ + worker({ id: "wrk_ok" }), + worker({ connection: "disconnected", id: "wrk_gone" }), + worker({ connection: "incompatible", id: "wrk_old" }), + worker({ drained: true, id: "wrk_drained" }), + worker({ connection: "disconnected", drained: true, id: "wrk_both" }), + ]; + + expect(summary(workers)).toEqual([ + "wrk_gone - disconnected", + "wrk_old - incompatible", + "wrk_drained - drained", + "wrk_both - disconnected", + "wrk_both - drained", + ]); + }); + + it("hold a quarantined device and a stalled device, not one mid-transition", () => { + const workers = [ + worker({ + devices: [ + device("dev_ready"), + device("dev_quarantined", { state: "quarantined" }), + device("dev_stuck", { stalled: true, state: "reclaiming", transitionAgeMs: 300_000 }), + device("dev_busy", { state: "provisioning", transitionAgeMs: 2_000 }), + ], + }), + ]; + + expect(summary(workers)).toEqual([ + "wrk_1 dev_quarantined quarantined", + "wrk_1 dev_stuck stalled", + ]); + }); + + it("hold a quarantined physical device like any quarantined device", () => { + const physical: WorkerDevice = { + class: "phone", + id: "dev_phone", + physical: true, + servesDefaultMode: false, + spec: { model: "iPhone 15 Pro", osVersion: "18.4", physical: true, platform: "ios" }, + state: "quarantined", + }; + + expect(summary([worker({ devices: [physical] })])).toEqual(["wrk_1 dev_phone quarantined"]); + }); + + it("hold a worker over its RAM budget, not one under it or with no budget", () => { + const workers = [ + worker({ + capacity: capacity({ limitBytes: 12 * GIB, overLimit: true, usedBytes: 13 * GIB }), + id: "wrk_over", + }), + worker({ + capacity: capacity({ limitBytes: 12 * GIB, overLimit: false, usedBytes: 4 * GIB }), + id: "wrk_under", + }), + worker({ capacity: capacity(), id: "wrk_none" }), + worker({ id: "wrk_unread" }), + ]; + + expect(summary(workers)).toEqual(["wrk_over - over RAM budget"]); + }); + + it("lose an item when its condition clears", () => { + const quarantined = device("dev_1", { state: "quarantined" }); + const stalled = device("dev_2", { stalled: true, state: "provisioning" }); + const ramBudget = { limitBytes: 12 * GIB, usedBytes: 13 * GIB }; + const before = worker({ + capacity: capacity({ ...ramBudget, overLimit: true }), + connection: "disconnected", + devices: [quarantined, stalled], + drained: true, + }); + expect(inboxItems([before])).toHaveLength(5); + + const cleared: [string, WorkerView][] = [ + ["disconnected", { ...before, connection: "connected" }], + ["drained", { ...before, drained: false }], + ["over RAM budget", { ...before, capacity: capacity({ ...ramBudget, overLimit: false }) }], + ["quarantined", { ...before, devices: [{ ...quarantined, state: "ready" }, stalled] }], + ["stalled", { ...before, devices: [quarantined, device("dev_2", { state: "ready" })] }], + ]; + for (const [condition, after] of cleared) { + const conditions = inboxItems([after]).map((item) => item.condition); + expect(conditions, condition).toHaveLength(4); + expect(conditions, condition).not.toContain(condition); + } + }); +}); + +describe("the Inbox page", () => { + it("lists a row per item, naming the worker or the device on its worker", () => { + const page = pageOf([ + worker({ connection: "disconnected", id: "wrk/1", label: "mac-mini-1" }), + worker({ devices: [device("dev_q", { state: "quarantined" })], id: "wrk_2" }), + ]); + + expect(page.rows.map((row) => [row.word, row.tone, row.subject, row.to])).toEqual([ + ["disconnected", "error", "mac-mini-1", "/inbox/wrk%2F1%2Fdisconnected"], + ["quarantined", "error", "iPhone 16 on wrk_2", "/inbox/wrk_2%2Fdev_q%2Fquarantined"], + ]); + }); + + it("shows the first item when the URL names none", () => { + const page = pageOf([worker({ drained: true }), worker({ drained: true, id: "wrk_2" })]); + + expect(page.named).toBe(false); + expect(shownOf(page).key).toBe("wrk_1/drained"); + }); + + it("shows the item the URL names", () => { + const page = pageOf( + [worker({ drained: true }), worker({ drained: true, id: "wrk_2" })], + "wrk_2/drained", + ); + + expect(page.named).toBe(true); + expect(shownOf(page).key).toBe("wrk_2/drained"); + }); + + it("says an item the URL names is resolved once the daemon stops reporting it", () => { + const page = pageOf([worker()], "wrk_1/drained"); + + expect(page.shown).toBe("resolved"); + }); + + it("shows nothing when the Inbox is empty and the URL names nothing", () => { + const page = pageOf([worker()]); + + expect(page.rows).toEqual([]); + expect(page.shown).toBeUndefined(); + }); + + it("titles a worker item by the worker and a device item by its model and runtime", () => { + const workers = [ + worker({ drained: true, label: "mac-mini-1" }), + worker({ devices: [device("dev_q", { state: "quarantined" })], id: "wrk_2" }), + ]; + + expect(shownOf(pageOf(workers)).title).toBe("mac-mini-1"); + expect(shownOf(pageOf(workers, "wrk_2/dev_q/quarantined")).title).toBe("iPhone 16 18.4"); + }); + + it("gives a disconnected worker the time since it was last seen", () => { + const w = worker({ connection: "disconnected", lastSeenAt: NOW - 100_000 }); + + expect(factsOf(w, "wrk_1/disconnected")).toEqual([ + { label: "Last seen", value: "1 min 40 s ago" }, + ]); + }); + + it("gives an incompatible worker both protocol ranges", () => { + const w = worker({ + connection: "incompatible", + protocol: { gateway: { max: 3, min: 2 }, worker: { max: 1, min: 1 } }, + }); + + expect(factsOf(w, "wrk_1/incompatible")).toEqual([ + { label: "Gateway protocol", value: "2–3" }, + { label: "Worker protocol", value: "1" }, + ]); + }); + + it("gives a drained worker the leases it still holds", () => { + const lease = { deviceId: "d", grantedAt: NOW, id: "l" } as unknown as never; + const w = worker({ drained: true, leases: [lease] }); + + expect(factsOf(w, "wrk_1/drained")).toEqual([{ label: "Leases still held", value: "1" }]); + }); + + it("gives a worker over its RAM budget what it uses and its limit", () => { + const ramBudget = { limitBytes: 12 * GIB, overLimit: true, usedBytes: 13 * GIB }; + + expect(factsOf(worker({ capacity: capacity(ramBudget) }), "wrk_1/ram")).toEqual([ + { label: "Used", value: "13.00 GiB" }, + { label: "Limit", value: "12.00 GiB" }, + ]); + }); + + it("gives a stalled device its id, state and time in that state", () => { + const w = worker({ + devices: [ + device("dev_stuck", { stalled: true, state: "provisioning", transitionAgeMs: 90_000 }), + ], + lastSeenAt: NOW - 10_000, + }); + + expect(factsOf(w, "wrk_1/dev_stuck/stalled")).toEqual([ + { label: "Device", value: "dev_stuck" }, + { label: "State", value: "provisioning" }, + { label: "In this state for", value: "1 min 40 s" }, + ]); + }); + + it("gives a quarantined device no time in its state", () => { + const w = worker({ devices: [device("dev_q", { state: "quarantined" })] }); + + expect(factsOf(w, "wrk_1/dev_q/quarantined")).toEqual([ + { label: "Device", value: "dev_q" }, + { label: "State", value: "quarantined" }, + ]); + }); + + it("ends a quarantined device's facts with Cause for each kind", () => { + const cases = [ + [ + { kind: "purge-failed", message: "Error: erase failed" }, + "Purge failed: Error: erase failed", + ], + [ + { kind: "shutdown-failed", message: "Error: no shutdown" }, + "Shutdown failed: Error: no shutdown", + ], + [{ kind: "delete-failed", message: "Error: no delete" }, "Delete failed: Error: no delete"], + [{ kind: "purge-failed" }, "Purge failed"], + [{ kind: "stalled", stalledState: "provisioning" }, "Stalled while provisioning"], + [{ kind: "stalled", stalledState: "reclaiming" }, "Stalled while reclaiming"], + ] as const; + + for (const [quarantineCause, text] of cases) { + const w = worker({ + devices: [Object.assign(device("dev_q", { state: "quarantined" }), { quarantineCause })], + }); + + expect(factsOf(w, "wrk_1/dev_q/quarantined"), text).toEqual([ + { label: "Device", value: "dev_q" }, + { label: "State", value: "quarantined" }, + { label: "Cause", value: text }, + ]); + } + }); + + it("gives a stalled device that is not quarantined no Cause, even when its record still carries one", () => { + const w = worker({ + devices: [ + Object.assign(device("dev_stuck", { stalled: true, state: "reclaiming" }), { + quarantineCause: { kind: "purge-failed", message: "Error: erase failed" }, + }), + ], + }); + + const labels = factsOf(w, "wrk_1/dev_stuck/stalled").map((fact) => fact.label); + + expect(labels).not.toContain("Cause"); + }); + + it("gives a stalled device on a disconnected worker no time in its state", () => { + // why: a gateway keeps a disconnected worker's devices as last reported, with an age it can no + // longer count from. + const w = worker({ + connection: "disconnected", + devices: [ + device("dev_stuck", { stalled: true, state: "reclaiming", transitionAgeMs: 90_000 }), + ], + }); + + const labels = factsOf(w, "wrk_1/dev_stuck/stalled").map((fact) => fact.label); + + expect(labels).toEqual(["Device", "State"]); + }); + + it("lists the last hour's events naming the worker or the device, newest first", () => { + const w = worker({ devices: [device("dev_1", { state: "quarantined" })], drained: true }); + const events = [ + event(1, "worker.drain-started", NOW - 50 * 60_000, { workerId: "wrk_1" }), + event(2, "device.quarantined", NOW - 5 * 60_000, { deviceId: "dev_1" }), + event(3, "lease.granted", NOW - 60_000, { deviceId: "dev_other" }), + event(4, "worker.drain-started", NOW - 2 * 60 * 60_000, { workerId: "wrk_1" }), + event(5, "worker.rejected", NOW - 60_000, { workerId: "wrk_1" }), + ]; + + const ofWorker = shownOf(pageOf([w], "wrk_1/drained", events)); + const ofDevice = shownOf(pageOf([w], "wrk_1/dev_1/quarantined", events)); + + expect(ofWorker.events.map((entry) => entry.key)).toEqual(["e1"]); + expect(ofDevice.events.map((entry) => entry.key)).toEqual(["e2", "e1"]); + expect(ofDevice.events[0]).toMatchObject({ + name: "device.quarantined", + to: "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/activity/e2", + tone: "error", + }); + }); + + it("links each item to its worker's page", () => { + const page = pageOf([worker({ drained: true, id: "wrk/1", label: "mac-mini-1" })]); + + expect(shownOf(page).worker).toEqual({ name: "mac-mini-1", to: "/fleet/wrk%2F1" }); + }); +}); diff --git a/ui/src/model/attention.test.ts b/ui/src/model/inbox.test.ts-e similarity index 100% rename from ui/src/model/attention.test.ts rename to ui/src/model/inbox.test.ts-e diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts new file mode 100644 index 000000000..1f88b82f8 --- /dev/null +++ b/ui/src/model/inbox.ts @@ -0,0 +1,19 @@ +import type { AttentionItem, AttentionPage } from "./attention"; +import type { ConsoleEvent } from "./events"; +import type { WorkerView } from "./workers"; + +export type InboxItem = AttentionItem; +export type InboxPage = AttentionPage; + +export function inboxItems(_workers: readonly WorkerView[]): readonly InboxItem[] { + return []; +} + +export function inboxPageOf(_input: { + readonly workers: readonly WorkerView[]; + readonly events: readonly ConsoleEvent[]; + readonly now: number; + readonly key: string | undefined; +}): InboxPage { + return { named: false, rows: [], shown: undefined }; +} From 76f6d08c7ce64007b184555778ccf11b4d016e3a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 00:07:00 +0200 Subject: [PATCH 02/57] feat(console): Attention becomes Inbox at /inbox (#768) --- e2e/console/fixtures.ts | 2 +- .../{attention.spec.ts => inbox.spec.ts} | 90 ++--- e2e/console/shell.spec.ts | 6 +- ui/src/app/routes.test.ts | 2 +- ui/src/app/routes.ts | 4 +- ui/src/app/shell.tsx | 8 +- ui/src/ds/icon.tsx | 2 +- ui/src/model/attention.ts | 279 ------------- ui/src/model/event-list.test.ts | 4 +- ui/src/model/event-list.ts | 6 +- ui/src/model/inbox.test.ts-e | 372 ------------------ ui/src/model/inbox.ts | 278 ++++++++++++- ui/src/model/overview.test.ts | 6 +- ui/src/model/overview.ts | 8 +- ui/src/model/paths.test.ts | 2 +- ui/src/model/paths.ts | 4 +- .../attention.css => inbox/inbox.css} | 22 +- .../{attention => inbox}/index.test.tsx | 22 +- ui/src/screens/{attention => inbox}/index.tsx | 50 ++- ui/src/state/{attention.ts => inbox.ts} | 19 +- ui/src/state/shell.ts | 6 +- 21 files changed, 396 insertions(+), 796 deletions(-) rename e2e/console/{attention.spec.ts => inbox.spec.ts} (83%) delete mode 100644 ui/src/model/attention.ts delete mode 100644 ui/src/model/inbox.test.ts-e rename ui/src/screens/{attention/attention.css => inbox/inbox.css} (79%) rename ui/src/screens/{attention => inbox}/index.test.tsx (71%) rename ui/src/screens/{attention => inbox}/index.tsx (65%) rename ui/src/state/{attention.ts => inbox.ts} (73%) diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 7c8c2a1e6..04de3c645 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -503,7 +503,7 @@ export async function signIn(page: Page, token: string): Promise { export const NAV = [ { label: "Overview", path: "/" }, - { label: "Attention", path: "/attention" }, + { label: "Inbox", path: "/inbox" }, { label: "Fleet", path: "/fleet" }, { label: "Leases", path: "/leases" }, { label: "Queue", path: "/queue" }, diff --git a/e2e/console/attention.spec.ts b/e2e/console/inbox.spec.ts similarity index 83% rename from e2e/console/attention.spec.ts rename to e2e/console/inbox.spec.ts index 9ea9fd69a..91974c694 100644 --- a/e2e/console/attention.spec.ts +++ b/e2e/console/inbox.spec.ts @@ -13,7 +13,7 @@ import { test, } from "./fixtures.js"; -/** What `GET /v1/workers` says, as far as these tests read. */ +/** why: What `GET /v1/workers` says, as far as these tests read. */ interface WorkerView { readonly id: string; readonly label?: string; @@ -30,7 +30,7 @@ interface WorkerView { const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; -/** The fake driver's script once its reclaim fails, so a released device is quarantined. */ +/** why: The fake driver's script once its reclaim fails, so a released device is quarantined. */ const FAILING_RECLAIM = { ios: { ...IOS, failures: { reclaim: { message: "erase failed", type: "generic" as const } } }, }; @@ -56,7 +56,7 @@ async function workers(daemon: RunningDaemon): Promise { } /** - * Waits, asking every 20 ms, until the daemon's own `GET /v1/workers` says what `predicate` + * why: Waits, asking every 20 ms, until the daemon's own `GET /v1/workers` says what `predicate` * looks for. The console's second starts there: it cannot show a fact before its daemon has it. */ async function untilTheDaemonSays( @@ -88,7 +88,7 @@ async function lease(daemon: RunningDaemon, agent: string): Promise<{ id: string return (granted.json as { lease: { id: string } }).lease; } -/** Leases a device, then releases it with a driver whose reclaim fails: it is quarantined. */ +/** why: Leases a device, then releases it with a driver whose reclaim fails: it is quarantined. */ async function quarantineOne(daemon: RunningDaemon): Promise { const held = await lease(daemon, "console-e2e-quarantine"); await daemon.writeDriverScript(FAILING_RECLAIM); @@ -100,7 +100,7 @@ async function quarantineOne(daemon: RunningDaemon): Promise { } /** - * Leaves a device `provisioning` with nothing working on it, as a daemon that stops mid-boot + * why: Leaves a device `provisioning` with nothing working on it, as a daemon that stops mid-boot * does: a lease starts a boot the driver takes two minutes over, and the daemon stops while * it runs. While the boot runs it is a live operation, never a stall; once the daemon is back * nothing drives it any more. `beforeStart` runs while the daemon is down. @@ -132,17 +132,17 @@ async function strandProvisioning( await daemon.start(); } -async function openAttention(page: Page, daemon: RunningDaemon): Promise { +async function openInbox(page: Page, daemon: RunningDaemon): Promise { await page.goto(daemon.url); await signIn(page, daemon.tokens.operator); // why: a phone folds the navigation into a menu, so the page is opened by its address. await expect(page.getByRole("heading", { level: 1, name: "Overview" })).toBeVisible(); - await page.goto(new URL("/attention", daemon.url).href); - await expect(page.getByRole("heading", { level: 1, name: "Attention" })).toBeVisible(); + await page.goto(new URL("/inbox", daemon.url).href); + await expect(page.getByRole("heading", { level: 1, name: "Inbox" })).toBeVisible(); } function rows(page: Page): Locator { - return page.getByRole("list", { name: "Needs attention" }).getByRole("link"); + return page.getByRole("list", { name: "Needs you" }).getByRole("link"); } function item(page: Page, condition: string, subject: string): Locator { @@ -155,22 +155,22 @@ function facts(page: Page): Locator { return page.getByRole("group", { name: "Facts" }); } -/** Whether the page itself scrolls sideways. */ +/** why: Whether the page itself scrolls sideways. */ async function hasHorizontalScroll(page: Page): Promise { return page.evaluate( () => document.documentElement.scrollWidth > document.documentElement.clientWidth, ); } -test.describe("the attention view", () => { - test("draining a worker adds it to the attention view within a second", async ({ page }) => { +test.describe("the Inbox view", () => { + test("draining a worker adds it to the Inbox view within a second", async ({ page }) => { const fleet = await startFleet([ { driverScript: { ios: IOS }, label: "worker-a" }, { driverScript: { ios: IOS }, label: "worker-b" }, ]); try { - await openAttention(page, fleet.gateway); - await expect(page.getByText("Nothing needs attention.")).toBeVisible(); + await openInbox(page, fleet.gateway); + await expect(page.getByText("Nothing needs you.")).toBeVisible(); const b = (await workers(fleet.gateway)).find((view) => view.label === "worker-b"); expect((await fleet.gateway.cli(["worker", "drain", b?.id ?? ""])).code).toBe(0); @@ -183,10 +183,10 @@ test.describe("the attention view", () => { await expect(drained).toBeVisible({ timeout: 1_000 }); await expect(drained).toHaveAttribute( "href", - `/attention/${encodeURIComponent(`${b?.id}/drained`)}`, + `/inbox/${encodeURIComponent(`${b?.id}/drained`)}`, ); await expect(rows(page)).toHaveCount(1); - await expect(page).toHaveURL(/\/attention$/); + await expect(page).toHaveURL(/\/inbox$/); await expect(page.getByRole("heading", { level: 2, name: "worker-b" })).toBeVisible(); await expect(page.getByRole("link", { name: "Open worker" })).toHaveAttribute( "href", @@ -208,7 +208,7 @@ test.describe("the attention view", () => { try { const [a] = await workers(fleet.gateway); expect((await fleet.gateway.cli(["worker", "drain", a?.id ?? ""])).code).toBe(0); - await openAttention(page, fleet.gateway); + await openInbox(page, fleet.gateway); const drained = item(page, "drained", "worker-a"); await expect(drained).toBeVisible(); @@ -216,31 +216,31 @@ test.describe("the attention view", () => { await untilTheDaemonSays(fleet.gateway, (views) => views[0]?.drained === false); await expect(drained).toHaveCount(0, { timeout: 1_000 }); - await expect(page.getByText("Nothing needs attention.")).toBeVisible(); + await expect(page.getByText("Nothing needs you.")).toBeVisible(); } finally { await disposeFleet(fleet); } }); - test("an item named in the URL that stops needing attention says Resolved. with a link back", async ({ + test("an item named in the URL that leaves the Inbox says Resolved. with a link back", async ({ page, }) => { const fleet = await startFleet([{ driverScript: { ios: IOS }, label: "worker-a" }]); try { const [a] = await workers(fleet.gateway); expect((await fleet.gateway.cli(["worker", "drain", a?.id ?? ""])).code).toBe(0); - await openAttention(page, fleet.gateway); + await openInbox(page, fleet.gateway); await item(page, "drained", "worker-a").click(); - await expect(page).toHaveURL(/\/attention\/.+/); + await expect(page).toHaveURL(/\/inbox\/.+/); await expect(page.getByRole("heading", { level: 2, name: "worker-a" })).toBeVisible(); expect((await fleet.gateway.cli(["worker", "undrain", a?.id ?? ""])).code).toBe(0); await untilTheDaemonSays(fleet.gateway, (views) => views[0]?.drained === false); await expect(page.getByText("Resolved.")).toBeVisible({ timeout: 1_000 }); - await page.getByRole("link", { name: "Back to Attention" }).click(); - await expect(page).toHaveURL(/\/attention$/); - await expect(page.getByText("Nothing needs attention.")).toBeVisible(); + await page.getByRole("link", { name: "Back to Inbox" }).click(); + await expect(page).toHaveURL(/\/inbox$/); + await expect(page.getByText("Nothing needs you.")).toBeVisible(); } finally { await disposeFleet(fleet); } @@ -252,8 +252,8 @@ test.describe("the attention view", () => { { driverScript: { ios: IOS }, label: "worker-b" }, ]); try { - await openAttention(page, fleet.gateway); - await expect(page.getByText("Nothing needs attention.")).toBeVisible(); + await openInbox(page, fleet.gateway); + await expect(page.getByText("Nothing needs you.")).toBeVisible(); await (fleet.workers[1] as RunningDaemon).stop(); await untilTheDaemonSays( @@ -278,7 +278,7 @@ test.describe("the attention view", () => { const fleet = { gateway, workers: [] as RunningDaemon[] }; let hangUp = () => {}; try { - // Joined by hand rather than with `startFleet`, which has no way to pass the worker the + // why: Joined by hand rather than with `startFleet`, which has no way to pass the worker the // stall threshold. const worker = await startDaemon("worker", { ...STALLING, @@ -296,7 +296,7 @@ test.describe("the attention view", () => { await quarantineOne(worker); await strandProvisioning(worker); let devices: WorkerView["devices"] = []; - // A stall starts with no event, so the gateway learns of it on its next periodic read of + // why: A stall starts with no event, so the gateway learns of it on its next periodic read of // the worker, every 30 seconds. await untilTheDaemonSays( fleet.gateway, @@ -313,7 +313,7 @@ test.describe("the attention view", () => { const quarantined = devices.find((device) => device.state === "quarantined"); const stalled = devices.find((device) => device.stalled === true); - await openAttention(page, fleet.gateway); + await openInbox(page, fleet.gateway); await expect(item(page, "incompatible", "old-worker")).toBeVisible(); await item(page, "incompatible", "old-worker").click(); @@ -341,7 +341,7 @@ test.describe("the attention view", () => { const { limitBytes } = (status.json as { capacity: { ramBudget: { limitBytes: number } } }) .capacity.ramBudget; await quarantineOne(host); - // Back with each iOS device costing more than the whole budget: the devices it already + // why: Back with each iOS device costing more than the whole budget: the devices it already // has put it over. await strandProvisioning(host, async () => { const set = await host.cli([ @@ -365,10 +365,10 @@ test.describe("the attention view", () => { }); const quarantined = view?.devices.find((device) => device.state === "quarantined"); const stalled = view?.devices.find((device) => device.state === "provisioning"); - // Past its one-second threshold, and nothing works on it since the restart. + // why: Past its one-second threshold, and nothing works on it since the restart. expect(stalled?.stalled, "the stranded device is reported stalled").toBe(true); - await openAttention(page, host); + await openInbox(page, host); const name = view?.id ?? ""; await expect(item(page, "quarantined", `iPhone 16 on ${name}`)).toBeVisible(); @@ -389,7 +389,7 @@ test.describe("the attention view", () => { } }); - test("the attention count shows in the shell from every view", async ({ page }) => { + test("the Inbox count shows in the shell from every view", async ({ page }) => { const gateway = await startDaemon("gateway"); const hangUps: (() => void)[] = []; try { @@ -402,19 +402,19 @@ test.describe("the attention view", () => { await page.goto(gateway.url); await signIn(page, gateway.tokens.operator); - const attention = page + const inboxLink = page .getByRole("navigation", { name: "Console" }) - .getByRole("link", { name: /^Attention/ }); + .getByRole("link", { name: /^Inbox/ }); for (const label of NAV_LABELS) { await page .getByRole("navigation", { name: "Console" }) .getByRole("link", { name: label }) .click(); await expect(page.getByRole("heading", { level: 1, name: label })).toBeVisible(); - await expect(attention).toHaveAccessibleName("Attention 2 items"); + await expect(inboxLink).toHaveAccessibleName("Inbox 2 items"); } - // One worker hangs up and is removed: its item goes, and one from the count. + // why: One worker hangs up and is removed: its item goes, and one from the count. hangUps.shift()?.(); await untilTheDaemonSays(gateway, (views) => views.some((view) => view.id === "wrk_old_1" && view.connection === "disconnected"), @@ -422,14 +422,14 @@ test.describe("the attention view", () => { const removed = await gateway.cli(["worker", "remove", "wrk_old_1"]); expect(removed.code, removed.stderr).toBe(0); await untilTheDaemonSays(gateway, (views) => views.length === 1); - await expect(attention).toHaveAccessibleName("Attention 1 item"); + await expect(inboxLink).toHaveAccessibleName("Inbox 1 item"); } finally { for (const hangUp of hangUps) hangUp(); await gateway.dispose(); } }); - test("the Attention view has no horizontal scroll at 360px wide", async ({ page }) => { + test("the Inbox view has no horizontal scroll at 360px wide", async ({ page }) => { const gateway = await startDaemon("gateway"); let hangUp = () => {}; try { @@ -440,7 +440,7 @@ test.describe("the attention view", () => { await untilTheDaemonSays(gateway, (views) => views.length === 1); await page.setViewportSize({ height: 740, width: 360 }); - await openAttention(page, gateway); + await openInbox(page, gateway); await expect(rows(page)).toHaveCount(1); expect(await hasHorizontalScroll(page)).toBe(false); @@ -453,15 +453,15 @@ test.describe("the attention view", () => { } }); - test("the Attention view is usable with the keyboard alone", async ({ browserName, page }) => { - // Safari moves focus to links with Option-Tab; plain Tab reaches only form controls there. + test("the Inbox view is usable with the keyboard alone", async ({ browserName, page }) => { + // why: Safari moves focus to links with Option-Tab; plain Tab reaches only form controls there. const tab = browserName === "webkit" ? "Alt+Tab" : "Tab"; const gateway = await startDaemon("gateway"); let hangUp = () => {}; try { hangUp = await joinOldWorker(gateway, { id: "wrk_old", label: "old-worker" }); await untilTheDaemonSays(gateway, (views) => views.length === 1); - /** Tabs forward until `link` has focus, and follows it with Enter. */ + /** why: Tabs forward until `link` has focus, and follows it with Enter. */ const follow = async (link: Locator) => { for (let step = 0; step < 20; step += 1) { if (await link.evaluate((element) => element === document.activeElement)) break; @@ -477,9 +477,9 @@ test.describe("the attention view", () => { await expect(page.getByRole("heading", { level: 1, name: "Overview" })).toBeVisible(); await follow( - page.getByRole("navigation", { name: "Console" }).getByRole("link", { name: /^Attention/ }), + page.getByRole("navigation", { name: "Console" }).getByRole("link", { name: /^Inbox/ }), ); - await expect(page.getByRole("heading", { level: 1, name: "Attention" })).toBeVisible(); + await expect(page.getByRole("heading", { level: 1, name: "Inbox" })).toBeVisible(); await follow(item(page, "incompatible", "old-worker")); await expect(page.getByRole("heading", { level: 2, name: "old-worker" })).toBeVisible(); diff --git a/e2e/console/shell.spec.ts b/e2e/console/shell.spec.ts index 26f925ef2..36643fe14 100644 --- a/e2e/console/shell.spec.ts +++ b/e2e/console/shell.spec.ts @@ -109,7 +109,7 @@ test.describe("the shell", () => { await expect(page.getByLabel("Operator token")).toBeVisible(); }); - test("the sidebar shows Overview and Attention, then the Operate group, then the Observe group, each with its label", async ({ + test("the sidebar shows Overview and Inbox, then the Operate group, then the Observe group, each with its label", async ({ daemon, page, }) => { @@ -120,7 +120,7 @@ test.describe("the shell", () => { await expect(nav.getByRole("link")).toHaveText([...NAV_LABELS]); expect(NAV.map((entry) => `${entry.label} ${entry.path}`)).toEqual([ "Overview /", - "Attention /attention", + "Inbox /inbox", "Fleet /fleet", "Leases /leases", "Queue /queue", @@ -135,7 +135,7 @@ test.describe("the shell", () => { await expect(section.getByRole("link")).toHaveText([...group.links]); } await expect(nav.getByRole("link", { name: "Overview" })).toHaveCount(1); - await expect(nav.getByRole("group").getByRole("link", { name: "Attention" })).toHaveCount(0); + await expect(nav.getByRole("group").getByRole("link", { name: "Inbox" })).toHaveCount(0); }); test("/fleet, /queue and /activity open the pages titled Fleet, Queue and Activity; /workers, /waiting and /events show Not found", async ({ diff --git a/ui/src/app/routes.test.ts b/ui/src/app/routes.test.ts index 9134ba359..59f6da8de 100644 --- a/ui/src/app/routes.test.ts +++ b/ui/src/app/routes.test.ts @@ -19,7 +19,7 @@ describe("the console's routes", () => { it("lists the sections in the sidebar's order, the overview first", () => { expect(ROUTES.map((route) => route.path)).toEqual([ "/", - "/attention", + "/inbox", "/fleet", "/leases", "/queue", diff --git a/ui/src/app/routes.ts b/ui/src/app/routes.ts index 5b2d47cfa..052b11262 100644 --- a/ui/src/app/routes.ts +++ b/ui/src/app/routes.ts @@ -1,7 +1,7 @@ import type { ComponentType } from "react"; import type { IconName } from "../ds"; -import { AttentionScreen } from "../screens/attention"; +import { InboxScreen } from "../screens/inbox"; import { ActivityScreen } from "../screens/activity"; import { LeasesScreen } from "../screens/leases"; import { OverviewScreen } from "../screens/overview"; @@ -21,7 +21,7 @@ export interface Route { export const ROUTES: readonly Route[] = [ { Screen: OverviewScreen, icon: "overview", label: "Overview", path: "/" }, - { Screen: AttentionScreen, icon: "attention", label: "Attention", path: "/attention" }, + { Screen: InboxScreen, icon: "inbox", label: "Inbox", path: "/inbox" }, { Screen: FleetScreen, group: "Operate", icon: "workers", label: "Fleet", path: "/fleet" }, { Screen: LeasesScreen, group: "Operate", icon: "leases", label: "Leases", path: "/leases" }, { Screen: QueueScreen, group: "Operate", icon: "waiting", label: "Queue", path: "/queue" }, diff --git a/ui/src/app/shell.tsx b/ui/src/app/shell.tsx index 0e01fa063..f1f5e8b93 100644 --- a/ui/src/app/shell.tsx +++ b/ui/src/app/shell.tsx @@ -4,7 +4,7 @@ import { AppFrame, Button, Icon, Sidebar, Status, StatusDot } from "../ds"; import { NotFoundScreen } from "../screens/not-found"; import { usePath } from "../state/router"; import { - useAttentionCount, + useInboxCount, useConnectionStatus, useSignedIn, useSignOut, @@ -16,7 +16,7 @@ import { ROUTES, routeFor } from "./routes"; export function Shell() { const path = usePath(); const route = routeFor(path); - const attention = useAttentionCount(); + const inbox = useInboxCount(); const sidebar = useSidebar(); useTokenCheck(); @@ -30,9 +30,7 @@ export function Shell() { icon: entry.icon, label: entry.label, to: entry.path, - ...(entry.path === "/attention" && attention !== undefined - ? { alert: true, count: attention } - : {}), + ...(entry.path === "/inbox" && inbox !== undefined ? { alert: true, count: inbox } : {}), })); return ( diff --git a/ui/src/ds/icon.tsx b/ui/src/ds/icon.tsx index b8a8585d1..ae5a2c437 100644 --- a/ui/src/ds/icon.tsx +++ b/ui/src/ds/icon.tsx @@ -3,7 +3,7 @@ const PATHS = { workers: "M2 3h12v4H2zM2 9h12v4H2zM5 5h.01M5 11h.01", leases: "M10 2a4 4 0 1 1-3.5 6L2 12.5V14h2v-1.5h1.5V11h1.5l1-1", waiting: "M2 4h12M2 8h9M2 12h6", - attention: "M8 2l6.5 11.5h-13zM8 6.5v3M8 11.5v.01", + inbox: "M2 9l2-6h8l2 6v4H2zM2 9h4l1 2h2l1-2h4", events: "M1.5 8h3l2-5 3 10 2-5h3", usage: "M2 14V2M2 14h12M5 11V8M8 11V5M11 11V7", collapse: "M2 2.5h12v11H2zM6 2.5v11M11.5 6L9.5 8l2 2", diff --git a/ui/src/model/attention.ts b/ui/src/model/attention.ts deleted file mode 100644 index b35349007..000000000 --- a/ui/src/model/attention.ts +++ /dev/null @@ -1,279 +0,0 @@ -import { eventSummary, eventTone } from "./activity"; -import { type ConsoleEvent, timeOfDay, workerIdOf } from "./events"; -import { itemPath } from "./paths"; -import { formatDuration } from "./time"; -import type { Tone } from "./tones"; -import { - stateEnteredAt, - type WorkerDevice, - type WorkerView, - workerName, - workerPath, -} from "./workers"; - -export type AttentionItem = - | { - readonly key: string; - readonly condition: "disconnected" | "incompatible" | "drained"; - readonly worker: WorkerView; - } - | { - readonly key: string; - readonly condition: "over RAM budget"; - readonly worker: WorkerView; - readonly usedBytes: number; - readonly limitBytes: number; - } - | { - readonly key: string; - readonly condition: "quarantined" | "stalled"; - readonly worker: WorkerView; - readonly device: WorkerDevice; - }; - -// why: a worker that is both disconnected and drained is two items, since each clears on its own. -export function attentionItems(workers: readonly WorkerView[]): readonly AttentionItem[] { - return workers.flatMap((worker) => [...workerItems(worker), ...deviceItems(worker)]); -} - -function workerItems(worker: WorkerView): AttentionItem[] { - const items: AttentionItem[] = []; - const key = (condition: string) => `${worker.id}/${condition}`; - if (worker.connection === "disconnected" || worker.connection === "incompatible") { - items.push({ condition: worker.connection, key: key(worker.connection), worker }); - } - if (worker.drained) items.push({ condition: "drained", key: key("drained"), worker }); - const ramBudget = worker.capacity?.ramBudget; - if (ramBudget?.overLimit === true) { - items.push({ - condition: "over RAM budget", - key: key("ram"), - limitBytes: ramBudget.limitBytes, - usedBytes: ramBudget.usedBytes, - worker, - }); - } - return items; -} - -function deviceItems(worker: WorkerView): AttentionItem[] { - return (worker.devices ?? []).flatMap((device): AttentionItem[] => { - const key = (condition: string) => `${worker.id}/${device.id}/${condition}`; - if (device.state === "quarantined") { - return [{ condition: "quarantined", device, key: key("quarantined"), worker }]; - } - if (device.stalled === true) { - return [{ condition: "stalled", device, key: key("stalled"), worker }]; - } - return []; - }); -} - -// why: a lost worker or a quarantined device is broken; everything else on the list needs a look -// soon, which is the warning tone, the same split the status words use. -export function attentionTone(condition: AttentionItem["condition"]): Tone { - return condition === "disconnected" || condition === "incompatible" || condition === "quarantined" - ? "error" - : "warn"; -} - -export interface AttentionRow { - readonly key: string; - readonly to: string; - readonly tone: Tone; - readonly word: string; - readonly subject: string; -} - -export interface AttentionFact { - readonly label: string; - readonly value: string; -} - -export interface AttentionEvent { - readonly key: string; - readonly time: string; - readonly name: string; - readonly tone?: Tone; - readonly text: string; - readonly to: string; -} - -export interface AttentionDetail { - readonly key: string; - readonly title: string; - readonly tone: Tone; - readonly word: string; - readonly worker: { readonly name: string; readonly to: string }; - readonly facts: readonly AttentionFact[]; - readonly events: readonly AttentionEvent[]; -} - -export interface AttentionPage { - readonly rows: readonly AttentionRow[]; - // why: a URL can name an item the daemon has since cleared; that is told apart from a list - // with nothing in it, which has no item to show at all. - readonly shown: AttentionDetail | "resolved" | undefined; - readonly named: boolean; -} - -const HOUR = 60 * 60 * 1_000; -const EVENT_ROWS = 25; - -function gibibytes(bytes: number): string { - return `${(bytes / 1024 ** 3).toFixed(2)} GiB`; -} - -function protocolText(versions: { readonly min: number; readonly max: number }): string { - return versions.min === versions.max - ? String(versions.min) - : `${versions.min}\u2013${versions.max}`; -} - -function subjectOf(item: AttentionItem): string { - return "device" in item - ? `${item.device.spec.model} on ${workerName(item.worker)}` - : workerName(item.worker); -} - -function factsOf(item: AttentionItem, now: number): readonly AttentionFact[] { - return "device" in item ? deviceFacts(item, now) : workerFacts(item, now); -} - -function deviceFacts( - item: Extract, - now: number, -): readonly AttentionFact[] { - const since = stateEnteredAt(item.device, item.worker); - return [ - { label: "Device", value: item.device.id }, - { label: "State", value: item.device.state }, - ...(since === undefined - ? [] - : [{ label: "In this state for", value: formatDuration(now - since) }]), - ...causeFacts(item.device), - ]; -} - -const CAUSE_TEXT = { - "purge-failed": "Purge failed", - "shutdown-failed": "Shutdown failed", - "delete-failed": "Delete failed", -} as const; - -function causeFacts(device: { - readonly state: string; - readonly quarantineCause?: - | { - readonly kind: keyof typeof CAUSE_TEXT | "stalled"; - readonly stalledState?: string | undefined; - readonly message?: string | undefined; - } - | undefined; -}): readonly AttentionFact[] { - const cause = device.quarantineCause; - if (device.state !== "quarantined" || cause === undefined) return []; - if (cause.kind === "stalled") { - return [{ label: "Cause", value: `Stalled while ${cause.stalledState ?? ""}` }]; - } - const text = CAUSE_TEXT[cause.kind]; - return [ - { label: "Cause", value: cause.message === undefined ? text : `${text}: ${cause.message}` }, - ]; -} - -function workerFacts( - item: Exclude, - now: number, -): readonly AttentionFact[] { - const { worker } = item; - if (item.condition === "over RAM budget") { - return [ - { label: "Used", value: gibibytes(item.usedBytes) }, - { label: "Limit", value: gibibytes(item.limitBytes) }, - ]; - } - if (item.condition === "disconnected") { - return [{ label: "Last seen", value: `${formatDuration(now - worker.lastSeenAt)} ago` }]; - } - if (item.condition === "drained") { - return [{ label: "Leases still held", value: String(worker.leases?.length ?? 0) }]; - } - const { protocol } = worker; - return protocol === undefined - ? [] - : [ - { label: "Gateway protocol", value: protocolText(protocol.gateway) }, - { label: "Worker protocol", value: protocolText(protocol.worker) }, - ]; -} - -function namesItem(event: ConsoleEvent, item: AttentionItem): boolean { - if (workerIdOf(event) === item.worker.id) return true; - if (!("device" in item)) return false; - const { payload } = event; - return ( - typeof payload === "object" && - payload !== null && - (payload as Record).deviceId === item.device.id - ); -} - -function detailOf( - item: AttentionItem, - input: { - readonly workers: readonly WorkerView[]; - readonly events: readonly ConsoleEvent[]; - readonly now: number; - }, -): AttentionDetail { - const { events, now, workers } = input; - return { - events: events - .filter((event) => event.timestamp > now - HOUR && namesItem(event, item)) - .sort((a, b) => b.timestamp - a.timestamp || b.seq - a.seq) - .slice(0, EVENT_ROWS) - .map((event) => { - const tone = eventTone(event.event); - return { - key: event.id, - name: event.event, - text: eventSummary(event, workers), - time: timeOfDay(event.timestamp), - to: itemPath("/activity", event.id), - ...(tone === undefined ? {} : { tone }), - }; - }), - facts: factsOf(item, now), - key: item.key, - title: - "device" in item - ? `${item.device.spec.model} ${item.device.spec.osVersion}` - : workerName(item.worker), - tone: attentionTone(item.condition), - word: item.condition, - worker: { name: workerName(item.worker), to: workerPath(item.worker.id) }, - }; -} - -// why: the list and the inspector are worked out together from the same items, so the row that is -// marked chosen is always the item the inspector shows. -export function attentionPageOf(input: { - readonly workers: readonly WorkerView[]; - readonly events: readonly ConsoleEvent[]; - readonly now: number; - readonly key: string | undefined; -}): AttentionPage { - const items = attentionItems(input.workers); - const rows = items.map((item) => ({ - key: item.key, - subject: subjectOf(item), - to: itemPath("/attention", item.key), - tone: attentionTone(item.condition), - word: item.condition, - })); - const named = input.key !== undefined; - const chosen = named ? items.find((item) => item.key === input.key) : items[0]; - if (chosen !== undefined) return { named, rows, shown: detailOf(chosen, input) }; - return { named, rows, shown: named ? "resolved" : undefined }; -} diff --git a/ui/src/model/event-list.test.ts b/ui/src/model/event-list.test.ts index 13e280244..9b861ff2a 100644 --- a/ui/src/model/event-list.test.ts +++ b/ui/src/model/event-list.test.ts @@ -211,7 +211,7 @@ describe("what an event links to", () => { expect(eventAction(queued, NO_PLACES)).toBeUndefined(); }); - it("is the attention item of a quarantined device", () => { + it("is the Inbox item of a quarantined device", () => { const quarantined = worker("wrk_1", "mac-1", { devices: [ { @@ -227,7 +227,7 @@ describe("what an event links to", () => { event("device.quarantined", { deviceId: "dev_1", workerId: "wrk_1" }), places({ workers: [quarantined] }), ), - ).toEqual({ label: "Open attention item", to: "/attention/wrk_1%2Fdev_1%2Fquarantined" }); + ).toEqual({ label: "Open Inbox item", to: "/inbox/wrk_1%2Fdev_1%2Fquarantined" }); }); it("is the worker the console lists, and none for one it does not", () => { diff --git a/ui/src/model/event-list.ts b/ui/src/model/event-list.ts index b4fb50685..75dd98122 100644 --- a/ui/src/model/event-list.ts +++ b/ui/src/model/event-list.ts @@ -1,5 +1,5 @@ import { eventSummary, eventTone } from "./activity"; -import { attentionItems } from "./attention"; +import { inboxItems } from "./inbox"; import { type ConsoleEvent, payloadPairs, @@ -153,11 +153,11 @@ export function eventAction(event: ConsoleEvent, places: EventPlaces): EventActi return { label: "Open request", to: itemPath("/queue", request.id) }; } const deviceId = textField(payload, "deviceId"); - const item = attentionItems(places.workers).find( + const item = inboxItems(places.workers).find( (entry) => "device" in entry && entry.worker.id === workerId && entry.device.id === deviceId, ); if (item !== undefined) { - return { label: "Open attention item", to: itemPath("/attention", item.key) }; + return { label: "Open Inbox item", to: itemPath("/inbox", item.key) }; } const worker = places.workers.find((entry) => entry.id === workerId); if (worker !== undefined) return { label: "Open worker", to: workerPath(worker.id) }; diff --git a/ui/src/model/inbox.test.ts-e b/ui/src/model/inbox.test.ts-e deleted file mode 100644 index 72d7f4b65..000000000 --- a/ui/src/model/inbox.test.ts-e +++ /dev/null @@ -1,372 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { attentionItems, attentionPageOf } from "./attention"; -import type { ConsoleEvent } from "./events"; -import type { WorkerDevice, WorkerView } from "./workers"; - -const NOW = Date.parse("2026-10-02T12:00:00Z"); -const GIB = 1024 ** 3; - -function worker(overrides: Partial = {}): WorkerView { - return { - catalog: [], - connection: "connected", - devices: [], - drained: false, - id: "wrk_1", - lastSeenAt: NOW, - leases: [], - ...overrides, - }; -} - -function device(id: string, overrides: Partial = {}): WorkerDevice { - return { - physical: false, - id, - mode: "full", - servesDefaultMode: true, - spec: { physical: false, model: "iPhone 16", osVersion: "18.4", platform: "ios" }, - state: "ready", - ...overrides, - }; -} - -function capacity(ramBudget?: { usedBytes: number; limitBytes: number; overLimit: boolean }) { - const entry = { - atRamBudget: false, - limit: 4, - maxRunning: 4, - overLimit: false, - reserved: 0, - running: 1, - used: 1, - }; - return { - android: { ...entry, warm: 0 }, - global: { maxRunning: 4, overLimit: false, reserved: 0, running: 1, warm: 0 }, - ios: { ...entry, warm: 0 }, - ...(ramBudget === undefined ? {} : { ramBudget }), - }; -} - -function event(seq: number, name: string, at: number, payload: unknown = {}): ConsoleEvent { - return { event: name, id: `e${seq}`, payload, seq, timestamp: at }; -} - -function summary(workers: readonly WorkerView[]): string[] { - return attentionItems(workers).map((item) => - [item.worker.id, "device" in item ? item.device.id : "-", item.condition].join(" "), - ); -} - -function pageOf( - workers: readonly WorkerView[], - key?: string, - events: readonly ConsoleEvent[] = [], -) { - return attentionPageOf({ events, key, now: NOW, workers }); -} - -function shownOf(page: ReturnType) { - if (typeof page.shown !== "object") throw new Error("no item is shown"); - return page.shown; -} - -function factsOf(w: WorkerView, key: string) { - return shownOf(pageOf([w], key)).facts; -} - -describe("the items that need attention", () => { - it("hold a disconnected, an incompatible and a drained worker, one item per condition", () => { - const workers = [ - worker({ id: "wrk_ok" }), - worker({ connection: "disconnected", id: "wrk_gone" }), - worker({ connection: "incompatible", id: "wrk_old" }), - worker({ drained: true, id: "wrk_drained" }), - worker({ connection: "disconnected", drained: true, id: "wrk_both" }), - ]; - - expect(summary(workers)).toEqual([ - "wrk_gone - disconnected", - "wrk_old - incompatible", - "wrk_drained - drained", - "wrk_both - disconnected", - "wrk_both - drained", - ]); - }); - - it("hold a quarantined device and a stalled device, not one mid-transition", () => { - const workers = [ - worker({ - devices: [ - device("dev_ready"), - device("dev_quarantined", { state: "quarantined" }), - device("dev_stuck", { stalled: true, state: "reclaiming", transitionAgeMs: 300_000 }), - device("dev_busy", { state: "provisioning", transitionAgeMs: 2_000 }), - ], - }), - ]; - - expect(summary(workers)).toEqual([ - "wrk_1 dev_quarantined quarantined", - "wrk_1 dev_stuck stalled", - ]); - }); - - it("hold a quarantined physical device like any quarantined device", () => { - const physical: WorkerDevice = { - class: "phone", - id: "dev_phone", - physical: true, - servesDefaultMode: false, - spec: { model: "iPhone 15 Pro", osVersion: "18.4", physical: true, platform: "ios" }, - state: "quarantined", - }; - - expect(summary([worker({ devices: [physical] })])).toEqual(["wrk_1 dev_phone quarantined"]); - }); - - it("hold a worker over its RAM budget, not one under it or with no budget", () => { - const workers = [ - worker({ - capacity: capacity({ limitBytes: 12 * GIB, overLimit: true, usedBytes: 13 * GIB }), - id: "wrk_over", - }), - worker({ - capacity: capacity({ limitBytes: 12 * GIB, overLimit: false, usedBytes: 4 * GIB }), - id: "wrk_under", - }), - worker({ capacity: capacity(), id: "wrk_none" }), - worker({ id: "wrk_unread" }), - ]; - - expect(summary(workers)).toEqual(["wrk_over - over RAM budget"]); - }); - - it("lose an item when its condition clears", () => { - const quarantined = device("dev_1", { state: "quarantined" }); - const stalled = device("dev_2", { stalled: true, state: "provisioning" }); - const ramBudget = { limitBytes: 12 * GIB, usedBytes: 13 * GIB }; - const before = worker({ - capacity: capacity({ ...ramBudget, overLimit: true }), - connection: "disconnected", - devices: [quarantined, stalled], - drained: true, - }); - expect(attentionItems([before])).toHaveLength(5); - - const cleared: [string, WorkerView][] = [ - ["disconnected", { ...before, connection: "connected" }], - ["drained", { ...before, drained: false }], - ["over RAM budget", { ...before, capacity: capacity({ ...ramBudget, overLimit: false }) }], - ["quarantined", { ...before, devices: [{ ...quarantined, state: "ready" }, stalled] }], - ["stalled", { ...before, devices: [quarantined, device("dev_2", { state: "ready" })] }], - ]; - for (const [condition, after] of cleared) { - const conditions = attentionItems([after]).map((item) => item.condition); - expect(conditions, condition).toHaveLength(4); - expect(conditions, condition).not.toContain(condition); - } - }); -}); - -describe("the attention page", () => { - it("lists a row per item, naming the worker or the device on its worker", () => { - const page = pageOf([ - worker({ connection: "disconnected", id: "wrk/1", label: "mac-mini-1" }), - worker({ devices: [device("dev_q", { state: "quarantined" })], id: "wrk_2" }), - ]); - - expect(page.rows.map((row) => [row.word, row.tone, row.subject, row.to])).toEqual([ - ["disconnected", "error", "mac-mini-1", "/attention/wrk%2F1%2Fdisconnected"], - ["quarantined", "error", "iPhone 16 on wrk_2", "/attention/wrk_2%2Fdev_q%2Fquarantined"], - ]); - }); - - it("shows the first item when the URL names none", () => { - const page = pageOf([worker({ drained: true }), worker({ drained: true, id: "wrk_2" })]); - - expect(page.named).toBe(false); - expect(shownOf(page).key).toBe("wrk_1/drained"); - }); - - it("shows the item the URL names", () => { - const page = pageOf( - [worker({ drained: true }), worker({ drained: true, id: "wrk_2" })], - "wrk_2/drained", - ); - - expect(page.named).toBe(true); - expect(shownOf(page).key).toBe("wrk_2/drained"); - }); - - it("says an item the URL names is resolved once the daemon stops reporting it", () => { - const page = pageOf([worker()], "wrk_1/drained"); - - expect(page.shown).toBe("resolved"); - }); - - it("shows nothing when nothing needs attention and the URL names nothing", () => { - const page = pageOf([worker()]); - - expect(page.rows).toEqual([]); - expect(page.shown).toBeUndefined(); - }); - - it("titles a worker item by the worker and a device item by its model and runtime", () => { - const workers = [ - worker({ drained: true, label: "mac-mini-1" }), - worker({ devices: [device("dev_q", { state: "quarantined" })], id: "wrk_2" }), - ]; - - expect(shownOf(pageOf(workers)).title).toBe("mac-mini-1"); - expect(shownOf(pageOf(workers, "wrk_2/dev_q/quarantined")).title).toBe("iPhone 16 18.4"); - }); - - it("gives a disconnected worker the time since it was last seen", () => { - const w = worker({ connection: "disconnected", lastSeenAt: NOW - 100_000 }); - - expect(factsOf(w, "wrk_1/disconnected")).toEqual([ - { label: "Last seen", value: "1 min 40 s ago" }, - ]); - }); - - it("gives an incompatible worker both protocol ranges", () => { - const w = worker({ - connection: "incompatible", - protocol: { gateway: { max: 3, min: 2 }, worker: { max: 1, min: 1 } }, - }); - - expect(factsOf(w, "wrk_1/incompatible")).toEqual([ - { label: "Gateway protocol", value: "2–3" }, - { label: "Worker protocol", value: "1" }, - ]); - }); - - it("gives a drained worker the leases it still holds", () => { - const lease = { deviceId: "d", grantedAt: NOW, id: "l" } as unknown as never; - const w = worker({ drained: true, leases: [lease] }); - - expect(factsOf(w, "wrk_1/drained")).toEqual([{ label: "Leases still held", value: "1" }]); - }); - - it("gives a worker over its RAM budget what it uses and its limit", () => { - const ramBudget = { limitBytes: 12 * GIB, overLimit: true, usedBytes: 13 * GIB }; - - expect(factsOf(worker({ capacity: capacity(ramBudget) }), "wrk_1/ram")).toEqual([ - { label: "Used", value: "13.00 GiB" }, - { label: "Limit", value: "12.00 GiB" }, - ]); - }); - - it("gives a stalled device its id, state and time in that state", () => { - const w = worker({ - devices: [ - device("dev_stuck", { stalled: true, state: "provisioning", transitionAgeMs: 90_000 }), - ], - lastSeenAt: NOW - 10_000, - }); - - expect(factsOf(w, "wrk_1/dev_stuck/stalled")).toEqual([ - { label: "Device", value: "dev_stuck" }, - { label: "State", value: "provisioning" }, - { label: "In this state for", value: "1 min 40 s" }, - ]); - }); - - it("gives a quarantined device no time in its state", () => { - const w = worker({ devices: [device("dev_q", { state: "quarantined" })] }); - - expect(factsOf(w, "wrk_1/dev_q/quarantined")).toEqual([ - { label: "Device", value: "dev_q" }, - { label: "State", value: "quarantined" }, - ]); - }); - - it("ends a quarantined device's facts with Cause for each kind", () => { - const cases = [ - [ - { kind: "purge-failed", message: "Error: erase failed" }, - "Purge failed: Error: erase failed", - ], - [ - { kind: "shutdown-failed", message: "Error: no shutdown" }, - "Shutdown failed: Error: no shutdown", - ], - [{ kind: "delete-failed", message: "Error: no delete" }, "Delete failed: Error: no delete"], - [{ kind: "purge-failed" }, "Purge failed"], - [{ kind: "stalled", stalledState: "provisioning" }, "Stalled while provisioning"], - [{ kind: "stalled", stalledState: "reclaiming" }, "Stalled while reclaiming"], - ] as const; - - for (const [quarantineCause, text] of cases) { - const w = worker({ - devices: [Object.assign(device("dev_q", { state: "quarantined" }), { quarantineCause })], - }); - - expect(factsOf(w, "wrk_1/dev_q/quarantined"), text).toEqual([ - { label: "Device", value: "dev_q" }, - { label: "State", value: "quarantined" }, - { label: "Cause", value: text }, - ]); - } - }); - - it("gives a stalled device that is not quarantined no Cause, even when its record still carries one", () => { - const w = worker({ - devices: [ - Object.assign(device("dev_stuck", { stalled: true, state: "reclaiming" }), { - quarantineCause: { kind: "purge-failed", message: "Error: erase failed" }, - }), - ], - }); - - const labels = factsOf(w, "wrk_1/dev_stuck/stalled").map((fact) => fact.label); - - expect(labels).not.toContain("Cause"); - }); - - it("gives a stalled device on a disconnected worker no time in its state", () => { - // why: a gateway keeps a disconnected worker's devices as last reported, with an age it can no - // longer count from. - const w = worker({ - connection: "disconnected", - devices: [ - device("dev_stuck", { stalled: true, state: "reclaiming", transitionAgeMs: 90_000 }), - ], - }); - - const labels = factsOf(w, "wrk_1/dev_stuck/stalled").map((fact) => fact.label); - - expect(labels).toEqual(["Device", "State"]); - }); - - it("lists the last hour's events naming the worker or the device, newest first", () => { - const w = worker({ devices: [device("dev_1", { state: "quarantined" })], drained: true }); - const events = [ - event(1, "worker.drain-started", NOW - 50 * 60_000, { workerId: "wrk_1" }), - event(2, "device.quarantined", NOW - 5 * 60_000, { deviceId: "dev_1" }), - event(3, "lease.granted", NOW - 60_000, { deviceId: "dev_other" }), - event(4, "worker.drain-started", NOW - 2 * 60 * 60_000, { workerId: "wrk_1" }), - event(5, "worker.rejected", NOW - 60_000, { workerId: "wrk_1" }), - ]; - - const ofWorker = shownOf(pageOf([w], "wrk_1/drained", events)); - const ofDevice = shownOf(pageOf([w], "wrk_1/dev_1/quarantined", events)); - - expect(ofWorker.events.map((entry) => entry.key)).toEqual(["e1"]); - expect(ofDevice.events.map((entry) => entry.key)).toEqual(["e2", "e1"]); - expect(ofDevice.events[0]).toMatchObject({ - name: "device.quarantined", - to: "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/activity/e2", - tone: "error", - }); - }); - - it("links each item to its worker's page", () => { - const page = pageOf([worker({ drained: true, id: "wrk/1", label: "mac-mini-1" })]); - - expect(shownOf(page).worker).toEqual({ name: "mac-mini-1", to: "/fleet/wrk%2F1" }); - }); -}); diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index 1f88b82f8..9df4d9c4c 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -1,19 +1,279 @@ -import type { AttentionItem, AttentionPage } from "./attention"; -import type { ConsoleEvent } from "./events"; -import type { WorkerView } from "./workers"; +import { eventSummary, eventTone } from "./activity"; +import { type ConsoleEvent, timeOfDay, workerIdOf } from "./events"; +import { itemPath } from "./paths"; +import { formatDuration } from "./time"; +import type { Tone } from "./tones"; +import { + stateEnteredAt, + type WorkerDevice, + type WorkerView, + workerName, + workerPath, +} from "./workers"; -export type InboxItem = AttentionItem; -export type InboxPage = AttentionPage; +export type InboxItem = + | { + readonly key: string; + readonly condition: "disconnected" | "incompatible" | "drained"; + readonly worker: WorkerView; + } + | { + readonly key: string; + readonly condition: "over RAM budget"; + readonly worker: WorkerView; + readonly usedBytes: number; + readonly limitBytes: number; + } + | { + readonly key: string; + readonly condition: "quarantined" | "stalled"; + readonly worker: WorkerView; + readonly device: WorkerDevice; + }; -export function inboxItems(_workers: readonly WorkerView[]): readonly InboxItem[] { - return []; +// why: a worker that is both disconnected and drained is two items, since each clears on its own. +export function inboxItems(workers: readonly WorkerView[]): readonly InboxItem[] { + return workers.flatMap((worker) => [...workerItems(worker), ...deviceItems(worker)]); } -export function inboxPageOf(_input: { +function workerItems(worker: WorkerView): InboxItem[] { + const items: InboxItem[] = []; + const key = (condition: string) => `${worker.id}/${condition}`; + if (worker.connection === "disconnected" || worker.connection === "incompatible") { + items.push({ condition: worker.connection, key: key(worker.connection), worker }); + } + if (worker.drained) items.push({ condition: "drained", key: key("drained"), worker }); + const ramBudget = worker.capacity?.ramBudget; + if (ramBudget?.overLimit === true) { + items.push({ + condition: "over RAM budget", + key: key("ram"), + limitBytes: ramBudget.limitBytes, + usedBytes: ramBudget.usedBytes, + worker, + }); + } + return items; +} + +function deviceItems(worker: WorkerView): InboxItem[] { + return (worker.devices ?? []).flatMap((device): InboxItem[] => { + const key = (condition: string) => `${worker.id}/${device.id}/${condition}`; + if (device.state === "quarantined") { + return [{ condition: "quarantined", device, key: key("quarantined"), worker }]; + } + if (device.stalled === true) { + return [{ condition: "stalled", device, key: key("stalled"), worker }]; + } + return []; + }); +} + +// why: a lost worker or a quarantined device is broken; everything else on the list needs a look +// soon, which is the warning tone, the same split the status words use. +export function inboxTone(condition: InboxItem["condition"]): Tone { + return condition === "disconnected" || condition === "incompatible" || condition === "quarantined" + ? "error" + : "warn"; +} + +export interface InboxRow { + readonly key: string; + readonly to: string; + readonly tone: Tone; + readonly word: string; + readonly subject: string; +} + +export interface InboxFact { + readonly label: string; + readonly value: string; +} + +export interface InboxEvent { + readonly key: string; + readonly time: string; + readonly name: string; + readonly tone?: Tone; + readonly text: string; + readonly to: string; +} + +export interface InboxDetail { + readonly key: string; + readonly title: string; + readonly tone: Tone; + readonly word: string; + readonly worker: { readonly name: string; readonly to: string }; + readonly facts: readonly InboxFact[]; + readonly events: readonly InboxEvent[]; +} + +export interface InboxPage { + readonly rows: readonly InboxRow[]; + // why: a URL can name an item the daemon has since cleared; that is told apart from a list + // with nothing in it, which has no item to show at all. + readonly shown: InboxDetail | "resolved" | undefined; + readonly named: boolean; +} + +const HOUR = 60 * 60 * 1_000; +const EVENT_ROWS = 25; + +function gibibytes(bytes: number): string { + return `${(bytes / 1024 ** 3).toFixed(2)} GiB`; +} + +function protocolText(versions: { readonly min: number; readonly max: number }): string { + return versions.min === versions.max + ? String(versions.min) + : `${versions.min}\u2013${versions.max}`; +} + +function subjectOf(item: InboxItem): string { + return "device" in item + ? `${item.device.spec.model} on ${workerName(item.worker)}` + : workerName(item.worker); +} + +function factsOf(item: InboxItem, now: number): readonly InboxFact[] { + return "device" in item ? deviceFacts(item, now) : workerFacts(item, now); +} + +function deviceFacts( + item: Extract, + now: number, +): readonly InboxFact[] { + const since = stateEnteredAt(item.device, item.worker); + return [ + { label: "Device", value: item.device.id }, + { label: "State", value: item.device.state }, + ...(since === undefined + ? [] + : [{ label: "In this state for", value: formatDuration(now - since) }]), + ...causeFacts(item.device), + ]; +} + +const CAUSE_TEXT = { + "purge-failed": "Purge failed", + "shutdown-failed": "Shutdown failed", + "delete-failed": "Delete failed", +} as const; + +function causeFacts(device: { + readonly state: string; + readonly quarantineCause?: + | { + readonly kind: keyof typeof CAUSE_TEXT | "stalled"; + readonly stalledState?: string | undefined; + readonly message?: string | undefined; + } + | undefined; +}): readonly InboxFact[] { + const cause = device.quarantineCause; + if (device.state !== "quarantined" || cause === undefined) return []; + if (cause.kind === "stalled") { + return [{ label: "Cause", value: `Stalled while ${cause.stalledState ?? ""}` }]; + } + const text = CAUSE_TEXT[cause.kind]; + return [ + { label: "Cause", value: cause.message === undefined ? text : `${text}: ${cause.message}` }, + ]; +} + +function workerFacts( + item: Exclude, + now: number, +): readonly InboxFact[] { + const { worker } = item; + if (item.condition === "over RAM budget") { + return [ + { label: "Used", value: gibibytes(item.usedBytes) }, + { label: "Limit", value: gibibytes(item.limitBytes) }, + ]; + } + if (item.condition === "disconnected") { + return [{ label: "Last seen", value: `${formatDuration(now - worker.lastSeenAt)} ago` }]; + } + if (item.condition === "drained") { + return [{ label: "Leases still held", value: String(worker.leases?.length ?? 0) }]; + } + const { protocol } = worker; + return protocol === undefined + ? [] + : [ + { label: "Gateway protocol", value: protocolText(protocol.gateway) }, + { label: "Worker protocol", value: protocolText(protocol.worker) }, + ]; +} + +function namesItem(event: ConsoleEvent, item: InboxItem): boolean { + if (workerIdOf(event) === item.worker.id) return true; + if (!("device" in item)) return false; + const { payload } = event; + return ( + typeof payload === "object" && + payload !== null && + (payload as Record).deviceId === item.device.id + ); +} + +function detailOf( + item: InboxItem, + input: { + readonly workers: readonly WorkerView[]; + readonly events: readonly ConsoleEvent[]; + readonly now: number; + }, +): InboxDetail { + const { events, now, workers } = input; + return { + events: events + .filter((event) => event.timestamp > now - HOUR && namesItem(event, item)) + .sort((a, b) => b.timestamp - a.timestamp || b.seq - a.seq) + .slice(0, EVENT_ROWS) + .map((event) => { + const tone = eventTone(event.event); + return { + key: event.id, + name: event.event, + text: eventSummary(event, workers), + time: timeOfDay(event.timestamp), + to: itemPath("/activity", event.id), + ...(tone === undefined ? {} : { tone }), + }; + }), + facts: factsOf(item, now), + key: item.key, + title: + "device" in item + ? `${item.device.spec.model} ${item.device.spec.osVersion}` + : workerName(item.worker), + tone: inboxTone(item.condition), + word: item.condition, + worker: { name: workerName(item.worker), to: workerPath(item.worker.id) }, + }; +} + +// why: the list and the inspector are worked out together from the same items, so the row that is +// marked chosen is always the item the inspector shows. +export function inboxPageOf(input: { readonly workers: readonly WorkerView[]; readonly events: readonly ConsoleEvent[]; readonly now: number; readonly key: string | undefined; }): InboxPage { - return { named: false, rows: [], shown: undefined }; + const items = inboxItems(input.workers); + const rows = items.map((item) => ({ + key: item.key, + subject: subjectOf(item), + to: itemPath("/inbox", item.key), + tone: inboxTone(item.condition), + word: item.condition, + })); + const named = input.key !== undefined; + const chosen = named ? items.find((item) => item.key === input.key) : items[0]; + if (chosen !== undefined) return { named, rows, shown: detailOf(chosen, input) }; + return { named, rows, shown: named ? "resolved" : undefined }; } diff --git a/ui/src/model/overview.test.ts b/ui/src/model/overview.test.ts index 1721e9f0a..f28181530 100644 --- a/ui/src/model/overview.test.ts +++ b/ui/src/model/overview.test.ts @@ -164,9 +164,9 @@ describe("the overview", () => { const { attention } = overviewOf({ events: [], now: NOW, requests: [], workers: fleet }); expect(attention.map((item) => [item.word, item.tone, item.subject, item.to])).toEqual([ - ["drained", "warn", "mini-2", "/attention/mini-2%2Fdrained"], - ["quarantined", "error", "Pixel 8 on mini-2", "/attention/mini-2%2Fd%2Fquarantined"], - ["disconnected", "error", "down-1", "/attention/down-1%2Fdisconnected"], + ["drained", "warn", "mini-2", "/inbox/mini-2%2Fdrained"], + ["quarantined", "error", "Pixel 8 on mini-2", "/inbox/mini-2%2Fd%2Fquarantined"], + ["disconnected", "error", "down-1", "/inbox/down-1%2Fdisconnected"], ]); }); diff --git a/ui/src/model/overview.ts b/ui/src/model/overview.ts index dae107a84..6be7d7e9e 100644 --- a/ui/src/model/overview.ts +++ b/ui/src/model/overview.ts @@ -1,5 +1,5 @@ import { eventSummary, eventTone } from "./activity"; -import { attentionItems, attentionTone } from "./attention"; +import { inboxItems, inboxTone } from "./inbox"; import type { ConsoleEvent } from "./events"; import { type DeviceSlot, slotsLabel, workerHealth, workerSlots } from "./fleet"; import type { FiguresState } from "./figures"; @@ -193,14 +193,14 @@ export function overviewOf(input: { ...(tone === undefined ? {} : { tone }), }; }), - attention: attentionItems(workers).map((item) => ({ + attention: inboxItems(workers).map((item) => ({ key: item.key, subject: "device" in item ? `${item.device.spec.model} on ${workerName(item.worker)}` : workerName(item.worker), - to: itemPath("/attention", item.key), - tone: attentionTone(item.condition), + to: itemPath("/inbox", item.key), + tone: inboxTone(item.condition), word: item.condition, })), figures, diff --git a/ui/src/model/paths.test.ts b/ui/src/model/paths.test.ts index cc363e316..581c90cfc 100644 --- a/ui/src/model/paths.test.ts +++ b/ui/src/model/paths.test.ts @@ -5,7 +5,7 @@ import { devicePath, fleetAddress, itemIdFrom, itemPath } from "./paths"; describe("an item's page path", () => { it("carries any id, a slash or a space included, and reads it back whole", () => { for (const id of ["wrk_1", "wrk 1/dev_2/quarantined", "a%b"]) { - expect(itemIdFrom("/attention", itemPath("/attention", id)), id).toBe(id); + expect(itemIdFrom("/inbox", itemPath("/inbox", id)), id).toBe(id); } }); diff --git a/ui/src/model/paths.ts b/ui/src/model/paths.ts index 178e69509..65d800775 100644 --- a/ui/src/model/paths.ts +++ b/ui/src/model/paths.ts @@ -1,10 +1,10 @@ -export type Section = "/fleet" | "/leases" | "/queue" | "/attention" | "/activity"; +export type Section = "/fleet" | "/leases" | "/queue" | "/inbox" | "/activity"; export function itemPath(section: Section, id: string): `/${string}` { return `${section}/${encodeURIComponent(id)}`; } -// why: ids are opaque and may hold a slash (an attention item's key does), so the whole rest of the +// why: ids are opaque and may hold a slash (an Inbox item's key does), so the whole rest of the // path is one id; a malformed escape is kept as typed rather than thrown. export function itemIdFrom(section: Section, path: string): string | undefined { if (!path.startsWith(`${section}/`)) return undefined; diff --git a/ui/src/screens/attention/attention.css b/ui/src/screens/inbox/inbox.css similarity index 79% rename from ui/src/screens/attention/attention.css rename to ui/src/screens/inbox/inbox.css index 1f8a6868f..c000da2bf 100644 --- a/ui/src/screens/attention/attention.css +++ b/ui/src/screens/inbox/inbox.css @@ -11,13 +11,13 @@ font-size: var(--text-md); } -.attention-events { +.inbox-events { margin: 0; padding: 0; list-style: none; } -.attention-event { +.inbox-event { display: grid; grid-template-columns: 4.5rem 11rem minmax(0, 1fr); align-items: center; @@ -30,47 +30,47 @@ transition: background-color var(--duration); } -.attention-events li:last-child .attention-event { +.inbox-events li:last-child .inbox-event { border-bottom: 0; } -.attention-event:hover { +.inbox-event:hover { background: var(--field); color: var(--text); } -.attention-event .mono { +.inbox-event .mono { overflow: hidden; font-size: var(--text-xs); text-overflow: ellipsis; white-space: nowrap; } -.attention-event-text { +.inbox-event-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.attention-event-error { +.inbox-event-error { color: var(--status-error); } -.attention-event-warn { +.inbox-event-warn { color: var(--status-warn); } @media (max-width: 600px) { - .attention-event { + .inbox-event { grid-template-columns: 4.5rem minmax(0, 1fr); } - .attention-event-text { + .inbox-event-text { grid-column: 1 / -1; } } -.attention-worker { +.inbox-worker { min-width: 0; overflow-wrap: anywhere; } diff --git a/ui/src/screens/attention/index.test.tsx b/ui/src/screens/inbox/index.test.tsx similarity index 71% rename from ui/src/screens/attention/index.test.tsx rename to ui/src/screens/inbox/index.test.tsx index f2229882d..ba117bbc1 100644 --- a/ui/src/screens/attention/index.test.tsx +++ b/ui/src/screens/inbox/index.test.tsx @@ -1,9 +1,9 @@ import { renderToStaticMarkup } from "react-dom/server"; import { describe, expect, it } from "vitest"; -import { attentionPageOf } from "../../model/attention"; +import { inboxPageOf } from "../../model/inbox"; import type { WorkerView } from "../../model/workers"; -import { AttentionBody } from "."; +import { InboxBody } from "."; const NOW = Date.parse("2026-10-02T12:00:00Z"); @@ -21,15 +21,15 @@ function worker(overrides: Partial = {}): WorkerView { } function render(workers: readonly WorkerView[], key?: string): string { - const page = attentionPageOf({ events: [], key, now: NOW, workers }); - return renderToStaticMarkup(); + const page = inboxPageOf({ events: [], key, now: NOW, workers }); + return renderToStaticMarkup(); } -describe("the attention screen", () => { - it("says so when nothing needs attention", () => { +describe("the Inbox screen", () => { + it("says so when the Inbox is empty", () => { const html = render([worker()]); - expect(html).toContain("Nothing needs attention."); + expect(html).toContain("Nothing needs you."); expect(html).toContain("0 open"); }); @@ -41,8 +41,8 @@ describe("the attention screen", () => { expect(html).toContain("2 open"); expect(html).toContain('aria-label="disconnected"'); - expect(html).toContain('href="/attention/wrk_a%2Fdisconnected"'); - expect(html).toContain('href="/attention/wrk_b%2Fdrained"'); + expect(html).toContain('href="/inbox/wrk_a%2Fdisconnected"'); + expect(html).toContain('href="/inbox/wrk_b%2Fdrained"'); }); it("shows the first item in the inspector with its worker linked and an Open worker button", () => { @@ -55,10 +55,10 @@ describe("the attention screen", () => { expect(html).toContain("No events in the last hour."); }); - it("says Resolved. with a link back when the URL names an item that no longer needs attention", () => { + it("says Resolved. with a link back when the URL names an item that is no longer in the Inbox", () => { const html = render([worker()], "wrk_1/drained"); expect(html).toContain("Resolved."); - expect(html).toContain('Back to Attention'); + expect(html).toContain('Back to Inbox'); }); }); diff --git a/ui/src/screens/attention/index.tsx b/ui/src/screens/inbox/index.tsx similarity index 65% rename from ui/src/screens/attention/index.tsx rename to ui/src/screens/inbox/index.tsx index b2e41801f..a784d0e59 100644 --- a/ui/src/screens/attention/index.tsx +++ b/ui/src/screens/inbox/index.tsx @@ -1,4 +1,4 @@ -import "./attention.css"; +import "./inbox.css"; import { ButtonLink, @@ -19,34 +19,34 @@ import { StatusDot, } from "../../ds"; import { - type AttentionDetail, - type AttentionEvent, - type AttentionPage, + type InboxDetail, + type InboxEvent, + type InboxPage, useAttention, - useAttentionRows, -} from "../../state/attention"; + useInboxRows, +} from "../../state/inbox"; -export function AttentionScreen() { +export function InboxScreen() { const view = useAttention(); - return {(page) => }; + return {(page) => }; } -export function AttentionBody({ page }: { readonly page: AttentionPage }) { - const { paging, shown } = useAttentionRows(page.rows); +export function InboxBody({ page }: { readonly page: InboxPage }) { + const { paging, shown } = useInboxRows(page.rows); const chosen = typeof page.shown === "object" ? page.shown.key : undefined; return ( } + footer={} > {page.rows.length === 0 ? ( - Nothing needs attention. + Nothing needs you. ) : ( - + {shown.map((row) => ( Nothing to show.; if (shown === "resolved") { return ( - Resolved. Back to Attention + Resolved. Back to Inbox ); } return ; } -function Item({ detail }: { readonly detail: AttentionDetail }) { +function Item({ detail }: { readonly detail: InboxDetail }) { return ( {detail.word} ·{" "} - + {detail.worker.name} @@ -110,20 +110,18 @@ function Item({ detail }: { readonly detail: AttentionDetail }) { ); } -function EventList({ events }: { readonly events: readonly AttentionEvent[] }) { +function EventList({ events }: { readonly events: readonly InboxEvent[] }) { if (events.length === 0) return No events in the last hour.; return ( -
    +
      {events.map((event) => (
    • - + {event.time} - + {event.name} - {event.text} + {event.text}
    • ))} diff --git a/ui/src/state/attention.ts b/ui/src/state/inbox.ts similarity index 73% rename from ui/src/state/attention.ts rename to ui/src/state/inbox.ts index a24a736ea..59c6ef13a 100644 --- a/ui/src/state/attention.ts +++ b/ui/src/state/inbox.ts @@ -1,6 +1,6 @@ import type { LoadView } from "../ds/loaded"; import type { Paging } from "../ds/pager"; -import { type AttentionPage, attentionPageOf, type AttentionRow } from "../model/attention"; +import { type InboxPage, inboxPageOf, type InboxRow } from "../model/inbox"; import { listSearch, TABLE_SIZES } from "../model/paging"; import { itemIdFrom } from "../model/paths"; import type { WorkerList } from "../model/workers"; @@ -10,31 +10,26 @@ import { usePaging } from "./paging"; import { bothViews, loadView, mapView } from "./resource"; import { usePath, useSearch } from "./router"; -export type { - AttentionDetail, - AttentionEvent, - AttentionPage, - AttentionRow, -} from "../model/attention"; +export type { InboxDetail, InboxEvent, InboxPage, InboxRow } from "../model/inbox"; export type { Paging } from "../ds/pager"; -export function useAttention(): LoadView { +export function useAttention(): LoadView { const workers = loadView(useLiveResource("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/v1/workers")); // why: the events only fill the inspector's list, so a feed still loading shows the page with // none rather than holding back the list. const feed = useRecentEvents(); const now = useNow(); - const key = itemIdFrom("/attention", usePath()); + const key = itemIdFrom("/inbox", usePath()); const reads = bothViews(workers, { data: feed.data ?? [], kind: "ready" }); return mapView(reads, ([list, events]) => - attentionPageOf({ events, key, now: now.server, workers: list.workers }), + inboxPageOf({ events, key, now: now.server, workers: list.workers }), ); } // why: the pager is read once the list is known, so a page in the URL is never corrected against // a list that has not arrived. -export function useAttentionRows(rows: readonly AttentionRow[]): { - readonly shown: readonly AttentionRow[]; +export function useInboxRows(rows: readonly InboxRow[]): { + readonly shown: readonly InboxRow[]; readonly paging: Paging; } { const paging = usePaging({ sizes: TABLE_SIZES, total: rows.length }); diff --git a/ui/src/state/shell.ts b/ui/src/state/shell.ts index e24d5b6c5..2814ec9f5 100644 --- a/ui/src/state/shell.ts +++ b/ui/src/state/shell.ts @@ -1,16 +1,16 @@ import { useEffect, useState, useSyncExternalStore } from "react"; import type { ConnectionPhase } from "../data/live/connection"; -import { attentionItems } from "../model/attention"; +import { inboxItems } from "../model/inbox"; import { formatDuration } from "../model/time"; import type { Toned } from "../model/tones"; import type { WorkerList } from "../model/workers"; import { useConnection, useLiveResource, useNow } from "./live"; import { useApi, useSession } from "./services"; -export function useAttentionCount(): number | undefined { +export function useInboxCount(): number | undefined { const workers = useLiveResource("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/v1/workers").data?.workers; - return workers === undefined ? undefined : attentionItems(workers).length; + return workers === undefined ? undefined : inboxItems(workers).length; } // why: a 401 at any time signs the operator out; a tab reloaded with a token since revoked finds out From 399089a3db627873784460c064232d7944c34b95 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 00:23:10 +0200 Subject: [PATCH 03/57] test: an absent physical device is a Needs a look item titled with its model and reason (#768) --- ui/src/model/inbox.test.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/ui/src/model/inbox.test.ts b/ui/src/model/inbox.test.ts index 3fd8528a3..a8e2116a5 100644 --- a/ui/src/model/inbox.test.ts +++ b/ui/src/model/inbox.test.ts @@ -171,6 +171,43 @@ describe("the Inbox items", () => { }); }); +describe("the Inbox items of an absent phone", () => { + it("hold an absent phone titled with its model and why, and not a phone in another state", () => { + const phone = ( + id: string, + state: WorkerDevice["state"], + absentReason?: "locked" | "untrusted" | "not-present", + ) => + Object.assign( + device(id, { + class: "phone", + physical: true, + servesDefaultMode: false, + spec: { model: "iPhone 15 Pro", osVersion: "18.4", physical: true, platform: "ios" }, + state, + }), + absentReason === undefined ? {} : { absentReason }, + ); + const workers = [ + worker({ + devices: [ + phone("dev_locked", "absent", "locked"), + phone("dev_untrusted", "absent", "untrusted"), + phone("dev_gone", "absent", "not-present"), + phone("dev_ready", "ready"), + phone("dev_shut", "shutdown"), + ], + }), + ]; + + expect(pageOf(workers).rows.map((row) => [row.key, row.word, row.tone, row.subject])).toEqual([ + ["wrk_1/dev_locked/absent", "absent", "warn", "iPhone 15 Pro is absent (locked)"], + ["wrk_1/dev_untrusted/absent", "absent", "warn", "iPhone 15 Pro is absent (untrusted)"], + ["wrk_1/dev_gone/absent", "absent", "warn", "iPhone 15 Pro is absent (not-present)"], + ]); + }); +}); + describe("the Inbox page", () => { it("lists a row per item, naming the worker or the device on its worker", () => { const page = pageOf([ From af97f6eba776b64a9f80a497111b5f7f5639014a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 00:23:34 +0200 Subject: [PATCH 04/57] feat(console): an absent phone is an Inbox item (#768) --- ui/src/model/inbox.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index 9df4d9c4c..b51698d87 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -26,7 +26,7 @@ export type InboxItem = } | { readonly key: string; - readonly condition: "quarantined" | "stalled"; + readonly condition: "quarantined" | "stalled" | "absent"; readonly worker: WorkerView; readonly device: WorkerDevice; }; @@ -65,6 +65,9 @@ function deviceItems(worker: WorkerView): InboxItem[] { if (device.stalled === true) { return [{ condition: "stalled", device, key: key("stalled"), worker }]; } + if (device.state === "absent") { + return [{ condition: "absent", device, key: key("absent"), worker }]; + } return []; }); } @@ -131,6 +134,10 @@ function protocolText(versions: { readonly min: number; readonly max: number }): } function subjectOf(item: InboxItem): string { + if (item.condition === "absent") { + // why: the daemon names a reason for every absent phone; "not-present" is the plain fallback for a record that lacks one. + return `${item.device.spec.model} is absent (${item.device.absentReason ?? "not-present"})`; + } return "device" in item ? `${item.device.spec.model} on ${workerName(item.worker)}` : workerName(item.worker); From a4546db99e8f378a4d0c3cd893d627a9b3c185e8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 00:39:31 +0200 Subject: [PATCH 05/57] test: a request is an item at 60 001 ms waited and not at 59 999 ms, both by the daemon's now (#768) --- ui/src/model/inbox.test.ts | 31 +++++++++++++++++++++++++++++++ ui/src/model/inbox.ts | 12 +++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/ui/src/model/inbox.test.ts b/ui/src/model/inbox.test.ts index a8e2116a5..2e2827b3d 100644 --- a/ui/src/model/inbox.test.ts +++ b/ui/src/model/inbox.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { inboxItems, inboxPageOf } from "./inbox"; import type { ConsoleEvent } from "./events"; +import type { WaitingRequest } from "./waiting"; import type { WorkerDevice, WorkerView } from "./workers"; const NOW = Date.parse("2026-10-02T12:00:00Z"); @@ -208,6 +209,36 @@ describe("the Inbox items of an absent phone", () => { }); }); +describe("the Inbox items of a long wait", () => { + it("hold a request that has waited over 60 s by the daemon's now, titled with its requester and the wait", () => { + const waiting = (waitedMs: number): WaitingRequest => ({ + createdAt: NOW - waitedMs, + id: "req_1", + queuePosition: 1, + requesterId: "agent-b", + spec: { model: "iPhone 16", platform: "ios" }, + stage: "queued", + }); + const rowsAt = (waitedMs: number) => + inboxPageOf({ + events: [], + key: undefined, + now: NOW, + requests: [waiting(waitedMs)], + workers: [worker()], + }).rows.map((row) => [row.key, row.word, row.tone, row.subject]); + + expect(rowsAt(59_999)).toEqual([]); + expect(rowsAt(60_000)).toEqual([]); + expect(rowsAt(60_001)).toEqual([ + ["request/req_1/waiting", "waiting", "warn", "agent-b has waited 1 min"], + ]); + expect( + inboxItems([worker()], { now: NOW, requests: [waiting(61_000)] }).map((item) => item.key), + ).toEqual(["request/req_1/waiting"]); + }); +}); + describe("the Inbox page", () => { it("lists a row per item, naming the worker or the device on its worker", () => { const page = pageOf([ diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index b51698d87..06f065ad7 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -2,6 +2,7 @@ import { eventSummary, eventTone } from "./activity"; import { type ConsoleEvent, timeOfDay, workerIdOf } from "./events"; import { itemPath } from "./paths"; import { formatDuration } from "./time"; +import type { WaitingRequest } from "./waiting"; import type { Tone } from "./tones"; import { stateEnteredAt, @@ -31,8 +32,16 @@ export type InboxItem = readonly device: WorkerDevice; }; +export interface InboxContext { + readonly now: number; + readonly requests?: readonly WaitingRequest[]; +} + // why: a worker that is both disconnected and drained is two items, since each clears on its own. -export function inboxItems(workers: readonly WorkerView[]): readonly InboxItem[] { +export function inboxItems( + workers: readonly WorkerView[], + _context?: InboxContext, +): readonly InboxItem[] { return workers.flatMap((worker) => [...workerItems(worker), ...deviceItems(worker)]); } @@ -270,6 +279,7 @@ export function inboxPageOf(input: { readonly events: readonly ConsoleEvent[]; readonly now: number; readonly key: string | undefined; + readonly requests?: readonly WaitingRequest[]; }): InboxPage { const items = inboxItems(input.workers); const rows = items.map((item) => ({ From cd80831dd707a49a7c4a967c56696e8a86db7d4e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 00:40:21 +0200 Subject: [PATCH 06/57] feat(console): a request waiting over 60 s is an Inbox item (#768) --- ui/src/model/inbox.test.ts | 6 ++++- ui/src/model/inbox.ts | 51 ++++++++++++++++++++++++++++++-------- ui/src/model/overview.ts | 7 ++---- 3 files changed, 48 insertions(+), 16 deletions(-) diff --git a/ui/src/model/inbox.test.ts b/ui/src/model/inbox.test.ts index 2e2827b3d..832404c7a 100644 --- a/ui/src/model/inbox.test.ts +++ b/ui/src/model/inbox.test.ts @@ -57,7 +57,11 @@ function event(seq: number, name: string, at: number, payload: unknown = {}): Co function summary(workers: readonly WorkerView[]): string[] { return inboxItems(workers).map((item) => - [item.worker.id, "device" in item ? item.device.id : "-", item.condition].join(" "), + [ + "worker" in item ? item.worker.id : "-", + "device" in item ? item.device.id : "-", + item.condition, + ].join(" "), ); } diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index 06f065ad7..4fc1665e0 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -30,8 +30,18 @@ export type InboxItem = readonly condition: "quarantined" | "stalled" | "absent"; readonly worker: WorkerView; readonly device: WorkerDevice; + } + | { + readonly key: string; + readonly condition: "waiting"; + readonly request: WaitingRequest; + readonly waitedMs: number; }; +type WorkerItem = Extract; + +export const WAITING_TOO_LONG_MS = 60_000; + export interface InboxContext { readonly now: number; readonly requests?: readonly WaitingRequest[]; @@ -40,9 +50,25 @@ export interface InboxContext { // why: a worker that is both disconnected and drained is two items, since each clears on its own. export function inboxItems( workers: readonly WorkerView[], - _context?: InboxContext, + context?: InboxContext, ): readonly InboxItem[] { - return workers.flatMap((worker) => [...workerItems(worker), ...deviceItems(worker)]); + return [ + ...workers.flatMap((worker) => [...workerItems(worker), ...deviceItems(worker)]), + ...(context === undefined ? [] : waitingItems(context)), + ]; +} + +// why: a request waits on the daemon's clock, so the wait is counted from the daemon's now; the +// longest wait comes first. +function waitingItems(context: InboxContext): InboxItem[] { + return [...(context.requests ?? [])] + .sort((a, b) => a.createdAt - b.createdAt || (a.id < b.id ? -1 : 1)) + .flatMap((request): InboxItem[] => { + const waitedMs = context.now - request.createdAt; + return waitedMs > WAITING_TOO_LONG_MS + ? [{ condition: "waiting", key: `request/${request.id}/waiting`, request, waitedMs }] + : []; + }); } function workerItems(worker: WorkerView): InboxItem[] { @@ -142,7 +168,10 @@ function protocolText(versions: { readonly min: number; readonly max: number }): : `${versions.min}\u2013${versions.max}`; } -function subjectOf(item: InboxItem): string { +export function inboxSubject(item: InboxItem): string { + if (item.condition === "waiting") { + return `${item.request.requesterId} has waited ${formatDuration(item.waitedMs)}`; + } if (item.condition === "absent") { // why: the daemon names a reason for every absent phone; "not-present" is the plain fallback for a record that lacks one. return `${item.device.spec.model} is absent (${item.device.absentReason ?? "not-present"})`; @@ -152,7 +181,7 @@ function subjectOf(item: InboxItem): string { : workerName(item.worker); } -function factsOf(item: InboxItem, now: number): readonly InboxFact[] { +function factsOf(item: WorkerItem, now: number): readonly InboxFact[] { return "device" in item ? deviceFacts(item, now) : workerFacts(item, now); } @@ -199,7 +228,7 @@ function causeFacts(device: { } function workerFacts( - item: Exclude, + item: Exclude, now: number, ): readonly InboxFact[] { const { worker } = item; @@ -224,7 +253,7 @@ function workerFacts( ]; } -function namesItem(event: ConsoleEvent, item: InboxItem): boolean { +function namesItem(event: ConsoleEvent, item: WorkerItem): boolean { if (workerIdOf(event) === item.worker.id) return true; if (!("device" in item)) return false; const { payload } = event; @@ -236,7 +265,7 @@ function namesItem(event: ConsoleEvent, item: InboxItem): boolean { } function detailOf( - item: InboxItem, + item: WorkerItem, input: { readonly workers: readonly WorkerView[]; readonly events: readonly ConsoleEvent[]; @@ -281,16 +310,18 @@ export function inboxPageOf(input: { readonly key: string | undefined; readonly requests?: readonly WaitingRequest[]; }): InboxPage { - const items = inboxItems(input.workers); + const items = inboxItems(input.workers, input); const rows = items.map((item) => ({ key: item.key, - subject: subjectOf(item), + subject: inboxSubject(item), to: itemPath("/inbox", item.key), tone: inboxTone(item.condition), word: item.condition, })); const named = input.key !== undefined; const chosen = named ? items.find((item) => item.key === input.key) : items[0]; - if (chosen !== undefined) return { named, rows, shown: detailOf(chosen, input) }; + if (chosen !== undefined && "worker" in chosen) { + return { named, rows, shown: detailOf(chosen, input) }; + } return { named, rows, shown: named ? "resolved" : undefined }; } diff --git a/ui/src/model/overview.ts b/ui/src/model/overview.ts index 6be7d7e9e..b92aa0852 100644 --- a/ui/src/model/overview.ts +++ b/ui/src/model/overview.ts @@ -1,5 +1,5 @@ import { eventSummary, eventTone } from "./activity"; -import { inboxItems, inboxTone } from "./inbox"; +import { inboxItems, inboxSubject, inboxTone } from "./inbox"; import type { ConsoleEvent } from "./events"; import { type DeviceSlot, slotsLabel, workerHealth, workerSlots } from "./fleet"; import type { FiguresState } from "./figures"; @@ -195,10 +195,7 @@ export function overviewOf(input: { }), attention: inboxItems(workers).map((item) => ({ key: item.key, - subject: - "device" in item - ? `${item.device.spec.model} on ${workerName(item.worker)}` - : workerName(item.worker), + subject: inboxSubject(item), to: itemPath("/inbox", item.key), tone: inboxTone(item.condition), word: item.condition, From d185884c2bc9ee28ea1ad2d30e8d88b117021a12 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 00:57:16 +0200 Subject: [PATCH 07/57] test: a lease is a heads-up at 4:59 left and not at 5:01, and one past its deadline says ends now; the Leases filter agrees (#768) --- ui/src/model/inbox.test.ts | 39 ++++++++++++++++++++++++++++++++++++++ ui/src/model/inbox.ts | 5 +++++ 2 files changed, 44 insertions(+) diff --git a/ui/src/model/inbox.test.ts b/ui/src/model/inbox.test.ts index 832404c7a..f3cd89077 100644 --- a/ui/src/model/inbox.test.ts +++ b/ui/src/model/inbox.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { inboxItems, inboxPageOf } from "./inbox"; import type { ConsoleEvent } from "./events"; +import { filterLeaseRows, type LeaseRecord, leaseRows, type TokenRecord } from "./leases"; import type { WaitingRequest } from "./waiting"; import type { WorkerDevice, WorkerView } from "./workers"; @@ -243,6 +244,44 @@ describe("the Inbox items of a long wait", () => { }); }); +describe("the Inbox items of a lease about to end", () => { + it("hold a lease with under 5 minutes left as a heads-up, not one with more, and the Leases filter agrees", () => { + const lease = (id: string, leftMs: number): LeaseRecord => ({ + deviceId: "dev_1", + grantedAt: NOW - 60_000, + id, + idChosenByRequester: false, + lastRenewedAt: NOW - 30_000, + ownerId: "tok_1", + requesterId: "tok_1", + ttlDeadline: NOW + leftMs, + ttlMs: 900_000, + }); + const tokens: TokenRecord[] = [ + { createdAt: NOW - 1_000_000, id: "tok_1", label: "ci-runner-3", role: "agent" }, + ]; + const workers = [worker({ devices: [device("dev_1")] })]; + const leases = [ + lease("lse_far", 301_000), + lease("lse_edge", 300_000), + lease("lse_near", 299_000), + lease("lse_past", -1_000), + ]; + + const page = inboxPageOf({ events: [], key: undefined, leases, now: NOW, tokens, workers }); + + expect(page.rows.map((row) => [row.key, row.word, row.subject])).toEqual([ + ["lease/lse_past/ending", "ending", "ci-runner-3 · iPhone 16 ends now"], + ["lease/lse_near/ending", "ending", "ci-runner-3 · iPhone 16 ends in 4:59"], + ]); + expect( + filterLeaseRows(leaseRows({ leases, now: NOW, tokens, workers }), "expiring").map( + (row) => row.id, + ), + ).toEqual(["lse_near", "lse_past"]); + }); +}); + describe("the Inbox page", () => { it("lists a row per item, naming the worker or the device on its worker", () => { const page = pageOf([ diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index 4fc1665e0..3eede8afb 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -1,6 +1,7 @@ import { eventSummary, eventTone } from "./activity"; import { type ConsoleEvent, timeOfDay, workerIdOf } from "./events"; import { itemPath } from "./paths"; +import type { LeaseRecord, TokenRecord } from "./leases"; import { formatDuration } from "./time"; import type { WaitingRequest } from "./waiting"; import type { Tone } from "./tones"; @@ -45,6 +46,8 @@ export const WAITING_TOO_LONG_MS = 60_000; export interface InboxContext { readonly now: number; readonly requests?: readonly WaitingRequest[]; + readonly leases?: readonly LeaseRecord[]; + readonly tokens?: readonly TokenRecord[]; } // why: a worker that is both disconnected and drained is two items, since each clears on its own. @@ -309,6 +312,8 @@ export function inboxPageOf(input: { readonly now: number; readonly key: string | undefined; readonly requests?: readonly WaitingRequest[]; + readonly leases?: readonly LeaseRecord[]; + readonly tokens?: readonly TokenRecord[]; }): InboxPage { const items = inboxItems(input.workers, input); const rows = items.map((item) => ({ From 104a82371357fed39ec5b9780a6cf1ed744a1de7 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 00:57:47 +0200 Subject: [PATCH 08/57] feat(console): a lease with under 5 minutes left is an Inbox heads-up, and the Leases filter says Ending < 5 min (#768) --- e2e/console/leases.spec.ts | 2 +- ui/src/model/inbox.ts | 46 ++++++++++++++++++++++++++++++++++++- ui/src/model/leases.test.ts | 12 +++++----- ui/src/model/leases.ts | 18 +++++++++------ 4 files changed, 63 insertions(+), 15 deletions(-) diff --git a/e2e/console/leases.spec.ts b/e2e/console/leases.spec.ts index 09d2eb117..4951ff204 100644 --- a/e2e/console/leases.spec.ts +++ b/e2e/console/leases.spec.ts @@ -539,7 +539,7 @@ test.describe("the leases page", () => { await expect(leaseRow(page, soon.id)).toBeVisible(); await expect(leaseRow(page, later.id)).toBeVisible(); - await page.getByRole("radio", { name: "Expiring" }).check(); + await page.getByRole("radio", { name: "Ending < 5 min" }).check(); await expect(leaseRow(page, soon.id)).toBeVisible(); await expect(leaseRow(page, later.id)).toHaveCount(0); diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index 3eede8afb..f08534fd3 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -1,7 +1,13 @@ import { eventSummary, eventTone } from "./activity"; import { type ConsoleEvent, timeOfDay, workerIdOf } from "./events"; import { itemPath } from "./paths"; -import type { LeaseRecord, TokenRecord } from "./leases"; +import { + deviceOfLease, + holderName, + isExpiring, + type LeaseRecord, + type TokenRecord, +} from "./leases"; import { formatDuration } from "./time"; import type { WaitingRequest } from "./waiting"; import type { Tone } from "./tones"; @@ -37,6 +43,14 @@ export type InboxItem = readonly condition: "waiting"; readonly request: WaitingRequest; readonly waitedMs: number; + } + | { + readonly key: string; + readonly condition: "ending"; + readonly lease: LeaseRecord; + readonly holder: string; + readonly model: string; + readonly leftMs: number; }; type WorkerItem = Extract; @@ -58,6 +72,7 @@ export function inboxItems( return [ ...workers.flatMap((worker) => [...workerItems(worker), ...deviceItems(worker)]), ...(context === undefined ? [] : waitingItems(context)), + ...(context === undefined ? [] : endingItems(workers, context)), ]; } @@ -74,6 +89,26 @@ function waitingItems(context: InboxContext): InboxItem[] { }); } +// why: a lease's time left counts against the daemon's clock, and the least time left comes first. +function endingItems(workers: readonly WorkerView[], context: InboxContext): InboxItem[] { + const { now, tokens = [] } = context; + return [...(context.leases ?? [])] + .sort((a, b) => a.ttlDeadline - b.ttlDeadline || (a.id < b.id ? -1 : 1)) + .flatMap((lease): InboxItem[] => { + if (!isExpiring(lease.ttlDeadline, now)) return []; + return [ + { + condition: "ending", + holder: holderName(lease.requesterId, tokens), + key: `lease/${lease.id}/ending`, + lease, + leftMs: lease.ttlDeadline - now, + model: deviceOfLease(lease, workers)?.spec.model ?? lease.deviceId, + }, + ]; + }); +} + function workerItems(worker: WorkerView): InboxItem[] { const items: InboxItem[] = []; const key = (condition: string) => `${worker.id}/${condition}`; @@ -171,10 +206,19 @@ function protocolText(versions: { readonly min: number; readonly max: number }): : `${versions.min}\u2013${versions.max}`; } +function minutesAndSeconds(ms: number): string { + const seconds = Math.floor(ms / 1_000); + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; +} + export function inboxSubject(item: InboxItem): string { if (item.condition === "waiting") { return `${item.request.requesterId} has waited ${formatDuration(item.waitedMs)}`; } + if (item.condition === "ending") { + const base = `${item.holder} · ${item.model} ends`; + return item.leftMs <= 0 ? `${base} now` : `${base} in ${minutesAndSeconds(item.leftMs)}`; + } if (item.condition === "absent") { // why: the daemon names a reason for every absent phone; "not-present" is the plain fallback for a record that lacks one. return `${item.device.spec.model} is absent (${item.device.absentReason ?? "not-present"})`; diff --git a/ui/src/model/leases.test.ts b/ui/src/model/leases.test.ts index e398023a2..94812a411 100644 --- a/ui/src/model/leases.test.ts +++ b/ui/src/model/leases.test.ts @@ -140,7 +140,7 @@ describe("the lease list rows", () => { expect(ids(sent.toReversed())).toEqual(ids(sent)); }); - it("marks a lease expiring only when under 15 minutes are left", () => { + it("marks a lease expiring only when under 5 minutes are left", () => { const left = (ms: number) => leaseRows({ leases: [lease({ ttlDeadline: NOW + ms })], @@ -149,8 +149,8 @@ describe("the lease list rows", () => { workers: [], })[0]?.expiring; - expect(left(15 * 60_000 - 1)).toBe(true); - expect(left(15 * 60_000)).toBe(false); + expect(left(5 * 60_000 - 1)).toBe(true); + expect(left(5 * 60_000)).toBe(false); expect(left(-5_000)).toBe(true); }); @@ -290,9 +290,9 @@ describe("a lease's inspection", () => { expect(shown.granted).toBe("07:05"); }); - it("warns once under 15 minutes are left", () => { - const soon = details({ expiresAt: new Date(NOW + 14 * 60_000).toISOString() }); - const later = details({ expiresAt: new Date(NOW + 16 * 60_000).toISOString() }); + it("warns once under 5 minutes are left", () => { + const soon = details({ expiresAt: new Date(NOW + 4 * 60_000).toISOString() }); + const later = details({ expiresAt: new Date(NOW + 6 * 60_000).toISOString() }); expect(inspect({ lease: soon }).expiring).toBe(true); expect(inspect({ lease: later }).expiring).toBe(false); diff --git a/ui/src/model/leases.ts b/ui/src/model/leases.ts index c9c543d27..dd5fb6f18 100644 --- a/ui/src/model/leases.ts +++ b/ui/src/model/leases.ts @@ -60,6 +60,10 @@ function holderTitle(holder: Holder): string { return holder.label ?? holder.id; } +export function holderName(requesterId: string, tokens: readonly TokenRecord[]): string { + return holderTitle(holderOf(requesterId, tokens)); +} + // why: a single host names no worker on its leases, and every lease there is on its one worker, the // host itself. function workerOfLease( @@ -94,7 +98,7 @@ function compare(a: string, b: string): number { return a < b ? -1 : 1; } -function deviceOfLease( +export function deviceOfLease( lease: LeaseRecord, workers: readonly WorkerView[], ): WorkerDevice | undefined { @@ -123,16 +127,16 @@ export type LeaseFilter = "all" | "expiring" | "ios" | "android"; export const LEASE_FILTERS: readonly { readonly value: LeaseFilter; readonly label: string }[] = [ { label: "All", value: "all" }, - { label: "Expiring", value: "expiring" }, + { label: "Ending < 5 min", value: "expiring" }, { label: "iOS", value: "ios" }, { label: "Android", value: "android" }, ]; -// why: a lease with under 15 minutes left has not been renewed for a while, so the list and the -// inspector warn by the same rule. -const EXPIRING_UNDER_MS = 15 * 60_000; +// why: a lease with under 5 minutes left is about to end, so the list, the inspector and the Inbox +// warn by the same rule. +export const EXPIRING_UNDER_MS = 5 * 60_000; -function isExpiring(deadline: number, now: number): boolean { +export function isExpiring(deadline: number, now: number): boolean { return deadline - now < EXPIRING_UNDER_MS; } @@ -176,7 +180,7 @@ export function leaseRows(input: { const sub = [model, worker].filter((part) => part !== undefined).join(" · "); return { expiring: isExpiring(lease.ttlDeadline, now), - holder: holderTitle(holderOf(lease.requesterId, tokens)), + holder: holderName(lease.requesterId, tokens), id: lease.id, key: `${lease.workerId ?? ""} ${lease.id}`, model, From fba5d1ffd78fb439ba2baa1c6bff22ac8f9ba226 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 00:58:25 +0200 Subject: [PATCH 09/57] test: items keep the order given: worker order for problems, longest wait first, least time left first (#768) --- ui/src/model/inbox.test.ts | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/ui/src/model/inbox.test.ts b/ui/src/model/inbox.test.ts index f3cd89077..aa332652c 100644 --- a/ui/src/model/inbox.test.ts +++ b/ui/src/model/inbox.test.ts @@ -282,6 +282,50 @@ describe("the Inbox items of a lease about to end", () => { }); }); +describe("the order of the Inbox items", () => { + it("keeps the order given for problems, puts the longest wait first and the least time left first", () => { + const request = (id: string, waitedMs: number): WaitingRequest => ({ + createdAt: NOW - waitedMs, + id, + queuePosition: 1, + requesterId: "agent-b", + spec: { model: "iPhone 16", platform: "ios" }, + stage: "queued", + }); + const lease = (id: string, leftMs: number): LeaseRecord => ({ + deviceId: "dev_1", + grantedAt: NOW - 60_000, + id, + idChosenByRequester: false, + lastRenewedAt: NOW - 30_000, + ownerId: "tok_1", + requesterId: "tok_1", + ttlDeadline: NOW + leftMs, + ttlMs: 900_000, + }); + const workers = [ + worker({ drained: true, id: "wrk_z" }), + worker({ drained: true, id: "wrk_a", devices: [device("dev_2", { state: "quarantined" })] }), + ]; + + const keys = inboxItems(workers, { + leases: [lease("lse_b", 200_000), lease("lse_a", 100_000)], + now: NOW, + requests: [request("req_new", 70_000), request("req_old", 90_000)], + }).map((item) => item.key); + + expect(keys).toEqual([ + "wrk_z/drained", + "wrk_a/drained", + "wrk_a/dev_2/quarantined", + "request/req_old/waiting", + "request/req_new/waiting", + "lease/lse_a/ending", + "lease/lse_b/ending", + ]); + }); +}); + describe("the Inbox page", () => { it("lists a row per item, naming the worker or the device on its worker", () => { const page = pageOf([ From d03ea62f17f83d3fe40f0b1a8377700650c3c54c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 00:58:37 +0200 Subject: [PATCH 10/57] test: items group as Broken, Needs a look, Heads-up, in that order; the problem count excludes heads-ups (#768) --- ui/src/model/inbox.test.ts | 45 ++++++++++++++++++++++++++++++++++++++ ui/src/model/inbox.ts | 4 ++++ 2 files changed, 49 insertions(+) diff --git a/ui/src/model/inbox.test.ts b/ui/src/model/inbox.test.ts index aa332652c..8ad16fa8f 100644 --- a/ui/src/model/inbox.test.ts +++ b/ui/src/model/inbox.test.ts @@ -326,6 +326,51 @@ describe("the order of the Inbox items", () => { }); }); +describe("the Inbox groups", () => { + it("group the rows as Broken, Needs a look, Heads-up, and count problems without the heads-ups", () => { + const workers = [ + worker({ drained: true, id: "wrk_a" }), + worker({ connection: "disconnected", id: "wrk_b" }), + ]; + const request: WaitingRequest = { + createdAt: NOW - 90_000, + id: "req_1", + queuePosition: 1, + requesterId: "agent-b", + spec: { model: "iPhone 16", platform: "ios" }, + stage: "queued", + }; + const lease: LeaseRecord = { + deviceId: "dev_1", + grantedAt: NOW - 60_000, + id: "lse_1", + idChosenByRequester: false, + lastRenewedAt: NOW - 30_000, + ownerId: "tok_1", + requesterId: "tok_1", + ttlDeadline: NOW + 100_000, + ttlMs: 900_000, + }; + + const page = inboxPageOf({ + events: [], + key: undefined, + leases: [lease], + now: NOW, + requests: [request], + workers, + }); + + expect(page.rows.map((row) => [row.group, row.key])).toEqual([ + ["Broken", "wrk_b/disconnected"], + ["Needs a look", "wrk_a/drained"], + ["Needs a look", "request/req_1/waiting"], + ["Heads-up", "lease/lse_1/ending"], + ]); + expect(page.problems).toBe(3); + }); +}); + describe("the Inbox page", () => { it("lists a row per item, naming the worker or the device on its worker", () => { const page = pageOf([ diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index f08534fd3..85dc22b6f 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -153,7 +153,10 @@ export function inboxTone(condition: InboxItem["condition"]): Tone { : "warn"; } +export type InboxGroup = "Broken" | "Needs a look" | "Heads-up"; + export interface InboxRow { + readonly group?: InboxGroup; readonly key: string; readonly to: string; readonly tone: Tone; @@ -186,6 +189,7 @@ export interface InboxDetail { } export interface InboxPage { + readonly problems?: number; readonly rows: readonly InboxRow[]; // why: a URL can name an item the daemon has since cleared; that is told apart from a list // with nothing in it, which has no item to show at all. From 7ed76115fb663b2eaea1cf8aedf56321e560502d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 00:58:54 +0200 Subject: [PATCH 11/57] feat(console): Inbox rows come in three groups, and the page counts its problems (#768) --- ui/src/model/inbox.ts | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index 85dc22b6f..cd441f52a 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -145,6 +145,18 @@ function deviceItems(worker: WorkerView): InboxItem[] { }); } +const GROUPS: readonly InboxGroup[] = ["Broken", "Needs a look", "Heads-up"]; + +export function inboxGroup(item: InboxItem): InboxGroup { + if (item.condition === "ending") return "Heads-up"; + return inboxTone(item.condition) === "error" ? "Broken" : "Needs a look"; +} + +// why: the Inbox lists its groups in a fixed order, each keeping the order its items came in. +function inGroupOrder(items: readonly InboxItem[]): readonly InboxItem[] { + return GROUPS.flatMap((group) => items.filter((item) => inboxGroup(item) === group)); +} + // why: a lost worker or a quarantined device is broken; everything else on the list needs a look // soon, which is the warning tone, the same split the status words use. export function inboxTone(condition: InboxItem["condition"]): Tone { @@ -156,7 +168,7 @@ export function inboxTone(condition: InboxItem["condition"]): Tone { export type InboxGroup = "Broken" | "Needs a look" | "Heads-up"; export interface InboxRow { - readonly group?: InboxGroup; + readonly group: InboxGroup; readonly key: string; readonly to: string; readonly tone: Tone; @@ -189,7 +201,7 @@ export interface InboxDetail { } export interface InboxPage { - readonly problems?: number; + readonly problems: number; readonly rows: readonly InboxRow[]; // why: a URL can name an item the daemon has since cleared; that is told apart from a list // with nothing in it, which has no item to show at all. @@ -364,7 +376,8 @@ export function inboxPageOf(input: { readonly tokens?: readonly TokenRecord[]; }): InboxPage { const items = inboxItems(input.workers, input); - const rows = items.map((item) => ({ + const rows = inGroupOrder(items).map((item) => ({ + group: inboxGroup(item), key: item.key, subject: inboxSubject(item), to: itemPath("/inbox", item.key), @@ -373,8 +386,9 @@ export function inboxPageOf(input: { })); const named = input.key !== undefined; const chosen = named ? items.find((item) => item.key === input.key) : items[0]; + const problems = items.filter((item) => inboxGroup(item) !== "Heads-up").length; if (chosen !== undefined && "worker" in chosen) { - return { named, rows, shown: detailOf(chosen, input) }; + return { named, problems, rows, shown: detailOf(chosen, input) }; } - return { named, rows, shown: named ? "resolved" : undefined }; + return { named, problems, rows, shown: named ? "resolved" : undefined }; } From 7b658ae4851d11f3b3f81857cb0f0a780b1ac6e8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:07:28 +0200 Subject: [PATCH 12/57] test: Overview with an empty Inbox shows Nothing needs you and no Needs you panel; with a disconnected worker it shows the panel with that item first, and the link All in Inbox (n) (#768) --- e2e/console/overview.spec.ts | 50 +++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/e2e/console/overview.spec.ts b/e2e/console/overview.spec.ts index ffd3bccc3..a00b8740d 100644 --- a/e2e/console/overview.spec.ts +++ b/e2e/console/overview.spec.ts @@ -1,7 +1,16 @@ import type { Page } from "@playwright/test"; import { waitFor } from "../helpers/wait.js"; -import { expect, type RunningDaemon, settled, signIn, startDaemon, test } from "./fixtures.js"; +import { + disposeFleet, + expect, + type RunningDaemon, + settled, + signIn, + startDaemon, + startFleet, + test, +} from "./fixtures.js"; const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; const ONE_DEVICE = { limits: { ios: { maxDevices: 1, maxRunning: 1 }, maxRunning: 1 } }; @@ -272,3 +281,42 @@ test.describe("the Overview's figures", () => { } }); }); + +async function workerConnection(host: RunningDaemon, label: string): Promise { + const { workers } = (await operatorGet(host, "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/v1/workers")) as { + workers: { label?: string; connection: string }[]; + }; + return workers.find((worker) => worker.label === label)?.connection; +} + +test.describe("the Overview's Inbox lines", () => { + test("an empty Inbox shows Nothing needs you and no Needs you panel; a disconnected worker shows the panel with that item first, and All in Inbox (1)", async ({ + page, + }) => { + const fleet = await startFleet([ + { driverScript: { ios: IOS }, label: "worker-a" }, + { driverScript: { ios: IOS }, label: "worker-b" }, + ]); + try { + await openOverview(page, fleet.gateway); + await expect(page.getByText("Nothing needs you")).toBeVisible(); + await expect(page.getByRole("heading", { name: "Needs you" })).toHaveCount(0); + + await (fleet.workers[1] as RunningDaemon).stop(); + await waitFor( + async () => (await workerConnection(fleet.gateway, "worker-b")) === "disconnected", + { + label: "worker-b disconnected", + }, + ); + + const panel = page.getByRole("region", { name: "Needs you" }); + await expect(panel).toBeVisible(); + await expect(page.getByText("Nothing needs you")).toHaveCount(0); + await expect(panel.getByRole("link").first()).toContainText("worker-b"); + await expect(panel.getByRole("link", { name: "All in Inbox (1)" })).toBeVisible(); + } finally { + await disposeFleet(fleet); + } + }); +}); From e904e43c5e1e541de7acf8aab0ee34aca9a19cb6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:09:49 +0200 Subject: [PATCH 13/57] feat(console): Overview says Nothing needs you, or lists the first four Inbox problems with a link to all of them (#768) --- ui/src/model/inbox.ts | 2 +- ui/src/model/overview.test.ts | 9 +++--- ui/src/model/overview.ts | 39 +++++++++++++++++------ ui/src/screens/overview/index.tsx | 35 ++++++++++---------- ui/src/screens/overview/overview.css | 7 ++++ ui/src/screens/overview/overview.test.tsx | 15 ++++++--- ui/src/state/overview.ts | 1 + 7 files changed, 74 insertions(+), 34 deletions(-) diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index cd441f52a..86ef8bbc8 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -153,7 +153,7 @@ export function inboxGroup(item: InboxItem): InboxGroup { } // why: the Inbox lists its groups in a fixed order, each keeping the order its items came in. -function inGroupOrder(items: readonly InboxItem[]): readonly InboxItem[] { +export function inGroupOrder(items: readonly InboxItem[]): readonly InboxItem[] { return GROUPS.flatMap((group) => items.filter((item) => inboxGroup(item) === group)); } diff --git a/ui/src/model/overview.test.ts b/ui/src/model/overview.test.ts index f28181530..f7a83b562 100644 --- a/ui/src/model/overview.test.ts +++ b/ui/src/model/overview.test.ts @@ -160,13 +160,14 @@ describe("the overview", () => { ]); }); - it("lists what needs attention, each linked to its own page and toned by how bad it is", () => { - const { attention } = overviewOf({ events: [], now: NOW, requests: [], workers: fleet }); + it("lists what needs you in the Inbox's order, each linked to its own page and toned by how bad it is", () => { + const { inbox } = overviewOf({ events: [], now: NOW, requests: [], workers: fleet }); - expect(attention.map((item) => [item.word, item.tone, item.subject, item.to])).toEqual([ - ["drained", "warn", "mini-2", "/inbox/mini-2%2Fdrained"], + expect(inbox.problems).toBe(3); + expect(inbox.needsYou.map((item) => [item.word, item.tone, item.subject, item.to])).toEqual([ ["quarantined", "error", "Pixel 8 on mini-2", "/inbox/mini-2%2Fd%2Fquarantined"], ["disconnected", "error", "down-1", "/inbox/down-1%2Fdisconnected"], + ["drained", "warn", "mini-2", "/inbox/mini-2%2Fdrained"], ]); }); diff --git a/ui/src/model/overview.ts b/ui/src/model/overview.ts index b92aa0852..b676c4ac1 100644 --- a/ui/src/model/overview.ts +++ b/ui/src/model/overview.ts @@ -1,5 +1,5 @@ import { eventSummary, eventTone } from "./activity"; -import { inboxItems, inboxSubject, inboxTone } from "./inbox"; +import { inboxGroup, inboxItems, inGroupOrder, inboxSubject, inboxTone } from "./inbox"; import type { ConsoleEvent } from "./events"; import { type DeviceSlot, slotsLabel, workerHealth, workerSlots } from "./fleet"; import type { FiguresState } from "./figures"; @@ -64,16 +64,22 @@ export interface OverviewActivity { readonly to: string; } +export interface OverviewInbox { + readonly problems: number; + readonly needsYou: readonly OverviewItem[]; +} + export interface Overview { readonly tiles: readonly OverviewTile[]; readonly figures: FiguresState; readonly platforms: readonly PlatformUse[]; readonly workers: readonly OverviewWorker[]; - readonly attention: readonly OverviewItem[]; + readonly inbox: OverviewInbox; readonly activity: readonly OverviewActivity[]; } const ACTIVITY_ROWS = 8; +const NEEDS_YOU_ROWS = 4; function percentOf(part: number, whole: number): number { return whole === 0 ? 0 : (part / whole) * 100; @@ -167,6 +173,27 @@ function tiles( ]; } +// why: Needs you lists problems only, in the Inbox's own order, so its first rows are the Inbox's. +function inboxOf( + workers: readonly WorkerView[], + requests: readonly WaitingRequest[], + now: number, +): OverviewInbox { + const problems = inGroupOrder(inboxItems(workers, { now, requests })).filter( + (item) => inboxGroup(item) !== "Heads-up", + ); + return { + needsYou: problems.slice(0, NEEDS_YOU_ROWS).map((item) => ({ + key: item.key, + subject: inboxSubject(item), + to: itemPath("/inbox", item.key), + tone: inboxTone(item.condition), + word: item.condition, + })), + problems: problems.length, + }; +} + // why: the overview reads three routes the other pages read too, and every figure on it is worked // out here from those, so a figure on the overview and the same figure on its page always agree. export function overviewOf(input: { @@ -193,13 +220,7 @@ export function overviewOf(input: { ...(tone === undefined ? {} : { tone }), }; }), - attention: inboxItems(workers).map((item) => ({ - key: item.key, - subject: inboxSubject(item), - to: itemPath("/inbox", item.key), - tone: inboxTone(item.condition), - word: item.condition, - })), + inbox: inboxOf(workers, requests, now), figures, platforms, tiles: [ diff --git a/ui/src/screens/overview/index.tsx b/ui/src/screens/overview/index.tsx index 9b79f3d14..321832b81 100644 --- a/ui/src/screens/overview/index.tsx +++ b/ui/src/screens/overview/index.tsx @@ -26,7 +26,7 @@ import { type Gauge, type Overview, type OverviewActivity, - type OverviewItem, + type OverviewInbox, type OverviewWorker, type PlatformUse, useOverview, @@ -121,9 +121,7 @@ export function OverviewBody(props: {
      - - - + All events}> @@ -215,19 +213,24 @@ function WorkerTable({ workers }: { readonly workers: readonly OverviewWorker[] ); } -function AttentionList({ items }: { readonly items: readonly OverviewItem[] }) { - if (items.length === 0) return Nothing needs attention.; +function NeedsYou({ inbox }: { readonly inbox: OverviewInbox }) { + if (inbox.problems === 0) return

      Nothing needs you

      ; return ( -
        - {items.map((item) => ( -
      • - - {item.word} - {item.subject} - -
      • - ))} -
      + +
        + {inbox.needsYou.map((item) => ( +
      • + + {item.word} + {item.subject} + +
      • + ))} +
      +

      + {`All in Inbox (${inbox.problems})`} +

      +
      ); } diff --git a/ui/src/screens/overview/overview.css b/ui/src/screens/overview/overview.css index 015daa6df..9047de711 100644 --- a/ui/src/screens/overview/overview.css +++ b/ui/src/screens/overview/overview.css @@ -152,3 +152,10 @@ margin: 0; font-size: var(--text-sm); } + +.overview-all { + margin: 0; + padding: var(--space-3) var(--space-4); + border-top: 1px solid var(--border); + font-size: var(--text-sm); +} diff --git a/ui/src/screens/overview/overview.test.tsx b/ui/src/screens/overview/overview.test.tsx index 3f2d18659..2cf5bc312 100644 --- a/ui/src/screens/overview/overview.test.tsx +++ b/ui/src/screens/overview/overview.test.tsx @@ -16,19 +16,19 @@ function text(html: string): string { const quiet: Overview = { activity: [], - attention: [], figures: { kind: "loading" }, + inbox: { needsYou: [], problems: 0 }, platforms: [], tiles: [], workers: [], }; describe("the overview screen", () => { - it("says so in one line where a fleet has no workers, nothing needs attention and nothing happened", () => { + it("says so in one line where a fleet has no workers, nothing needs you and nothing happened", () => { const shown = text(renderToStaticMarkup()); expect(shown).toContain("No workers have connected."); - expect(shown).toContain("Nothing needs attention."); + expect(shown).toContain("Nothing needs you"); expect(shown).toContain("No events in the last hour."); }); @@ -150,7 +150,14 @@ describe("the overview screen", () => { expect(shown.split("The stats are not allowed.")).toHaveLength(3); expect(shown.indexOf("The stats are not allowed.")).toBeGreaterThan(shown.indexOf("Workers 0")); - for (const kept of ["Utilisation", "Leases", "Waiting", "Capacity", "Attention", "Activity"]) { + for (const kept of [ + "Utilisation", + "Leases", + "Waiting", + "Capacity", + "Nothing needs you", + "Activity", + ]) { expect(shown, kept).toContain(kept); } expect(shown).toContain("No workers have connected."); diff --git a/ui/src/state/overview.ts b/ui/src/state/overview.ts index 9490dbee1..de99279c4 100644 --- a/ui/src/state/overview.ts +++ b/ui/src/state/overview.ts @@ -11,6 +11,7 @@ import { bothViews, loadView, mapView } from "./resource"; export type { Overview, OverviewActivity, + OverviewInbox, OverviewItem, OverviewWorker, Gauge, From 64dae0391064a4ce32eead0af0078b035772c2d6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:10:35 +0200 Subject: [PATCH 14/57] test: with five problem items the panel shows four, and a row opens /inbox/ (#768) --- e2e/console/overview.spec.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/e2e/console/overview.spec.ts b/e2e/console/overview.spec.ts index a00b8740d..ce43b38e8 100644 --- a/e2e/console/overview.spec.ts +++ b/e2e/console/overview.spec.ts @@ -4,6 +4,7 @@ import { waitFor } from "../helpers/wait.js"; import { disposeFleet, expect, + joinOldWorker, type RunningDaemon, settled, signIn, @@ -319,4 +320,37 @@ test.describe("the Overview's Inbox lines", () => { await disposeFleet(fleet); } }); + + test("with five problem items the panel shows four, and a row opens /inbox/", async ({ + page, + }) => { + const gateway = await startDaemon("gateway"); + const hangUps: (() => void)[] = []; + try { + for (let index = 1; index <= 5; index += 1) { + hangUps.push( + await joinOldWorker(gateway, { id: `wrk_old_${index}`, label: `old-${index}` }), + ); + } + await waitFor( + async () => { + const { workers } = (await operatorGet(gateway, "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/v1/workers")) as { + workers: { connection: string }[]; + }; + return workers.filter((worker) => worker.connection === "incompatible").length === 5; + }, + { label: "five incompatible workers" }, + ); + await openOverview(page, gateway); + + const panel = page.getByRole("region", { name: "Needs you" }); + await expect(panel.getByRole("listitem")).toHaveCount(4); + await expect(panel.getByRole("link", { name: "All in Inbox (5)" })).toBeVisible(); + await panel.getByRole("listitem").first().getByRole("link").click(); + await expect(page).toHaveURL(/\/inbox\/wrk_old_\d%2Fincompatible$/); + } finally { + for (const hangUp of hangUps) hangUp(); + await gateway.dispose(); + } + }); }); From 56a1491c715c57406975ebb06b88b64798c2ec3e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:11:33 +0200 Subject: [PATCH 15/57] test: with /v1/lease-requests stubbed to fail, Overview says Could not check: waiting requests and not Nothing needs you (#768) --- e2e/console/overview.spec.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/e2e/console/overview.spec.ts b/e2e/console/overview.spec.ts index ce43b38e8..dc9aeaf0a 100644 --- a/e2e/console/overview.spec.ts +++ b/e2e/console/overview.spec.ts @@ -353,4 +353,26 @@ test.describe("the Overview's Inbox lines", () => { await gateway.dispose(); } }); + + test("with /v1/lease-requests stubbed to fail, Overview says Could not check: waiting requests and not Nothing needs you", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await page.route( + (url) => url.pathname === "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/v1/lease-requests", + (route) => + route.fulfill({ + json: { error: { code: "INTERNAL", message: "The queue is down." } }, + status: 500, + }), + ); + await openOverview(page, host); + + await expect(page.getByText("Could not check: waiting requests")).toBeVisible(); + await expect(page.getByText("Nothing needs you")).toHaveCount(0); + } finally { + await host.dispose(); + } + }); }); From b2b79378ca3b99241273871a77fe27876d8027ee Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:12:33 +0200 Subject: [PATCH 16/57] feat(console): Overview says Could not check: waiting requests when that read failed, and never Nothing needs you then (#768) --- ui/src/model/overview.ts | 27 +++++++++++++++++------ ui/src/screens/overview/index.tsx | 8 ++++++- ui/src/screens/overview/overview.test.tsx | 2 +- ui/src/state/overview.ts | 7 ++++-- 4 files changed, 33 insertions(+), 11 deletions(-) diff --git a/ui/src/model/overview.ts b/ui/src/model/overview.ts index b676c4ac1..c09e3a30f 100644 --- a/ui/src/model/overview.ts +++ b/ui/src/model/overview.ts @@ -65,6 +65,8 @@ export interface OverviewActivity { } export interface OverviewInbox { + // why: a read that failed leaves the Inbox unchecked there, so the page never says it is clear. + readonly couldNotCheck: readonly string[]; readonly problems: number; readonly needsYou: readonly OverviewItem[]; } @@ -174,11 +176,13 @@ function tiles( } // why: Needs you lists problems only, in the Inbox's own order, so its first rows are the Inbox's. -function inboxOf( - workers: readonly WorkerView[], - requests: readonly WaitingRequest[], - now: number, -): OverviewInbox { +function inboxOf(input: { + readonly workers: readonly WorkerView[]; + readonly requests: readonly WaitingRequest[]; + readonly couldNotCheck: readonly string[]; + readonly now: number; +}): OverviewInbox { + const { couldNotCheck, now, requests, workers } = input; const problems = inGroupOrder(inboxItems(workers, { now, requests })).filter( (item) => inboxGroup(item) !== "Heads-up", ); @@ -190,6 +194,7 @@ function inboxOf( tone: inboxTone(item.condition), word: item.condition, })), + couldNotCheck, problems: problems.length, }; } @@ -201,9 +206,17 @@ export function overviewOf(input: { readonly requests: readonly WaitingRequest[]; readonly events: readonly ConsoleEvent[]; readonly figures?: FiguresState; + readonly couldNotCheck?: readonly string[]; readonly now: number; }): Overview { - const { events, figures = { kind: "loading" }, now, requests, workers } = input; + const { + couldNotCheck = [], + events, + figures = { kind: "loading" }, + now, + requests, + workers, + } = input; const platforms = [platformUse(workers, "ios"), platformUse(workers, "android")]; return { activity: [...events] @@ -220,7 +233,7 @@ export function overviewOf(input: { ...(tone === undefined ? {} : { tone }), }; }), - inbox: inboxOf(workers, requests, now), + inbox: inboxOf({ couldNotCheck, now, requests, workers }), figures, platforms, tiles: [ diff --git a/ui/src/screens/overview/index.tsx b/ui/src/screens/overview/index.tsx index 321832b81..f43fbdc1c 100644 --- a/ui/src/screens/overview/index.tsx +++ b/ui/src/screens/overview/index.tsx @@ -214,7 +214,13 @@ function WorkerTable({ workers }: { readonly workers: readonly OverviewWorker[] } function NeedsYou({ inbox }: { readonly inbox: OverviewInbox }) { - if (inbox.problems === 0) return

      Nothing needs you

      ; + const unchecked = + inbox.couldNotCheck.length === 0 ? null : ( +

      {`Could not check: ${inbox.couldNotCheck.join(", ")}`}

      + ); + if (inbox.problems === 0) { + return unchecked ??

      Nothing needs you

      ; + } return (
        diff --git a/ui/src/screens/overview/overview.test.tsx b/ui/src/screens/overview/overview.test.tsx index 2cf5bc312..b2b7f8051 100644 --- a/ui/src/screens/overview/overview.test.tsx +++ b/ui/src/screens/overview/overview.test.tsx @@ -17,7 +17,7 @@ function text(html: string): string { const quiet: Overview = { activity: [], figures: { kind: "loading" }, - inbox: { needsYou: [], problems: 0 }, + inbox: { couldNotCheck: [], needsYou: [], problems: 0 }, platforms: [], tiles: [], workers: [], diff --git a/ui/src/state/overview.ts b/ui/src/state/overview.ts index de99279c4..0a3cf73bb 100644 --- a/ui/src/state/overview.ts +++ b/ui/src/state/overview.ts @@ -22,9 +22,11 @@ export function useOverview(range: ConsoleRange): LoadView { const workers = loadView(useLiveResource("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/v1/workers")); const asked = loadView(useLiveResource("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/v1/lease-requests")); // why: a daemon that keeps no queue of its own answers 501; the overview then counts no waiting - // requests instead of hiding the whole fleet behind "not available". + // requests instead of hiding the whole fleet behind "not available". A read that failed is not + // that: the fleet still shows, and the Inbox line says what could not be checked. + const failed = asked.kind === "refused"; const waiting: LoadView = - asked.kind === "unsupported" ? { data: { requests: [] }, kind: "ready" } : asked; + asked.kind === "unsupported" || failed ? { data: { requests: [] }, kind: "ready" } : asked; const events = loadView(useRecentEvents()); const figures = useFigures(range); const now = useNow(); @@ -32,6 +34,7 @@ export function useOverview(range: ConsoleRange): LoadView { return mapView(reads, ([[workerList, waitingList], recent]) => overviewOf({ events: recent, + couldNotCheck: failed ? ["waiting requests"] : [], figures, now: now.server, requests: waitingList.requests, From 98f513e771881d2ef000c332998ffd583cca777c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:14:24 +0200 Subject: [PATCH 17/57] test: Overview shows the five numbers with the daemon's values, and Ending soon counts a lease with 4 minutes left and not one with 10 (#768) --- e2e/console/overview.spec.ts | 95 +++++++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 1 deletion(-) diff --git a/e2e/console/overview.spec.ts b/e2e/console/overview.spec.ts index dc9aeaf0a..49e5fcdc0 100644 --- a/e2e/console/overview.spec.ts +++ b/e2e/console/overview.spec.ts @@ -1,4 +1,4 @@ -import type { Page } from "@playwright/test"; +import type { Page, Route } from "@playwright/test"; import { waitFor } from "../helpers/wait.js"; import { @@ -376,3 +376,96 @@ test.describe("the Overview's Inbox lines", () => { } }); }); + +test.describe("the Overview's five numbers", () => { + test("show the daemon's values: one lease held of four devices with three ready, one request waiting with its longest wait, two of two workers, Wait p95, and Ending soon counting a lease with 4 minutes left and not one with 10", async ({ + page, + }) => { + const fleet = await startFleet([ + { driverScript: { ios: IOS }, label: "worker-a" }, + { driverScript: { ios: IOS }, label: "worker-b" }, + ]); + try { + const held: string[] = []; + for (const agent of ["one", "two", "three", "four"]) { + const granted = await fleet.gateway.cli([...LEASE, "--agent-id", agent, "--detach"]); + expect(granted.code, granted.stderr).toBe(0); + held.push((granted.json as { lease: { id: string } }).lease.id); + } + for (const id of held.slice(1)) { + const released = await fleet.gateway.cli(["release", id]); + expect(released.code, released.stderr).toBe(0); + } + await waitFor( + async () => { + const { workers } = (await operatorGet(fleet.gateway, "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/v1/workers")) as { + workers: { devices: { state: string }[] }[]; + }; + const states = workers.flatMap((worker) => worker.devices.map((device) => device.state)); + return states.length === 4 && states.filter((state) => state === "ready").length === 3; + }, + { label: "four devices, three ready" }, + ); + // why: a request is stubbed as waiting 2 minutes and a lease as ending, at times a real daemon cannot reach quickly, + // each counted from the daemon's own clock (its Date header). + await page.route( + (url) => url.pathname === "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/v1/lease-requests", + async (route: Route) => { + const response = await route.fetch(); + const now = new Date(response.headers().date ?? "").getTime(); + await route.fulfill({ + json: { + requests: [ + { + createdAt: now - 125_000, + id: "req_stub", + platform: "ios", + queuePosition: 1, + requesterId: "stub", + stage: "queued", + }, + ], + }, + response, + }); + }, + ); + await page.route( + (url) => url.pathname === "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/v1/leases", + async (route: Route) => { + const response = await route.fetch(); + const now = new Date(response.headers().date ?? "").getTime(); + const { leases } = (await response.json()) as { + leases: { id: string; ttlDeadline: number }[]; + }; + const [first] = leases; + if (first === undefined) throw new Error("the daemon lists no lease"); + await route.fulfill({ + json: { + leases: [ + { ...first, ttlDeadline: now + 4 * 60_000 }, + { ...first, id: "lease-later", ttlDeadline: now + 10 * 60_000 }, + ], + }, + response, + }); + }, + ); + + await openOverview(page, fleet.gateway); + + const stats = await statsOf(fleet.gateway, "1h"); + await expect.poll(() => tileText(page, "Leased")).toBe("Leased | 1 | of 4 · 3 ready"); + await expect + .poll(() => tileText(page, "Waiting")) + .toMatch(/^Waiting \| 1 \| longest 2 min \d+ s$/); + await expect.poll(() => tileText(page, "Workers")).toBe("Workers | 2 | of 2"); + await expect + .poll(() => tileText(page, "Wait p95")) + .toBe(`Wait p95 | ${waitText(stats.totals.wait.p95)} | last hour`); + await expect.poll(() => tileText(page, "Ending soon")).toBe("Ending soon | 1 | under 5 min"); + } finally { + await disposeFleet(fleet); + } + }); +}); From 0ac03dcc43b91bbf4ecb141470390b7ecab43d97 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:17:29 +0200 Subject: [PATCH 18/57] feat(console): Overview shows Leased, Waiting, Workers, Wait p95 and Ending soon, and reads the leases and tokens (#768) --- ui/src/model/inbox.ts | 6 +- ui/src/model/overview.test.ts | 49 +++++----------- ui/src/model/overview.ts | 68 +++++++++++++++-------- ui/src/screens/overview/index.tsx | 7 ++- ui/src/screens/overview/overview.test.tsx | 13 +++-- ui/src/state/overview.ts | 11 +++- 6 files changed, 84 insertions(+), 70 deletions(-) diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index 86ef8bbc8..d2419d9d6 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -59,9 +59,9 @@ export const WAITING_TOO_LONG_MS = 60_000; export interface InboxContext { readonly now: number; - readonly requests?: readonly WaitingRequest[]; - readonly leases?: readonly LeaseRecord[]; - readonly tokens?: readonly TokenRecord[]; + readonly requests?: readonly WaitingRequest[] | undefined; + readonly leases?: readonly LeaseRecord[] | undefined; + readonly tokens?: readonly TokenRecord[] | undefined; } // why: a worker that is both disconnected and drained is two items, since each clears on its own. diff --git a/ui/src/model/overview.test.ts b/ui/src/model/overview.test.ts index f7a83b562..e9a3b471a 100644 --- a/ui/src/model/overview.test.ts +++ b/ui/src/model/overview.test.ts @@ -94,54 +94,33 @@ describe("the overview", () => { waitP95: 38_000, }); - const { tiles } = overviewOf({ + const { ending, tiles, wait } = overviewOf({ events, figures: { data: figuresOf(stats, "1h", NOW), kind: "ready" }, + leases: [], now: NOW, requests, workers: fleet, }); - expect(tiles.map((tile) => [tile.label, tile.value, tile.unit])).toEqual([ - ["Utilisation", "17", "%"], - ["Leases", "2", "of 12"], + const shown = [...tiles, wait, ending]; + expect(shown.map((tile) => [tile?.label, tile?.value, tile?.unit])).toEqual([ + ["Leased", "2", "of 4 · 1 ready"], ["Waiting", "1", "longest 1 min 14 s"], - ["Workers", "2", "of 3 up"], - ["Granted", "3", "last hour"], + ["Workers", "2", "of 3"], ["Wait p95", "38 s", "last hour"], + ["Ending soon", "0", "under 5 min"], ]); - expect(tiles.find((tile) => tile.label === "Granted")?.to).toBe("/usage"); }); - it("links the Granted tile to /usage from 1h and to /usage?range=6h, 24h and 7d from the others", () => { - const links = (["1h", "6h", "24h", "7d"] as const).map((range) => { - const stats = statsOf({ bucketMs: 60_000, from: NOW - 60 * 60_000, granted: 3, to: NOW }); - const { tiles } = overviewOf({ - events: [], - figures: { data: figuresOf(stats, range, NOW), kind: "ready" }, - now: NOW, - requests: [], - workers: fleet, - }); - return tiles.find((tile) => tile.label === "Granted")?.to; - }); - - expect(links).toEqual(["/usage", "/usage?range=6h", "/usage?range=24h", "/usage?range=7d"]); - }); - - it("shows only the fleet's four tiles while the daemon's figures are loading or refused", () => { + it("has no Wait p95 tile while the daemon's figures are loading or refused", () => { const shown = [{ kind: "loading" }, { kind: "refused", message: "no" }] as const; - const labels = shown.map((figures) => - overviewOf({ events: [], figures, now: NOW, requests: [], workers: fleet }).tiles.map( - (tile) => tile.label, - ), + const waits = shown.map( + (figures) => overviewOf({ events: [], figures, now: NOW, requests: [], workers: fleet }).wait, ); - expect(labels).toEqual([ - ["Utilisation", "Leases", "Waiting", "Workers"], - ["Utilisation", "Leases", "Waiting", "Workers"], - ]); + expect(waits).toEqual([undefined, undefined]); }); it("splits each platform's limit into leased, ready and booting, counting connected workers only", () => { @@ -260,8 +239,7 @@ describe("the overview", () => { const alone = overviewOf({ events, now: NOW, requests: [], workers: [unread("mini-3")] }); expect(alone.tiles.map((tile) => [tile.label, tile.value])).toEqual([ - ["Utilisation", "—"], - ["Leases", "—"], + ["Leased", "—"], ["Waiting", "0"], ["Workers", "1"], ]); @@ -285,8 +263,7 @@ describe("the overview", () => { }); expect(mixed.tiles.map((tile) => [tile.label, tile.value])).toEqual([ - ["Utilisation", "—"], - ["Leases", "—"], + ["Leased", "—"], ["Waiting", "0"], ["Workers", "2"], ]); diff --git a/ui/src/model/overview.ts b/ui/src/model/overview.ts index c09e3a30f..8297593ba 100644 --- a/ui/src/model/overview.ts +++ b/ui/src/model/overview.ts @@ -1,5 +1,13 @@ import { eventSummary, eventTone } from "./activity"; -import { inboxGroup, inboxItems, inGroupOrder, inboxSubject, inboxTone } from "./inbox"; +import { + inboxGroup, + type InboxContext, + inboxItems, + inGroupOrder, + inboxSubject, + inboxTone, +} from "./inbox"; +import { isExpiring, type LeaseRecord, type TokenRecord } from "./leases"; import type { ConsoleEvent } from "./events"; import { type DeviceSlot, slotsLabel, workerHealth, workerSlots } from "./fleet"; import type { FiguresState } from "./figures"; @@ -73,6 +81,8 @@ export interface OverviewInbox { export interface Overview { readonly tiles: readonly OverviewTile[]; + readonly wait?: OverviewTile; + readonly ending: OverviewTile; readonly figures: FiguresState; readonly platforms: readonly PlatformUse[]; readonly workers: readonly OverviewWorker[]; @@ -140,25 +150,21 @@ function overviewWorker(worker: WorkerView): OverviewWorker { function tiles( workers: readonly WorkerView[], requests: readonly WaitingRequest[], - platforms: readonly PlatformUse[], now: number, ): readonly OverviewTile[] { const held = leasesHeld(workers); - const limit = platforms.reduce((sum, platform) => sum + (platform.limit ?? 0), 0); const connected = workers.filter((worker) => worker.connection === "connected").length; const oldest = Math.min(...requests.map((request) => request.createdAt)); - const unknown = held === undefined; + const devices = workers.flatMap((worker) => + (worker.devices ?? []).filter((entry) => entry.state !== "deleted"), + ); + const ready = devices.filter((entry) => entry.state === "ready").length; return [ { - label: "Utilisation", - ...(unknown ? {} : { unit: "%" }), - value: unknown ? "—" : String(Math.round(percentOf(held, limit))), - }, - { - label: "Leases", + label: "Leased", to: "/leases", - ...(unknown ? {} : { unit: `of ${formatCount(limit)}` }), - value: unknown ? "—" : formatCount(held), + ...(held === undefined ? {} : { unit: `of ${formatCount(devices.length)} · ${ready} ready` }), + value: held === undefined ? "—" : formatCount(held), }, { label: "Waiting", @@ -169,21 +175,32 @@ function tiles( { label: "Workers", to: "/fleet", - unit: `of ${formatCount(workers.length)} up`, + unit: `of ${formatCount(workers.length)}`, value: formatCount(connected), }, ]; } +// why: the same rule the Leases filter and the Inbox use, against the daemon's clock; a failed read +// of the leases is "not known", not none. +function endingSoon(leases: readonly LeaseRecord[] | undefined, now: number): OverviewTile { + const count = leases?.filter((lease) => isExpiring(lease.ttlDeadline, now)).length; + return { + label: "Ending soon", + to: "/leases", + ...(count === undefined ? {} : { unit: "under 5 min" }), + value: count === undefined ? "—" : formatCount(count), + }; +} + // why: Needs you lists problems only, in the Inbox's own order, so its first rows are the Inbox's. function inboxOf(input: { readonly workers: readonly WorkerView[]; - readonly requests: readonly WaitingRequest[]; readonly couldNotCheck: readonly string[]; - readonly now: number; + readonly context: InboxContext; }): OverviewInbox { - const { couldNotCheck, now, requests, workers } = input; - const problems = inGroupOrder(inboxItems(workers, { now, requests })).filter( + const { context, couldNotCheck, workers } = input; + const problems = inGroupOrder(inboxItems(workers, context)).filter( (item) => inboxGroup(item) !== "Heads-up", ); return { @@ -205,6 +222,8 @@ export function overviewOf(input: { readonly workers: readonly WorkerView[]; readonly requests: readonly WaitingRequest[]; readonly events: readonly ConsoleEvent[]; + readonly leases?: readonly LeaseRecord[] | undefined; + readonly tokens?: readonly TokenRecord[] | undefined; readonly figures?: FiguresState; readonly couldNotCheck?: readonly string[]; readonly now: number; @@ -213,8 +232,10 @@ export function overviewOf(input: { couldNotCheck = [], events, figures = { kind: "loading" }, + leases, now, requests, + tokens, workers, } = input; const platforms = [platformUse(workers, "ios"), platformUse(workers, "android")]; @@ -233,13 +254,16 @@ export function overviewOf(input: { ...(tone === undefined ? {} : { tone }), }; }), - inbox: inboxOf({ couldNotCheck, now, requests, workers }), + ending: endingSoon(leases, now), + inbox: inboxOf({ + context: { leases, now, requests, tokens }, + couldNotCheck, + workers, + }), figures, platforms, - tiles: [ - ...tiles(workers, requests, platforms, now), - ...(figures.kind === "ready" ? [figures.data.granted, figures.data.wait] : []), - ], + tiles: tiles(workers, requests, now), + ...(figures.kind === "ready" ? { wait: figures.data.wait } : {}), workers: workers.map(overviewWorker), }; } diff --git a/ui/src/screens/overview/index.tsx b/ui/src/screens/overview/index.tsx index f43fbdc1c..a1b1d0dc4 100644 --- a/ui/src/screens/overview/index.tsx +++ b/ui/src/screens/overview/index.tsx @@ -80,13 +80,16 @@ export function OverviewBody(props: { {overview.tiles.map((tile) => ( ))} - {ready === undefined ? ( + {overview.wait === undefined ? (
      • - ) : null} + ) : ( + + )} + {leases === undefined ? ( diff --git a/ui/src/screens/overview/overview.test.tsx b/ui/src/screens/overview/overview.test.tsx index b2b7f8051..194eceb68 100644 --- a/ui/src/screens/overview/overview.test.tsx +++ b/ui/src/screens/overview/overview.test.tsx @@ -17,6 +17,7 @@ function text(html: string): string { const quiet: Overview = { activity: [], figures: { kind: "loading" }, + ending: { label: "Ending soon", value: "0" }, inbox: { couldNotCheck: [], needsYou: [], problems: 0 }, platforms: [], tiles: [], @@ -127,7 +128,7 @@ describe("the overview screen", () => { ); expect(partial).toContain("Figures cover from today 10:30."); - expect(partial.indexOf("Figures cover from")).toBeLessThan(partial.indexOf("Utilisation")); + expect(partial.indexOf("Figures cover from")).toBeLessThan(partial.indexOf("Leased")); expect(whole).not.toContain("Figures cover from"); }); @@ -151,9 +152,9 @@ describe("the overview screen", () => { expect(shown.split("The stats are not allowed.")).toHaveLength(3); expect(shown.indexOf("The stats are not allowed.")).toBeGreaterThan(shown.indexOf("Workers 0")); for (const kept of [ - "Utilisation", - "Leases", + "Leased", "Waiting", + "Ending soon", "Capacity", "Nothing needs you", "Activity", @@ -161,7 +162,7 @@ describe("the overview screen", () => { expect(shown, kept).toContain(kept); } expect(shown).toContain("No workers have connected."); - for (const gone of ["Granted", "Wait p95", "Leases held, last hour"]) { + for (const gone of ["Wait p95", "Leases held, last hour"]) { expect(shown, gone).not.toContain(gone); } }); @@ -177,7 +178,7 @@ describe("the overview screen", () => { ); expect(shown.split("The stats are not allowed.")).toHaveLength(2); - expect(shown.indexOf("The stats are not allowed.")).toBeLessThan(shown.indexOf("Granted")); + expect(shown.indexOf("The stats are not allowed.")).toBeLessThan(shown.indexOf("Wait p95")); expect(shown).toContain("Wait p95"); expect(shown).toContain("Leases held, last 6 hours"); }); @@ -194,7 +195,7 @@ describe("the overview screen", () => { ); expect(shown.split("Loading…")).toHaveLength(3); - expect(shown).toContain("Utilisation"); + expect(shown).toContain("Leased"); expect(shown).not.toContain("Wait p95"); }); }); diff --git a/ui/src/state/overview.ts b/ui/src/state/overview.ts index 0a3cf73bb..d4cd23311 100644 --- a/ui/src/state/overview.ts +++ b/ui/src/state/overview.ts @@ -1,5 +1,6 @@ import type { LoadView } from "../ds/loaded"; import { overviewOf, type Overview } from "../model/overview"; +import type { LeaseList, TokenList } from "../model/leases"; import type { ConsoleRange } from "../model/range"; import type { WaitingList } from "../model/waiting"; import type { WorkerList } from "../model/workers"; @@ -25,6 +26,12 @@ export function useOverview(range: ConsoleRange): LoadView { // requests instead of hiding the whole fleet behind "not available". A read that failed is not // that: the fleet still shows, and the Inbox line says what could not be checked. const failed = asked.kind === "refused"; + const leases = useLiveResource("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/v1/leases"); + const tokens = useLiveResource("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/v1/tokens"); + const couldNot = [ + ...(asked.kind === "refused" ? ["waiting requests"] : []), + ...(leases.data === undefined && leases.error !== undefined ? ["leases"] : []), + ]; const waiting: LoadView = asked.kind === "unsupported" || failed ? { data: { requests: [] }, kind: "ready" } : asked; const events = loadView(useRecentEvents()); @@ -34,10 +41,12 @@ export function useOverview(range: ConsoleRange): LoadView { return mapView(reads, ([[workerList, waitingList], recent]) => overviewOf({ events: recent, - couldNotCheck: failed ? ["waiting requests"] : [], + couldNotCheck: couldNot, figures, + leases: leases.data?.leases, now: now.server, requests: waitingList.requests, + tokens: tokens.data?.tokens, workers: workerList.workers, }), ); From a7ba01beba0f63d52a1c8a00f152812045b88153 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:17:39 +0200 Subject: [PATCH 19/57] test: capacity counts every read device per platform: a drained worker's ready device counts as drained, a disconnected worker's devices as offline, a shutdown device as shut down, a deleted one not at all (#768) --- ui/src/model/overview.test.ts | 52 +++++++++++++++++++++++ ui/src/model/overview.ts | 13 ++++++ ui/src/screens/overview/overview.test.tsx | 1 + 3 files changed, 66 insertions(+) diff --git a/ui/src/model/overview.test.ts b/ui/src/model/overview.test.ts index e9a3b471a..ea4ab496f 100644 --- a/ui/src/model/overview.test.ts +++ b/ui/src/model/overview.test.ts @@ -273,4 +273,56 @@ describe("the overview", () => { ["mini-3", undefined, "Not reported"], ]); }); + + it("counts every read device per platform by part: a drained worker's ready device is drained, a disconnected worker's devices are offline, a shutdown device is shut down, a deleted one is not counted, and a worker not read yet adds nothing", () => { + const workers = [ + worker("w1", [ + device("a", "leased", "ios"), + device("b", "ready", "ios"), + device("c", "provisioning", "ios"), + device("d", "reclaiming", "ios"), + device("e", "shutdown", "ios"), + device("f", "deleted", "ios"), + device("g", "absent", "ios"), + device("h", "quarantined", "android"), + ]), + worker("w2", [device("i", "ready", "ios"), device("j", "leased", "ios")], { drained: true }), + worker("w3", [device("k", "ready", "ios"), device("l", "leased", "android")], { + connection: "disconnected", + }), + unread("w4"), + ]; + + const { capacity } = overviewOf({ events: [], now: NOW, requests: [], workers }); + + expect( + capacity.map((platform) => [ + platform.name, + platform.notRead, + platform.parts.map((part) => [part.count, part.word]), + ]), + ).toEqual([ + [ + "iOS", + 1, + [ + [2, "leased"], + [1, "ready"], + [2, "booting"], + [1, "drained"], + [1, "absent"], + [1, "shut down"], + [1, "offline"], + ], + ], + [ + "Android", + 1, + [ + [1, "quarantined"], + [1, "offline"], + ], + ], + ]); + }); }); diff --git a/ui/src/model/overview.ts b/ui/src/model/overview.ts index 8297593ba..2e1103740 100644 --- a/ui/src/model/overview.ts +++ b/ui/src/model/overview.ts @@ -79,7 +79,19 @@ export interface OverviewInbox { readonly needsYou: readonly OverviewItem[]; } +export interface CapacityPart { + readonly count: number; + readonly word: string; +} + +export interface PlatformCapacity { + readonly name: string; + readonly parts: readonly CapacityPart[]; + readonly notRead: number; +} + export interface Overview { + readonly capacity: readonly PlatformCapacity[]; readonly tiles: readonly OverviewTile[]; readonly wait?: OverviewTile; readonly ending: OverviewTile; @@ -254,6 +266,7 @@ export function overviewOf(input: { ...(tone === undefined ? {} : { tone }), }; }), + capacity: [], ending: endingSoon(leases, now), inbox: inboxOf({ context: { leases, now, requests, tokens }, diff --git a/ui/src/screens/overview/overview.test.tsx b/ui/src/screens/overview/overview.test.tsx index 194eceb68..d4d592e61 100644 --- a/ui/src/screens/overview/overview.test.tsx +++ b/ui/src/screens/overview/overview.test.tsx @@ -17,6 +17,7 @@ function text(html: string): string { const quiet: Overview = { activity: [], figures: { kind: "loading" }, + capacity: [], ending: { label: "Ending soon", value: "0" }, inbox: { couldNotCheck: [], needsYou: [], problems: 0 }, platforms: [], From 40464442e5af1951ec9f63697a690ef47ba03d57 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:18:36 +0200 Subject: [PATCH 20/57] feat(console): Capacity counts every read device per platform by part (#768) --- ui/src/ds/slots.css | 20 +++++ ui/src/ds/slots.tsx | 4 +- ui/src/model/overview.test.ts | 22 +----- ui/src/model/overview.ts | 95 +++++++++++++++-------- ui/src/screens/overview/index.tsx | 48 ++++++------ ui/src/screens/overview/overview.css | 22 ++++++ ui/src/screens/overview/overview.test.tsx | 23 +++--- ui/src/state/overview.ts | 2 +- 8 files changed, 144 insertions(+), 92 deletions(-) diff --git a/ui/src/ds/slots.css b/ui/src/ds/slots.css index 591a99617..877e7f54e 100644 --- a/ui/src/ds/slots.css +++ b/ui/src/ds/slots.css @@ -51,6 +51,26 @@ background: var(--status-warn); } +.slot-drained { + background: repeating-linear-gradient( + 135deg, + var(--status-ok) 0 3px, + var(--field) 3px 6px + ); +} + +.slot-shutdown { + background: var(--border-strong); +} + +.slot-offline { + background: repeating-linear-gradient( + 135deg, + var(--border-strong) 0 3px, + var(--field) 3px 6px + ); +} + .slot-free { border: 1px dashed var(--border-strong); } diff --git a/ui/src/ds/slots.tsx b/ui/src/ds/slots.tsx index 7fab38af9..70bd385ae 100644 --- a/ui/src/ds/slots.tsx +++ b/ui/src/ds/slots.tsx @@ -47,8 +47,10 @@ export function SlotLegend() { ); } +export type ShareKind = SlotKind | "drained" | "shutdown" | "offline"; + export interface Share { - readonly kind: SlotKind; + readonly kind: ShareKind; readonly percent: number; } diff --git a/ui/src/model/overview.test.ts b/ui/src/model/overview.test.ts index ea4ab496f..afeee71eb 100644 --- a/ui/src/model/overview.test.ts +++ b/ui/src/model/overview.test.ts @@ -123,22 +123,6 @@ describe("the overview", () => { expect(waits).toEqual([undefined, undefined]); }); - it("splits each platform's limit into leased, ready and booting, counting connected workers only", () => { - const { platforms } = overviewOf({ events: [], now: NOW, requests: [], workers: fleet }); - - expect(platforms).toEqual([ - { - busyPercent: 0, - leasedPercent: 12.5, - limit: 8, - name: "iOS", - readyPercent: 12.5, - running: 2, - }, - { busyPercent: 0, leasedPercent: 25, limit: 4, name: "Android", readyPercent: 0, running: 1 }, - ]); - }); - it("lists what needs you in the Inbox's order, each linked to its own page and toned by how bad it is", () => { const { inbox } = overviewOf({ events: [], now: NOW, requests: [], workers: fleet }); @@ -244,9 +228,9 @@ describe("the overview", () => { ["Workers", "1"], ]); - expect(alone.platforms.map((p) => [p.name, p.running, p.limit])).toEqual([ - ["iOS", undefined, undefined], - ["Android", undefined, undefined], + expect(alone.capacity.map((p) => [p.name, p.notRead, p.parts.length])).toEqual([ + ["iOS", 1, 0], + ["Android", 1, 0], ]); const row = alone.workers[0]; diff --git a/ui/src/model/overview.ts b/ui/src/model/overview.ts index 2e1103740..e53a0f6ba 100644 --- a/ui/src/model/overview.ts +++ b/ui/src/model/overview.ts @@ -19,7 +19,14 @@ import { itemPath } from "./paths"; import { formatDuration } from "./time"; import type { Tone, Toned } from "./tones"; import type { WaitingRequest } from "./waiting"; -import { isUnread, leasesHeld, type WorkerView, workerName, workerPath } from "./workers"; +import { + isUnread, + leasesHeld, + type WorkerDevice, + type WorkerView, + workerName, + workerPath, +} from "./workers"; export interface OverviewTile { readonly label: string; @@ -28,15 +35,6 @@ export interface OverviewTile { readonly to?: string; } -export interface PlatformUse { - readonly name: string; - readonly running?: number; - readonly limit?: number; - readonly leasedPercent: number; - readonly readyPercent: number; - readonly busyPercent: number; -} - export interface Gauge { readonly percent: number; readonly text: string; @@ -81,6 +79,8 @@ export interface OverviewInbox { export interface CapacityPart { readonly count: number; + readonly kind: PartKind; + readonly percent: number; readonly word: string; } @@ -96,7 +96,6 @@ export interface Overview { readonly wait?: OverviewTile; readonly ending: OverviewTile; readonly figures: FiguresState; - readonly platforms: readonly PlatformUse[]; readonly workers: readonly OverviewWorker[]; readonly inbox: OverviewInbox; readonly activity: readonly OverviewActivity[]; @@ -109,28 +108,58 @@ function percentOf(part: number, whole: number): number { return whole === 0 ? 0 : (part / whole) * 100; } -function platformUse(workers: readonly WorkerView[], platform: "ios" | "android"): PlatformUse { - const live = workers.filter((worker) => worker.connection === "connected"); - const name = platform === "ios" ? "iOS" : "Android"; - if (workers.some(isUnread)) { - return { busyPercent: 0, leasedPercent: 0, name, readyPercent: 0 }; +const PARTS = [ + { kind: "leased", word: "leased" }, + { kind: "ready", word: "ready" }, + { kind: "busy", word: "booting" }, + { kind: "drained", word: "drained" }, + { kind: "broken", word: "quarantined" }, + { kind: "absent", word: "absent" }, + { kind: "shutdown", word: "shut down" }, + { kind: "offline", word: "offline" }, +] as const; + +export type PartKind = (typeof PARTS)[number]["kind"]; + +const PART_OF_STATE: Readonly> = { + absent: "absent", + leased: "leased", + provisioning: "busy", + quarantined: "broken", + ready: "ready", + reclaiming: "busy", + shutdown: "shutdown", +}; + +// why: where a device is decides before what it is doing: on a worker that is not connected its +// state is the last one heard, so it counts as offline; on a drained worker a ready device is +// not available to lease, so it counts as drained. +function partOf(worker: WorkerView, device: WorkerDevice): PartKind | undefined { + if (device.state === "deleted") return undefined; + if (worker.connection !== "connected") return "offline"; + if (device.state === "ready" && worker.drained) return "drained"; + return PART_OF_STATE[device.state]; +} + +function platformCapacity( + workers: readonly WorkerView[], + platform: "ios" | "android", +): PlatformCapacity { + const counts = new Map(); + for (const worker of workers) { + for (const device of worker.devices ?? []) { + const part = device.spec.platform === platform ? partOf(worker, device) : undefined; + if (part !== undefined) counts.set(part, (counts.get(part) ?? 0) + 1); + } } - const limit = live.reduce((sum, worker) => sum + (worker.capacity?.[platform].limit ?? 0), 0); - const devices = live.flatMap((worker) => - (worker.devices ?? []).filter((device) => device.spec.platform === platform), - ); - const count = (...states: readonly string[]) => - devices.filter((device) => states.includes(device.state)).length; - const leased = count("leased"); - const ready = count("ready"); - const busy = count("provisioning", "reclaiming"); + const total = [...counts.values()].reduce((sum, count) => sum + count, 0); return { - busyPercent: percentOf(busy, limit), - leasedPercent: percentOf(leased, limit), - limit, - name, - readyPercent: percentOf(ready, limit), - running: leased + ready + busy, + name: platform === "ios" ? "iOS" : "Android", + notRead: workers.filter(isUnread).length, + parts: PARTS.flatMap(({ kind, word }) => { + const count = counts.get(kind) ?? 0; + return count === 0 ? [] : [{ count, kind, percent: percentOf(count, total), word }]; + }), }; } @@ -250,7 +279,6 @@ export function overviewOf(input: { tokens, workers, } = input; - const platforms = [platformUse(workers, "ios"), platformUse(workers, "android")]; return { activity: [...events] .sort((a, b) => b.timestamp - a.timestamp || b.seq - a.seq) @@ -266,7 +294,7 @@ export function overviewOf(input: { ...(tone === undefined ? {} : { tone }), }; }), - capacity: [], + capacity: [platformCapacity(workers, "ios"), platformCapacity(workers, "android")], ending: endingSoon(leases, now), inbox: inboxOf({ context: { leases, now, requests, tokens }, @@ -274,7 +302,6 @@ export function overviewOf(input: { workers, }), figures, - platforms, tiles: tiles(workers, requests, now), ...(figures.kind === "ready" ? { wait: figures.data.wait } : {}), workers: workers.map(overviewWorker), diff --git a/ui/src/screens/overview/index.tsx b/ui/src/screens/overview/index.tsx index a1b1d0dc4..7461f8c61 100644 --- a/ui/src/screens/overview/index.tsx +++ b/ui/src/screens/overview/index.tsx @@ -13,7 +13,6 @@ import { Refusal, Row, ShareBar, - SlotLegend, Slots, StatRow, StatTile, @@ -28,7 +27,7 @@ import { type OverviewActivity, type OverviewInbox, type OverviewWorker, - type PlatformUse, + type PlatformCapacity, useOverview, } from "../../state/overview"; @@ -99,12 +98,11 @@ export function OverviewBody(props: { ) : ( )} - +
        - {overview.platforms.map((platform) => ( + {overview.capacity.map((platform) => ( ))} -
        @@ -134,31 +132,31 @@ export function OverviewBody(props: { ); } -function PlatformBar({ platform }: { readonly platform: PlatformUse }) { - const known = platform.running !== undefined && platform.limit !== undefined; +function PlatformBar({ platform }: { readonly platform: PlatformCapacity }) { + const words = platform.parts.map((part) => `${part.count} ${part.word}`).join(", "); + const notRead = + platform.notRead === 0 + ? null + : platform.notRead === 1 + ? "1 worker not read yet" + : `${platform.notRead} workers not read yet`; return (

        {platform.name} - - {!known ? ( - — - ) : ( - <> - {platform.running} of {platform.limit} running - - )} - + {notRead === null ? null : {notRead}}

        - {known ? ( - - ) : null} + + + +
          + {platform.parts.map((part) => ( +
        • +
        • + ))} +
        ); } diff --git a/ui/src/screens/overview/overview.css b/ui/src/screens/overview/overview.css index 9047de711..28595f8db 100644 --- a/ui/src/screens/overview/overview.css +++ b/ui/src/screens/overview/overview.css @@ -159,3 +159,25 @@ border-top: 1px solid var(--border); font-size: var(--text-sm); } + +.platform-parts { + display: flex; + flex-wrap: wrap; + gap: var(--space-1) var(--space-3); + margin: 0; + padding: 0; + list-style: none; + color: var(--text-muted); + font-size: var(--text-xs); +} + +.platform-parts li { + display: inline-flex; + align-items: center; + gap: var(--space-1); +} + +.platform-parts .slot { + width: 8px; + height: 8px; +} diff --git a/ui/src/screens/overview/overview.test.tsx b/ui/src/screens/overview/overview.test.tsx index d4d592e61..ec7438f01 100644 --- a/ui/src/screens/overview/overview.test.tsx +++ b/ui/src/screens/overview/overview.test.tsx @@ -20,7 +20,6 @@ const quiet: Overview = { capacity: [], ending: { label: "Ending soon", value: "0" }, inbox: { couldNotCheck: [], needsYou: [], problems: 0 }, - platforms: [], tiles: [], workers: [], }; @@ -39,15 +38,15 @@ describe("the overview screen", () => { { expect(html).toContain('href="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/fleet/w1"'); expect(text(html)).not.toContain("memory 88%"); expect(html).toContain('—'); - expect(html).toContain('—

        '); - expect(text(html)).toContain("2 of 4 running"); - expect(html.match(/class="share-bar"/g)).toHaveLength(1); + expect(text(html)).toContain("iOS 1 worker not read yet"); + expect(html).toContain('role="img" aria-label="Android: 2 leased, 2 offline"'); + expect(text(html)).toContain("2 leased 2 offline"); }); it("draws the range picker as a radio group of four with the chosen range checked, three chart panels and the Capacity panel", () => { @@ -107,7 +106,7 @@ describe("the overview screen", () => { "Leases held, last 6 hours", "Requests in the queue, last 6 hours", "Device slots in use, last 6 hours", - "Capacity", + "Capacity · all workers", ]), ); }); diff --git a/ui/src/state/overview.ts b/ui/src/state/overview.ts index d4cd23311..db01ce3ba 100644 --- a/ui/src/state/overview.ts +++ b/ui/src/state/overview.ts @@ -16,7 +16,7 @@ export type { OverviewItem, OverviewWorker, Gauge, - PlatformUse, + PlatformCapacity, } from "../model/overview"; export function useOverview(range: ConsoleRange): LoadView { From fd32ef3396dd75de328552b22e7e0201545539d2 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:23:28 +0200 Subject: [PATCH 21/57] test: Overview's workers table lists all workers with no pager, and Open Fleet goes to /fleet (#768) --- e2e/console/overview.spec.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/e2e/console/overview.spec.ts b/e2e/console/overview.spec.ts index 49e5fcdc0..bb3fea8ff 100644 --- a/e2e/console/overview.spec.ts +++ b/e2e/console/overview.spec.ts @@ -243,7 +243,7 @@ test.describe("the Overview's figures", () => { const links = [ { follow: () => tile(page, "Waiting").getByRole("link").click(), path: "/queue" }, { follow: () => tile(page, "Workers").getByRole("link").click(), path: "/fleet" }, - { follow: () => page.getByRole("link", { name: /^All \d+$/ }).click(), path: "/fleet" }, + { follow: () => page.getByRole("link", { name: "Open Fleet" }).click(), path: "/fleet" }, { follow: () => page.getByRole("link", { name: "All events" }).click(), path: "/activity" }, ]; await openOverview(page, host); @@ -469,3 +469,26 @@ test.describe("the Overview's five numbers", () => { } }); }); + +test.describe("the Overview's workers table", () => { + test("lists all workers with no pager, and Open Fleet goes to /fleet", async ({ page }) => { + const fleet = await startFleet([ + { driverScript: { ios: IOS }, label: "worker-a" }, + { driverScript: { ios: IOS }, label: "worker-b" }, + ]); + try { + await openOverview(page, fleet.gateway); + + const workersPanel = page.getByRole("region", { name: "Workers" }); + await expect(workersPanel.locator("tbody tr")).toHaveCount(2); + await expect(workersPanel.getByRole("link", { name: "worker-a" })).toBeVisible(); + await expect(workersPanel.getByRole("link", { name: "worker-b" })).toBeVisible(); + await expect(page.getByRole("navigation", { name: /pages$/ })).toHaveCount(0); + + await page.getByRole("link", { name: "Open Fleet" }).click(); + await expect(page).toHaveURL(/\/fleet$/); + } finally { + await disposeFleet(fleet); + } + }); +}); From 43bbd984df7c37bafa881d2752978f919f18d375 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:24:03 +0200 Subject: [PATCH 22/57] feat(console): the Overview's workers panel links to Open Fleet (#768) --- ui/src/screens/overview/index.tsx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/ui/src/screens/overview/index.tsx b/ui/src/screens/overview/index.tsx index 7461f8c61..91ec885d0 100644 --- a/ui/src/screens/overview/index.tsx +++ b/ui/src/screens/overview/index.tsx @@ -114,11 +114,7 @@ export function OverviewBody(props: { )} - All {overview.workers.length}} - > + Open Fleet}>
        From b31bfbc008d7786b0b0cb5c1d7712d54e75327a3 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:25:03 +0200 Subject: [PATCH 23/57] test: Overview's and Usage's range chips sit in the shared toolbar (#768) --- e2e/console/overview.spec.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/e2e/console/overview.spec.ts b/e2e/console/overview.spec.ts index bb3fea8ff..41328b260 100644 --- a/e2e/console/overview.spec.ts +++ b/e2e/console/overview.spec.ts @@ -492,3 +492,23 @@ test.describe("the Overview's workers table", () => { } }); }); + +test.describe("the range chips", () => { + test("sit in the shared toolbar on Overview and on Usage", async ({ page }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + for (const path of ["/", "/usage"]) { + await page.goto(new URL(path, host.url).toString()); + if (path === "/") await signIn(page, host.tokens.operator); + await expect(page.getByRole("heading", { level: 1 })).toBeVisible(); + const chips = page.locator("#main .toolbar .toolbar-start").getByRole("group", { + name: "Range", + }); + await expect(chips, path).toBeVisible(); + await expect(chips.getByRole("radio")).toHaveCount(4); + } + } finally { + await host.dispose(); + } + }); +}); From eb7b135b70581928f97303f61a371e410d902e7c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:25:48 +0200 Subject: [PATCH 24/57] feat(console): Overview's and Usage's range chips sit in the shared toolbar (#768) --- ui/src/ds/toolbar.css | 5 +++++ ui/src/screens/overview/index.tsx | 11 +++++++---- ui/src/screens/overview/overview.css | 12 ------------ ui/src/screens/usage/index.tsx | 11 +++++++---- ui/src/screens/usage/usage.css | 12 ------------ 5 files changed, 19 insertions(+), 32 deletions(-) diff --git a/ui/src/ds/toolbar.css b/ui/src/ds/toolbar.css index 44925dff8..1dcd29392 100644 --- a/ui/src/ds/toolbar.css +++ b/ui/src/ds/toolbar.css @@ -10,3 +10,8 @@ .toolbar-end { margin-left: auto; } + +.toolbar-end p { + margin: 0; + font-size: var(--text-sm); +} diff --git a/ui/src/screens/overview/index.tsx b/ui/src/screens/overview/index.tsx index 91ec885d0..00cf28624 100644 --- a/ui/src/screens/overview/index.tsx +++ b/ui/src/screens/overview/index.tsx @@ -18,6 +18,7 @@ import { StatTile, Status, StatusDot, + Toolbar, } from "../../ds"; import type { FigureChart, FiguresState } from "../../state/figures"; import { type ConsoleRange, RANGE_CHOICES, useRange } from "../../state/range"; @@ -70,10 +71,12 @@ export function OverviewBody(props: { const [leases, ...others] = ready?.data.charts ?? []; return ( <> -
        - - {ready?.data.note === undefined ? null :

        {ready.data.note}

        } -
        + + } + end={ready?.data.note === undefined ? null :

        {ready.data.note}

        } + /> {ready?.refusal === undefined ? null : } {overview.tiles.map((tile) => ( diff --git a/ui/src/screens/overview/overview.css b/ui/src/screens/overview/overview.css index 28595f8db..590b03e63 100644 --- a/ui/src/screens/overview/overview.css +++ b/ui/src/screens/overview/overview.css @@ -141,18 +141,6 @@ color: var(--status-warn); } -.overview-range { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--space-3); -} - -.overview-range p { - margin: 0; - font-size: var(--text-sm); -} - .overview-all { margin: 0; padding: var(--space-3) var(--space-4); diff --git a/ui/src/screens/usage/index.tsx b/ui/src/screens/usage/index.tsx index 7b14b04f6..6baeeafa5 100644 --- a/ui/src/screens/usage/index.tsx +++ b/ui/src/screens/usage/index.tsx @@ -10,6 +10,7 @@ import { Refusal, StatRow, StatTile, + Toolbar, } from "../../ds"; import { type ConsoleRange, RANGE_CHOICES } from "../../state/range"; import { @@ -116,10 +117,12 @@ export function UsageBody(props: { const ready = state.kind === "ready" ? state : undefined; return ( <> -
        - - {ready?.data.note === undefined ? null :

        {ready.data.note}

        } -
        + + } + end={ready?.data.note === undefined ? null :

        {ready.data.note}

        } + /> {state.kind === "loading" ?

        Loading…

        : null} {state.kind === "refused" ? : null} {ready === undefined ? null : ( diff --git a/ui/src/screens/usage/usage.css b/ui/src/screens/usage/usage.css index eb55afe2a..f814f2478 100644 --- a/ui/src/screens/usage/usage.css +++ b/ui/src/screens/usage/usage.css @@ -1,15 +1,3 @@ -.usage-range { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--space-3); -} - -.usage-range p { - margin: 0; - font-size: var(--text-sm); -} - .usage-panels { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 20rem), 1fr)); From 39febbbbe54f4c0f874ec4d7298d4f6495e53c0a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:29:08 +0200 Subject: [PATCH 25/57] test: the Leases held and Requests in the queue charts follow ?range=, and Usage shows the Device slots in use chart in the shared frame (#768) --- e2e/console/overview.spec.ts | 31 +++++++++++++------------------ e2e/console/usage.spec.ts | 17 +++++++---------- 2 files changed, 20 insertions(+), 28 deletions(-) diff --git a/e2e/console/overview.spec.ts b/e2e/console/overview.spec.ts index 41328b260..e71cc2035 100644 --- a/e2e/console/overview.spec.ts +++ b/e2e/console/overview.spec.ts @@ -25,6 +25,7 @@ const RANGES = [ ] as const; const CHARTS = ["leasesHeld", "queueDepth", "slotsUsed"] as const; +const OVERVIEW_CHARTS = ["leasesHeld", "queueDepth"] as const; interface Stats { readonly totals: { readonly granted: number; readonly wait: { readonly p95: number | null } }; @@ -110,7 +111,7 @@ async function tablesOf(page: Page): Promise { } function expectedTables(stats: Stats): readonly (readonly string[])[] { - return CHARTS.map((key) => + return OVERVIEW_CHARTS.map((key) => [...stats.series].reverse().map((point) => (point[key] === null ? "—" : String(point[key]))), ); } @@ -119,7 +120,7 @@ test.describe("the Overview's figures", () => { // why: a run is charted once its minute is over, which can take most of a minute. test.describe.configure({ timeout: 150_000 }); - test("picking each of 1 hour, 6 hours, 24 hours and 7 days writes its ?range=, and the two tiles and all three chart tables equal GET /v1/stats", async ({ + test("picking each of 1 hour, 6 hours, 24 hours and 7 days writes its ?range=, and the Wait p95 tile and the two chart tables equal GET /v1/stats", async ({ page, }) => { const host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); @@ -137,9 +138,6 @@ test.describe("the Overview's figures", () => { ).toBeVisible(); const stats = await statsOf(host, range.since); - await expect - .poll(() => tileText(page, "Granted")) - .toBe(`Granted | ${stats.totals.granted} | ${range.unit}`); await expect .poll(() => tileText(page, "Wait p95")) .toBe(`Wait p95 | ${waitText(stats.totals.wait.p95)} | ${range.unit}`); @@ -160,21 +158,20 @@ test.describe("the Overview's figures", () => { await scriptedRun(host); await openOverview(page, host, "/?range=6h"); await expect(page.getByRole("radio", { name: "6 hours" })).toBeChecked(); - await expect(tile(page, "Granted")).toBeVisible(); - const before = [await tileText(page, "Granted"), await tileText(page, "Wait p95")]; + await expect(tile(page, "Wait p95")).toBeVisible(); + const before = [await tileText(page, "Wait p95")]; await page.reload(); await expect(page.getByRole("heading", { level: 1, name: "Overview" })).toBeVisible(); await expect(page.getByRole("radio", { name: "6 hours" })).toBeChecked(); - await expect.poll(() => tileText(page, "Granted")).toBe(before[0]); - await expect.poll(() => tileText(page, "Wait p95")).toBe(before[1]); + await expect.poll(() => tileText(page, "Wait p95")).toBe(before[0]); } finally { await host.dispose(); } }); - test("a daemon stop and start, with the events behind the figures pruned, shows the same Wait p95, Granted and chart rows", async ({ + test("a daemon stop and start, with the events behind the figures pruned, shows the same Wait p95 and chart rows", async ({ page, }) => { const host = await startDaemon("worker", { @@ -184,14 +181,13 @@ test.describe("the Overview's figures", () => { try { await scriptedRun(host); await openOverview(page, host, "/?range=24h"); - await expect(tile(page, "Granted")).toBeVisible(); + await expect(tile(page, "Wait p95")).toBeVisible(); const before = { - granted: await tileText(page, "Granted"), rows: (await tablesOf(page)).map((rows) => rows.filter((row) => row !== "—")), wait: await tileText(page, "Wait p95"), }; - expect(before.rows).toHaveLength(3); + expect(before.rows).toHaveLength(2); expect(before.rows.every((rows) => rows.length > 0)).toBe(true); await host.stop(); @@ -204,7 +200,6 @@ test.describe("the Overview's figures", () => { events: { event: string }[]; }; expect(events.filter((entry) => entry.event === "lease.granted")).toEqual([]); - await expect.poll(() => tileText(page, "Granted")).toBe(before.granted); await expect.poll(() => tileText(page, "Wait p95")).toBe(before.wait); const after = (await tablesOf(page)).map((rows) => rows.filter((row) => row !== "—")); expect(after.map((rows, index) => rows.slice(-(before.rows[index]?.length ?? 0)))).toEqual( @@ -215,19 +210,19 @@ test.describe("the Overview's figures", () => { } }); - test("a lease granted while the Overview is open raises Granted within 2 seconds with no reload", async ({ + test("a lease granted while the Overview is open raises Leased within 2 seconds with no reload", async ({ page, }) => { const host = await startDaemon("worker", { driverScript: { ios: IOS } }); try { await openOverview(page, host); - await expect(tile(page, "Granted")).toBeVisible(); - await expect(tile(page, "Granted")).toContainText("0"); + await expect(tile(page, "Leased")).toBeVisible(); + await expect(tile(page, "Leased")).toContainText("0"); const granted = await host.cli([...LEASE, "--agent-id", "late", "--detach"]); expect(granted.code, granted.stderr).toBe(0); - await expect(tile(page, "Granted").locator(".stat-value")).toHaveText("1", { + await expect(tile(page, "Leased").locator(".stat-value")).toHaveText("1", { timeout: 2_000, }); } finally { diff --git a/e2e/console/usage.spec.ts b/e2e/console/usage.spec.ts index 97e5b1df9..a14e856cd 100644 --- a/e2e/console/usage.spec.ts +++ b/e2e/console/usage.spec.ts @@ -221,20 +221,17 @@ test.describe("the Usage page", () => { } }); - test("clicking the Overview's Granted tile on /?range=7d opens /usage?range=7d", async ({ - page, - }) => { + test("shows the Device slots in use chart in the shared frame", async ({ page }) => { const host = await startDaemon("worker", { driverScript: { ios: IOS } }); try { - await page.goto(new URL("/?range=7d", host.url).toString()); + await page.goto(new URL("/usage?range=6h", host.url).toString()); await signIn(page, host.tokens.operator); - await expect(page.getByRole("heading", { level: 1, name: "Overview" })).toBeVisible(); - - await page.getByRole("link", { name: /Granted/ }).click(); - await expect(page.getByRole("heading", { level: 1, name: "Usage" })).toBeVisible(); - expect(new URL(page.url()).pathname + new URL(page.url()).search).toBe("/usage?range=7d"); - await expect(page.getByRole("radio", { name: "7 days" })).toBeChecked(); + + await expect( + page.getByRole("heading", { name: "Device slots in use, last 6 hours", exact: true }), + ).toBeVisible(); + await expect(page.locator("#main details.chart-data")).toHaveCount(1); } finally { await host.dispose(); } From 6d29bed9e18ca5ef5253fed7cdb9b0d39349655c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:32:25 +0200 Subject: [PATCH 26/57] feat(console): the Overview draws two charts and Usage draws Device slots in use (#768) --- ui/src/ds/chart.tsx | 24 +++++++++++++++++++++++ ui/src/ds/index.ts | 2 +- ui/src/model/usage.ts | 12 +++++++++++- ui/src/screens/overview/index.tsx | 24 ++++++++--------------- ui/src/screens/overview/overview.test.tsx | 4 ++-- ui/src/screens/usage/index.tsx | 2 ++ ui/src/screens/usage/usage.test.tsx | 1 + 7 files changed, 49 insertions(+), 20 deletions(-) diff --git a/ui/src/ds/chart.tsx b/ui/src/ds/chart.tsx index a7de33cbc..3af2872bb 100644 --- a/ui/src/ds/chart.tsx +++ b/ui/src/ds/chart.tsx @@ -16,6 +16,8 @@ import { } from "recharts"; import type { NameType, ValueType } from "recharts/types/component/DefaultTooltipContent"; +import { Panel } from "./panel"; + export interface MinuteCount { readonly at: number; readonly label: string; @@ -136,3 +138,25 @@ export function MinuteTable(props: { ); } + +// why: the Overview and Usage draw a minute series the same way: the chart, its one-line summary +// for a reader who cannot see it, and the table of the same numbers. +export function ChartPanel(props: { + readonly chart: { + readonly title: string; + readonly unit: string; + readonly heading: string; + readonly summary: string; + readonly bucketMs: number; + readonly points: readonly MinuteCount[]; + }; +}) { + const { bucketMs, heading, points, summary, title, unit } = props.chart; + return ( + + +

        {summary}

        + +
        + ); +} diff --git a/ui/src/ds/index.ts b/ui/src/ds/index.ts index fcfdeb65e..7d00f0890 100644 --- a/ui/src/ds/index.ts +++ b/ui/src/ds/index.ts @@ -2,7 +2,7 @@ import "./foundation.css"; export { Button, ButtonLink } from "./button"; export { Drawer, DrawerTabs } from "./drawer"; -export { MinuteChart, MinuteTable } from "./chart"; +export { ChartPanel, MinuteChart, MinuteTable } from "./chart"; export { ChoiceChips, Tabs } from "./choice"; export { Feed } from "./feed"; export { Facts } from "./facts"; diff --git a/ui/src/model/usage.ts b/ui/src/model/usage.ts index 66c5c0ce5..93c507423 100644 --- a/ui/src/model/usage.ts +++ b/ui/src/model/usage.ts @@ -1,5 +1,12 @@ import type { UsageOutput } from "../../../src/contract/index"; -import { type FigureTile, formatWait, partialNote, waitTile } from "./figures"; +import { + type FigureChart, + type FigureTile, + figuresOf, + formatWait, + partialNote, + waitTile, +} from "./figures"; import { formatBytes } from "./load"; import { agentIdOf } from "./leases"; import { formatCount } from "./paging"; @@ -45,6 +52,7 @@ export interface UsageRequesterRow { export interface UsageView { readonly note?: string; + readonly slots?: FigureChart; readonly tiles: readonly FigureTile[]; readonly bySource: readonly UsageCount[]; readonly durations: readonly UsageDuration[]; @@ -123,6 +131,7 @@ export function usageOf(stats: UsageOutput, range: ConsoleRange, now: number): U const unit = rangeUnit(range); const { bySource } = totals; const note = partialNote(stats, now); + const slots = figuresOf(stats, range, now).charts.find((chart) => chart.key === "slotsUsed"); return { bySource: [ ["warm", bySource.warm] as const, @@ -170,6 +179,7 @@ export function usageOf(stats: UsageOutput, range: ConsoleRange, now: number): U { label: "Held p50", unit, value: duration(totals.held.p50) }, ], use: useLines(totals), + ...(slots === undefined ? {} : { slots }), workers: stats.workers.map((worker) => scopeRow(worker.id, worker.label ?? worker.id, worker)), ...(note === undefined ? {} : { note }), }; diff --git a/ui/src/screens/overview/index.tsx b/ui/src/screens/overview/index.tsx index 00cf28624..f3da1b3ac 100644 --- a/ui/src/screens/overview/index.tsx +++ b/ui/src/screens/overview/index.tsx @@ -1,13 +1,12 @@ import "./overview.css"; import { + ChartPanel, ChoiceChips, Empty, Link, Loaded, Meter, - MinuteChart, - MinuteTable, Page, Panel, Refusal, @@ -20,7 +19,7 @@ import { StatusDot, Toolbar, } from "../../ds"; -import type { FigureChart, FiguresState } from "../../state/figures"; +import type { FiguresState } from "../../state/figures"; import { type ConsoleRange, RANGE_CHOICES, useRange } from "../../state/range"; import { type Gauge, @@ -50,16 +49,6 @@ function FigureNote({ figures }: { readonly figures: FiguresState }) { return null; } -function FigureChartPanel({ chart }: { readonly chart: FigureChart }) { - return ( - - -

        {chart.summary}

        - -
        - ); -} - export function OverviewBody(props: { readonly overview: Overview; readonly range?: ConsoleRange; @@ -68,7 +57,10 @@ export function OverviewBody(props: { const { overview, range = "1h", onRange = () => undefined } = props; const { figures } = overview; const ready = figures.kind === "ready" ? figures : undefined; - const [leases, ...others] = ready?.data.charts ?? []; + // why: Device slots in use is drawn on Usage; the Overview keeps the two charts of load. + const [leases, ...others] = (ready?.data.charts ?? []).filter( + (chart) => chart.key !== "slotsUsed", + ); return ( <> ) : ( - + )}
        @@ -112,7 +104,7 @@ export function OverviewBody(props: { {others.length === 0 ? null : ( {others.map((chart) => ( - + ))} )} diff --git a/ui/src/screens/overview/overview.test.tsx b/ui/src/screens/overview/overview.test.tsx index ec7438f01..f0d6afa14 100644 --- a/ui/src/screens/overview/overview.test.tsx +++ b/ui/src/screens/overview/overview.test.tsx @@ -85,7 +85,7 @@ describe("the overview screen", () => { expect(text(html)).toContain("2 leased 2 offline"); }); - it("draws the range picker as a radio group of four with the chosen range checked, three chart panels and the Capacity panel", () => { + it("draws the range picker as a radio group of four with the chosen range checked, two chart panels and the Capacity panel", () => { const shown = renderToStaticMarkup( undefined} />, ); @@ -105,10 +105,10 @@ describe("the overview screen", () => { expect.arrayContaining([ "Leases held, last 6 hours", "Requests in the queue, last 6 hours", - "Device slots in use, last 6 hours", "Capacity · all workers", ]), ); + expect(headings).not.toContain("Device slots in use, last 6 hours"); }); it("shows the partial note above the tiles when the figures carry one, and no note otherwise", () => { diff --git a/ui/src/screens/usage/index.tsx b/ui/src/screens/usage/index.tsx index 6baeeafa5..574d19d79 100644 --- a/ui/src/screens/usage/index.tsx +++ b/ui/src/screens/usage/index.tsx @@ -1,6 +1,7 @@ import "./usage.css"; import { + ChartPanel, ChoiceChips, type Column, DataTable, @@ -147,6 +148,7 @@ function Figures(props: { ))} + {view.slots === undefined ? null : }
        { ([, id]) => new RegExp(`id="${id}"[^>]*>([^<]*)<`).exec(html)?.[1], ); expect(regions).toEqual([ + "Device slots in use, last 24 hours", "Grants by source", "Durations", "Rejections by reason", From 1874d14e639c351173098b7868a45ced7e0608a7 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:35:30 +0200 Subject: [PATCH 27/57] test: /inbox lists a drained worker under Needs a look and a disconnected one under Broken; the chips show one group at a time (#768) --- e2e/console/inbox.spec.ts | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/e2e/console/inbox.spec.ts b/e2e/console/inbox.spec.ts index 91974c694..b415ae623 100644 --- a/e2e/console/inbox.spec.ts +++ b/e2e/console/inbox.spec.ts @@ -163,6 +163,47 @@ async function hasHorizontalScroll(page: Page): Promise { } test.describe("the Inbox view", () => { + test("/inbox lists a drained worker under Needs a look and a disconnected one under Broken; the chips show one group at a time", async ({ + page, + }) => { + const fleet = await startFleet([ + { driverScript: { ios: IOS }, label: "worker-a" }, + { driverScript: { ios: IOS }, label: "worker-b" }, + ]); + try { + const a = (await workers(fleet.gateway)).find((view) => view.label === "worker-a"); + expect((await fleet.gateway.cli(["worker", "drain", a?.id ?? ""])).code).toBe(0); + await (fleet.workers[1] as RunningDaemon).stop(); + await untilTheDaemonSays( + fleet.gateway, + (views) => + views.find((view) => view.label === "worker-a")?.drained === true && + views.find((view) => view.label === "worker-b")?.connection === "disconnected", + ); + await openInbox(page, fleet.gateway); + + const broken = page.getByRole("region", { name: "Broken" }); + const needsALook = page.getByRole("region", { name: "Needs a look" }); + await expect(broken.getByRole("link", { name: /worker-b/ })).toBeVisible(); + await expect(needsALook.getByRole("link", { name: /worker-a/ })).toBeVisible(); + await expect(page.getByRole("region", { name: "Heads-up" })).toHaveCount(0); + + await page.getByRole("radio", { name: "Broken" }).check(); + await expect(broken).toBeVisible(); + await expect(needsALook).toHaveCount(0); + + await page.getByRole("radio", { name: "Needs a look" }).check(); + await expect(needsALook).toBeVisible(); + await expect(broken).toHaveCount(0); + + await page.getByRole("radio", { name: "All" }).check(); + await expect(broken).toBeVisible(); + await expect(needsALook).toBeVisible(); + } finally { + await disposeFleet(fleet); + } + }); + test("draining a worker adds it to the Inbox view within a second", async ({ page }) => { const fleet = await startFleet([ { driverScript: { ios: IOS }, label: "worker-a" }, From a9327baa8996199a416f16be956dc0048fea7087 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:36:57 +0200 Subject: [PATCH 28/57] feat(console): /inbox lists items in three groups, with chips that show one group at a time (#768) --- ui/src/model/inbox.ts | 20 +++- ui/src/screens/inbox/inbox.css | 38 +++++++ ui/src/screens/inbox/index.test.tsx | 33 ++---- ui/src/screens/inbox/index.tsx | 166 ++++++++-------------------- ui/src/state/inbox.ts | 101 ++++++++++++----- ui/src/state/overview.ts | 23 +--- 6 files changed, 192 insertions(+), 189 deletions(-) diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index d2419d9d6..6df331c5b 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -167,6 +167,20 @@ export function inboxTone(condition: InboxItem["condition"]): Tone { export type InboxGroup = "Broken" | "Needs a look" | "Heads-up"; +export type InboxFilter = "all" | InboxGroup; + +export const INBOX_FILTERS: readonly { readonly value: InboxFilter; readonly label: string }[] = [ + { label: "All", value: "all" }, + ...GROUPS.map((group) => ({ label: group, value: group })), +]; + +export function filterInboxRows( + rows: readonly InboxRow[], + filter: InboxFilter, +): readonly InboxRow[] { + return filter === "all" ? rows : rows.filter((row) => row.group === filter); +} + export interface InboxRow { readonly group: InboxGroup; readonly key: string; @@ -371,9 +385,9 @@ export function inboxPageOf(input: { readonly events: readonly ConsoleEvent[]; readonly now: number; readonly key: string | undefined; - readonly requests?: readonly WaitingRequest[]; - readonly leases?: readonly LeaseRecord[]; - readonly tokens?: readonly TokenRecord[]; + readonly requests?: readonly WaitingRequest[] | undefined; + readonly leases?: readonly LeaseRecord[] | undefined; + readonly tokens?: readonly TokenRecord[] | undefined; }): InboxPage { const items = inboxItems(input.workers, input); const rows = inGroupOrder(items).map((item) => ({ diff --git a/ui/src/screens/inbox/inbox.css b/ui/src/screens/inbox/inbox.css index c000da2bf..2a193bab2 100644 --- a/ui/src/screens/inbox/inbox.css +++ b/ui/src/screens/inbox/inbox.css @@ -74,3 +74,41 @@ min-width: 0; overflow-wrap: anywhere; } + +.inbox-list { + margin: 0; + padding: 0; + list-style: none; +} + +.inbox-row { + display: flex; + align-items: center; + gap: var(--space-3); + padding: var(--space-3) var(--space-4); + border-bottom: 1px solid var(--border); + color: var(--text); + font-size: var(--text-sm); + text-decoration: none; + transition: background-color var(--duration); +} + +.inbox-list li:last-child .inbox-row { + border-bottom: 0; +} + +.inbox-row:hover { + background: var(--field); + color: var(--text); +} + +.inbox-subject { + min-width: 0; + margin-left: auto; + overflow: hidden; + color: var(--text-muted); + font-family: var(--font-mono); + font-size: var(--text-xs); + text-overflow: ellipsis; + white-space: nowrap; +} diff --git a/ui/src/screens/inbox/index.test.tsx b/ui/src/screens/inbox/index.test.tsx index ba117bbc1..b05c545da 100644 --- a/ui/src/screens/inbox/index.test.tsx +++ b/ui/src/screens/inbox/index.test.tsx @@ -20,45 +20,26 @@ function worker(overrides: Partial = {}): WorkerView { }; } -function render(workers: readonly WorkerView[], key?: string): string { - const page = inboxPageOf({ events: [], key, now: NOW, workers }); - return renderToStaticMarkup(); +function render(workers: readonly WorkerView[]): string { + const page = inboxPageOf({ events: [], key: undefined, now: NOW, workers }); + return renderToStaticMarkup(); } describe("the Inbox screen", () => { it("says so when the Inbox is empty", () => { - const html = render([worker()]); - - expect(html).toContain("Nothing needs you."); - expect(html).toContain("0 open"); + expect(render([worker()])).toContain("Nothing needs you."); }); - it("counts the open items and links each row to its item, with its condition as its name", () => { + it("links each row to its item, with its condition as its name, under its group", () => { const html = render([ worker({ connection: "disconnected", id: "wrk_a", label: "mac-mini-1" }), worker({ drained: true, id: "wrk_b" }), ]); - expect(html).toContain("2 open"); + expect(html).toContain("Broken"); + expect(html).toContain("Needs a look"); expect(html).toContain('aria-label="disconnected"'); expect(html).toContain('href="/inbox/wrk_a%2Fdisconnected"'); expect(html).toContain('href="/inbox/wrk_b%2Fdrained"'); }); - - it("shows the first item in the inspector with its worker linked and an Open worker button", () => { - const html = render([worker({ drained: true, id: "wrk/1", label: "mac-mini-1" })]); - - expect(html).toContain("Leases still held"); - expect(html).toContain('href="/fleet/wrk%2F1"'); - expect(html).toContain("Open worker"); - expect(html).toContain("Recent events"); - expect(html).toContain("No events in the last hour."); - }); - - it("says Resolved. with a link back when the URL names an item that is no longer in the Inbox", () => { - const html = render([worker()], "wrk_1/drained"); - - expect(html).toContain("Resolved."); - expect(html).toContain('Back to Inbox'); - }); }); diff --git a/ui/src/screens/inbox/index.tsx b/ui/src/screens/inbox/index.tsx index a784d0e59..2ccd6a375 100644 --- a/ui/src/screens/inbox/index.tsx +++ b/ui/src/screens/inbox/index.tsx @@ -1,130 +1,62 @@ import "./inbox.css"; -import { - ButtonLink, - Card, - Empty, - Grid, - Inspector, - InspectorEmpty, - Link, - List, - ListPane, - ListRow, - Loaded, - MasterDetail, - Pager, - Panel, - Status, - StatusDot, -} from "../../ds"; -import { - type InboxDetail, - type InboxEvent, - type InboxPage, - useAttention, - useInboxRows, -} from "../../state/inbox"; +import { ChoiceChips, Empty, Link, Loaded, Page, Panel, StatusDot, Toolbar } from "../../ds"; +import { INBOX_FILTERS, type InboxFilter, type InboxRow, useInbox } from "../../state/inbox"; -export function InboxScreen() { - const view = useAttention(); - return {(page) => }; -} - -export function InboxBody({ page }: { readonly page: InboxPage }) { - const { paging, shown } = useInboxRows(page.rows); - const chosen = typeof page.shown === "object" ? page.shown.key : undefined; - return ( - } - > - {page.rows.length === 0 ? ( - Nothing needs you. - ) : ( - - {shown.map((row) => ( - } - title={row.word} - sub={row.subject} - /> - ))} - - )} - - } - detail={} - /> - ); -} - -function Detail({ shown }: { readonly shown: InboxPage["shown"] }) { - if (shown === undefined) return Nothing to show.; - if (shown === "resolved") { - return ( - - Resolved. Back to Inbox - - ); - } - return ; -} +const GROUP_ORDER = ["Broken", "Needs a look", "Heads-up"] as const; -function Item({ detail }: { readonly detail: InboxDetail }) { +export function InboxScreen() { + const { choose, filter, rows, view } = useInbox(); return ( - - {detail.word} ·{" "} - - {detail.worker.name} - - + {view.data.problems} open : null } - actions={Open worker} > - {detail.facts.length === 0 ? null : ( - - {detail.facts.map((fact) => ( - -

        {fact.label}

        -

        {fact.value}

        -
        - ))} -
        - )} - - - -
        + + } + /> + {(page) => } + ); } -function EventList({ events }: { readonly events: readonly InboxEvent[] }) { - if (events.length === 0) return No events in the last hour.; +export function InboxBody(props: { + readonly rows: readonly InboxRow[]; + readonly filter: InboxFilter; +}) { + const { filter, rows } = props; + if (rows.length === 0) { + return {filter === "all" ? "Nothing needs you." : "Nothing in this group."}; + } return ( -
          - {events.map((event) => ( -
        • - - {event.time} - - {event.name} - - {event.text} - -
        • - ))} -
        + <> + {GROUP_ORDER.map((group) => { + const inGroup = rows.filter((row) => row.group === group); + return inGroup.length === 0 ? null : ( + +
          + {inGroup.map((row) => ( +
        • + + + {row.word} + {row.subject} + +
        • + ))} +
        +
        + ); + })} + ); } diff --git a/ui/src/state/inbox.ts b/ui/src/state/inbox.ts index 59c6ef13a..ee1395eb8 100644 --- a/ui/src/state/inbox.ts +++ b/ui/src/state/inbox.ts @@ -1,42 +1,93 @@ +import { useState } from "react"; + import type { LoadView } from "../ds/loaded"; -import type { Paging } from "../ds/pager"; -import { type InboxPage, inboxPageOf, type InboxRow } from "../model/inbox"; -import { listSearch, TABLE_SIZES } from "../model/paging"; +import { + filterInboxRows, + type InboxFilter, + type InboxPage, + inboxPageOf, + type InboxRow, +} from "../model/inbox"; +import type { LeaseList, TokenList } from "../model/leases"; import { itemIdFrom } from "../model/paths"; +import type { WaitingList } from "../model/waiting"; import type { WorkerList } from "../model/workers"; +import { type ListDrawerState, useListDrawer } from "./drawer"; import { useRecentEvents } from "./events"; import { useLiveResource, useNow } from "./live"; -import { usePaging } from "./paging"; import { bothViews, loadView, mapView } from "./resource"; -import { usePath, useSearch } from "./router"; +import { usePath } from "./router"; export type { InboxDetail, InboxEvent, InboxPage, InboxRow } from "../model/inbox"; -export type { Paging } from "../ds/pager"; +export { INBOX_FILTERS, type InboxFilter } from "../model/inbox"; + +export interface InboxReads { + readonly waiting: LoadView; + readonly leases: LeaseList["leases"] | undefined; + readonly tokens: TokenList["tokens"] | undefined; + readonly couldNotCheck: readonly string[]; +} + +// why: a daemon that keeps no queue of its own answers 501; the Inbox then counts no waiting +// requests instead of hiding the fleet behind "not available". A read that failed is not that: +// the rest still shows, and the page says what could not be checked. +export function useInboxReads(): InboxReads { + const asked = loadView(useLiveResource("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/v1/lease-requests")); + const leases = useLiveResource("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/v1/leases"); + const tokens = useLiveResource("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/v1/tokens"); + const failed = asked.kind === "refused"; + return { + couldNotCheck: [ + ...(failed ? ["waiting requests"] : []), + ...(leases.data === undefined && leases.error !== undefined ? ["leases"] : []), + ], + leases: leases.data?.leases, + tokens: tokens.data?.tokens, + waiting: + asked.kind === "unsupported" || failed ? { data: { requests: [] }, kind: "ready" } : asked, + }; +} -export function useAttention(): LoadView { +export interface Inbox { + readonly view: LoadView; + readonly filter: InboxFilter; + readonly choose: (filter: InboxFilter) => void; + readonly rows: (page: InboxPage) => readonly InboxRow[]; + // why: the key in the URL stands even before the list has loaded, so the drawer can ask for it. + readonly urlId: string | undefined; +} + +export function useInbox(): Inbox { const workers = loadView(useLiveResource("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/v1/workers")); - // why: the events only fill the inspector's list, so a feed still loading shows the page with + const reads = useInboxReads(); + // why: the events only fill the drawer's list, so a feed still loading shows the page with // none rather than holding back the list. const feed = useRecentEvents(); const now = useNow(); - const key = itemIdFrom("/inbox", usePath()); - const reads = bothViews(workers, { data: feed.data ?? [], kind: "ready" }); - return mapView(reads, ([list, events]) => - inboxPageOf({ events, key, now: now.server, workers: list.workers }), + const urlId = itemIdFrom("/inbox", usePath()); + const [filter, choose] = useState("all"); + const view = mapView( + bothViews(bothViews(workers, reads.waiting), { data: feed.data ?? [], kind: "ready" }), + ([[list, waiting], events]) => + inboxPageOf({ + events, + key: urlId, + leases: reads.leases, + now: now.server, + requests: waiting.requests, + tokens: reads.tokens, + workers: list.workers, + }), ); -} - -// why: the pager is read once the list is known, so a page in the URL is never corrected against -// a list that has not arrived. -export function useInboxRows(rows: readonly InboxRow[]): { - readonly shown: readonly InboxRow[]; - readonly paging: Paging; -} { - const paging = usePaging({ sizes: TABLE_SIZES, total: rows.length }); - const keep = listSearch(useSearch()); - const start = (paging.page - 1) * paging.size; return { - paging, - shown: rows.slice(start, start + paging.size).map((row) => ({ ...row, to: row.to + keep })), + choose, + filter, + rows: (page) => filterInboxRows(page.rows, filter), + urlId, + view, }; } + +export function useInboxDrawer(urlId: string | undefined): ListDrawerState { + return useListDrawer("/inbox", urlId); +} diff --git a/ui/src/state/overview.ts b/ui/src/state/overview.ts index db01ce3ba..1a04cdf39 100644 --- a/ui/src/state/overview.ts +++ b/ui/src/state/overview.ts @@ -1,12 +1,11 @@ import type { LoadView } from "../ds/loaded"; import { overviewOf, type Overview } from "../model/overview"; -import type { LeaseList, TokenList } from "../model/leases"; import type { ConsoleRange } from "../model/range"; -import type { WaitingList } from "../model/waiting"; import type { WorkerList } from "../model/workers"; import { useRecentEvents } from "./events"; import { useFigures } from "./figures"; import { useLiveResource, useNow } from "./live"; +import { useInboxReads } from "./inbox"; import { bothViews, loadView, mapView } from "./resource"; export type { @@ -21,19 +20,7 @@ export type { export function useOverview(range: ConsoleRange): LoadView { const workers = loadView(useLiveResource("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/v1/workers")); - const asked = loadView(useLiveResource("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/v1/lease-requests")); - // why: a daemon that keeps no queue of its own answers 501; the overview then counts no waiting - // requests instead of hiding the whole fleet behind "not available". A read that failed is not - // that: the fleet still shows, and the Inbox line says what could not be checked. - const failed = asked.kind === "refused"; - const leases = useLiveResource("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/v1/leases"); - const tokens = useLiveResource("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/v1/tokens"); - const couldNot = [ - ...(asked.kind === "refused" ? ["waiting requests"] : []), - ...(leases.data === undefined && leases.error !== undefined ? ["leases"] : []), - ]; - const waiting: LoadView = - asked.kind === "unsupported" || failed ? { data: { requests: [] }, kind: "ready" } : asked; + const { couldNotCheck, leases, tokens, waiting } = useInboxReads(); const events = loadView(useRecentEvents()); const figures = useFigures(range); const now = useNow(); @@ -41,12 +28,12 @@ export function useOverview(range: ConsoleRange): LoadView { return mapView(reads, ([[workerList, waitingList], recent]) => overviewOf({ events: recent, - couldNotCheck: couldNot, + couldNotCheck, figures, - leases: leases.data?.leases, + leases, now: now.server, requests: waitingList.requests, - tokens: tokens.data?.tokens, + tokens, workers: workerList.workers, }), ); From 072bfd28920b6f03653ea85afd8e710c67f96b6b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:38:37 +0200 Subject: [PATCH 29/57] test: a waiting request stubbed with a createdAt 61 s before the daemon's now shows under Needs a look, and one at 30 s does not (#768) --- e2e/console/inbox.spec.ts | 41 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/e2e/console/inbox.spec.ts b/e2e/console/inbox.spec.ts index b415ae623..2c9497c63 100644 --- a/e2e/console/inbox.spec.ts +++ b/e2e/console/inbox.spec.ts @@ -1,4 +1,4 @@ -import type { Locator, Page } from "@playwright/test"; +import type { Locator, Page, Route } from "@playwright/test"; import { waitFor } from "../helpers/wait.js"; import { @@ -204,6 +204,45 @@ test.describe("the Inbox view", () => { } }); + test("a waiting request stubbed with a createdAt 61 s before the daemon's now shows under Needs a look, and one at 30 s does not", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + // why: a request cannot wait a minute on a real daemon quickly, so the list is stubbed, each + // age counted from the daemon's own clock (its Date header). + await page.route( + (url) => url.pathname === "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/v1/lease-requests", + async (route: Route) => { + const response = await route.fetch(); + const now = new Date(response.headers().date ?? "").getTime(); + const request = (id: string, waitedMs: number) => ({ + createdAt: now - waitedMs, + id, + platform: "ios", + queuePosition: 1, + requesterId: id, + stage: "queued", + }); + await route.fulfill({ + json: { requests: [request("long-waiter", 61_000), request("short-waiter", 30_000)] }, + response, + }); + }, + ); + + await openInbox(page, host); + + const needsALook = page.getByRole("region", { name: "Needs a look" }); + await expect( + needsALook.getByRole("link", { name: /long-waiter has waited 1 min/ }), + ).toBeVisible(); + await expect(page.getByRole("link", { name: /short-waiter/ })).toHaveCount(0); + } finally { + await host.dispose(); + } + }); + test("draining a worker adds it to the Inbox view within a second", async ({ page }) => { const fleet = await startFleet([ { driverScript: { ios: IOS }, label: "worker-a" }, From 79f6515e61fca4e64d36cacedc70aff02e80354d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:39:14 +0200 Subject: [PATCH 30/57] test: a lease stubbed with 4 minutes left shows under Heads-up, and one with 10 minutes does not (#768) --- e2e/console/inbox.spec.ts | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/e2e/console/inbox.spec.ts b/e2e/console/inbox.spec.ts index 2c9497c63..3d50221bf 100644 --- a/e2e/console/inbox.spec.ts +++ b/e2e/console/inbox.spec.ts @@ -243,6 +243,48 @@ test.describe("the Inbox view", () => { } }); + test("a lease stubbed with 4 minutes left shows under Heads-up, and one with 10 minutes does not", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + // why: a lease cannot be 4 minutes from its deadline on a real daemon quickly, so the list is + // stubbed, each deadline counted from the daemon's own clock (its Date header). + await page.route( + (url) => url.pathname === "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/v1/leases", + async (route: Route) => { + const response = await route.fetch(); + const now = new Date(response.headers().date ?? "").getTime(); + const lease = (id: string, leftMs: number) => ({ + deviceId: "dev_stub", + grantedAt: now - 60_000, + id, + idChosenByRequester: false, + lastRenewedAt: now - 30_000, + ownerId: "tok_stub", + requesterId: "tok_stub", + ttlDeadline: now + leftMs, + ttlMs: 900_000, + }); + await route.fulfill({ + json: { leases: [lease("lease-soon", 4 * 60_000), lease("lease-later", 10 * 60_000)] }, + response, + }); + }, + ); + + await openInbox(page, host); + + const headsUp = page.getByRole("region", { name: "Heads-up" }); + await expect(headsUp.getByRole("link")).toHaveCount(1); + await expect( + headsUp.getByRole("link", { name: /tok_stub · dev_stub ends in 3:\d\d/ }), + ).toBeVisible(); + } finally { + await host.dispose(); + } + }); + test("draining a worker adds it to the Inbox view within a second", async ({ page }) => { const fleet = await startFleet([ { driverScript: { ios: IOS }, label: "worker-a" }, From 6e82e2d175ad73d963847ea82e93f708218ca6cd Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:39:53 +0200 Subject: [PATCH 31/57] test: an Inbox item whose key holds a . reloads at its address (#768) --- e2e/console/inbox.spec.ts | 43 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/e2e/console/inbox.spec.ts b/e2e/console/inbox.spec.ts index 3d50221bf..037f54bf9 100644 --- a/e2e/console/inbox.spec.ts +++ b/e2e/console/inbox.spec.ts @@ -285,6 +285,49 @@ test.describe("the Inbox view", () => { } }); + test("an Inbox item whose key holds a . reloads at its address", async ({ page }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + // why: a gateway's lease id holds a `.`, which a single host never makes, so the list is stubbed. + await page.route( + (url) => url.pathname === "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/v1/leases", + async (route: Route) => { + const response = await route.fetch(); + const now = new Date(response.headers().date ?? "").getTime(); + await route.fulfill({ + json: { + leases: [ + { + deviceId: "dev_stub", + grantedAt: now - 60_000, + id: "wrk_a.lse_1", + idChosenByRequester: false, + lastRenewedAt: now - 30_000, + ownerId: "tok_stub", + requesterId: "tok_stub", + ttlDeadline: now + 4 * 60_000, + ttlMs: 900_000, + }, + ], + }, + response, + }); + }, + ); + await openInbox(page, host); + + await page.getByRole("region", { name: "Heads-up" }).getByRole("link").click(); + const address = new URL(page.url()).pathname; + expect(address).toBe(`/inbox/${encodeURIComponent("lease/wrk_a.lse_1/ending")}/`); + await page.reload(); + + await expect(page.getByRole("heading", { level: 1, name: "Inbox" })).toBeVisible(); + expect(new URL(page.url()).pathname).toBe(address); + } finally { + await host.dispose(); + } + }); + test("draining a worker adds it to the Inbox view within a second", async ({ page }) => { const fleet = await startFleet([ { driverScript: { ios: IOS }, label: "worker-a" }, From 50b181edcdb3f5991469589f469e08f5fe55b646 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:40:05 +0200 Subject: [PATCH 32/57] feat(console): an Inbox address ends in / when its key holds a . (#768) --- ui/src/model/event-list.ts | 4 ++-- ui/src/model/inbox.ts | 4 ++-- ui/src/model/overview.ts | 4 ++-- ui/src/model/paths.ts | 7 +++++++ 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/ui/src/model/event-list.ts b/ui/src/model/event-list.ts index 75dd98122..69ad33b8c 100644 --- a/ui/src/model/event-list.ts +++ b/ui/src/model/event-list.ts @@ -12,7 +12,7 @@ import { import { eventsPerMinute, extremes, type MinuteCount } from "./history"; import { type LeaseRecord, leasePath } from "./leases"; import { formatCount, writeQuery } from "./paging"; -import { itemPath } from "./paths"; +import { inboxPath, itemPath } from "./paths"; import type { Tone } from "./tones"; import type { WaitingRequest } from "./waiting"; import { type WorkerView, workerPath } from "./workers"; @@ -157,7 +157,7 @@ export function eventAction(event: ConsoleEvent, places: EventPlaces): EventActi (entry) => "device" in entry && entry.worker.id === workerId && entry.device.id === deviceId, ); if (item !== undefined) { - return { label: "Open Inbox item", to: itemPath("/inbox", item.key) }; + return { label: "Open Inbox item", to: inboxPath(item.key) }; } const worker = places.workers.find((entry) => entry.id === workerId); if (worker !== undefined) return { label: "Open worker", to: workerPath(worker.id) }; diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index 6df331c5b..db7cff9ed 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -1,6 +1,6 @@ import { eventSummary, eventTone } from "./activity"; import { type ConsoleEvent, timeOfDay, workerIdOf } from "./events"; -import { itemPath } from "./paths"; +import { inboxPath, itemPath } from "./paths"; import { deviceOfLease, holderName, @@ -394,7 +394,7 @@ export function inboxPageOf(input: { group: inboxGroup(item), key: item.key, subject: inboxSubject(item), - to: itemPath("/inbox", item.key), + to: inboxPath(item.key), tone: inboxTone(item.condition), word: item.condition, })); diff --git a/ui/src/model/overview.ts b/ui/src/model/overview.ts index e53a0f6ba..d6b485e6a 100644 --- a/ui/src/model/overview.ts +++ b/ui/src/model/overview.ts @@ -15,7 +15,7 @@ import { minuteLabel } from "./history"; import { formatBusyPercent, loadGauges } from "./load"; import { levelOf } from "./load-thresholds"; import { formatCount } from "./paging"; -import { itemPath } from "./paths"; +import { inboxPath, itemPath } from "./paths"; import { formatDuration } from "./time"; import type { Tone, Toned } from "./tones"; import type { WaitingRequest } from "./waiting"; @@ -248,7 +248,7 @@ function inboxOf(input: { needsYou: problems.slice(0, NEEDS_YOU_ROWS).map((item) => ({ key: item.key, subject: inboxSubject(item), - to: itemPath("/inbox", item.key), + to: inboxPath(item.key), tone: inboxTone(item.condition), word: item.condition, })), diff --git a/ui/src/model/paths.ts b/ui/src/model/paths.ts index 65d800775..5b47a4892 100644 --- a/ui/src/model/paths.ts +++ b/ui/src/model/paths.ts @@ -4,6 +4,13 @@ export function itemPath(section: Section, id: string): `/${string}` { return `${section}/${encodeURIComponent(id)}`; } +// why: an Inbox key may hold a `.` (a gateway lease id does), and the daemon serves the console's page +// only for a path whose last segment has none, so such an address ends in `/`. +export function inboxPath(key: string): `/${string}` { + const path = itemPath("/inbox", key); + return key.includes(".") ? `${path}/` : path; +} + // why: ids are opaque and may hold a slash (an Inbox item's key does), so the whole rest of the // path is one id; a malformed escape is kept as typed rather than thrown. export function itemIdFrom(section: Section, path: string): string | undefined { From b99cbded9b16946dd9bf3148fd2e526f2a7787f7 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:44:17 +0200 Subject: [PATCH 33/57] test: an Inbox row opens /inbox/ with the what-happened box and the item's details; a cleared item says This is no longer in the Inbox. (#768) --- e2e/console/inbox.spec.ts | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/e2e/console/inbox.spec.ts b/e2e/console/inbox.spec.ts index 037f54bf9..fd2b5b0f6 100644 --- a/e2e/console/inbox.spec.ts +++ b/e2e/console/inbox.spec.ts @@ -142,7 +142,7 @@ async function openInbox(page: Page, daemon: RunningDaemon): Promise { } function rows(page: Page): Locator { - return page.getByRole("list", { name: "Needs you" }).getByRole("link"); + return page.locator("main").getByRole("list").getByRole("link"); } function item(page: Page, condition: string, subject: string): Locator { @@ -328,6 +328,39 @@ test.describe("the Inbox view", () => { } }); + test("an Inbox row opens /inbox/ with the what-happened box and the item's details; a cleared item says This is no longer in the Inbox.", async ({ + page, + }) => { + const fleet = await startFleet([{ driverScript: { ios: IOS }, label: "worker-a" }]); + try { + const [a] = await workers(fleet.gateway); + expect((await fleet.gateway.cli(["worker", "drain", a?.id ?? ""])).code).toBe(0); + await openInbox(page, fleet.gateway); + + await item(page, "drained", "worker-a").click(); + + await expect(page).toHaveURL(new RegExp(`/inbox/${encodeURIComponent(`${a?.id}/drained`)}$`)); + const drawer = page.getByRole("dialog"); + await expect(drawer.getByRole("heading", { name: "worker-a" })).toBeVisible(); + await expect(drawer.getByRole("region", { name: "What happened" })).toContainText( + "worker-a is drained", + ); + await expect(facts(page)).toContainText(/Leases still held\s*0/); + await expect(drawer.getByRole("link", { name: "Open worker" })).toHaveAttribute( + "href", + `/fleet/${encodeURIComponent(a?.id ?? "")}`, + ); + + expect((await fleet.gateway.cli(["worker", "undrain", a?.id ?? ""])).code).toBe(0); + await untilTheDaemonSays(fleet.gateway, (views) => views[0]?.drained === false); + + await expect(drawer).toContainText("This is no longer in the Inbox.", { timeout: 1_000 }); + await expect(drawer.getByRole("region", { name: "What happened" })).toHaveCount(0); + } finally { + await disposeFleet(fleet); + } + }); + test("draining a worker adds it to the Inbox view within a second", async ({ page }) => { const fleet = await startFleet([ { driverScript: { ios: IOS }, label: "worker-a" }, From ffa55c72953c13dad9caac4c339405c9da74c1c3 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:45:27 +0200 Subject: [PATCH 34/57] feat(console): an Inbox row opens a drawer at /inbox/ with the what-happened box and the item's details (#768) --- ui/src/model/inbox.test.ts | 6 +- ui/src/model/inbox.ts | 121 +++++++++++++++++++++++++++------ ui/src/screens/inbox/inbox.css | 22 +++--- ui/src/screens/inbox/index.tsx | 97 ++++++++++++++++++++++++-- 4 files changed, 208 insertions(+), 38 deletions(-) diff --git a/ui/src/model/inbox.test.ts b/ui/src/model/inbox.test.ts index 8ad16fa8f..05cb9eb44 100644 --- a/ui/src/model/inbox.test.ts +++ b/ui/src/model/inbox.test.ts @@ -567,6 +567,10 @@ describe("the Inbox page", () => { it("links each item to its worker's page", () => { const page = pageOf([worker({ drained: true, id: "wrk/1", label: "mac-mini-1" })]); - expect(shownOf(page).worker).toEqual({ name: "mac-mini-1", to: "/fleet/wrk%2F1" }); + expect(shownOf(page).about).toEqual({ + name: "mac-mini-1", + open: "Open worker", + to: "/fleet/wrk%2F1", + }); }); }); diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index db7cff9ed..9efbef7a2 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -3,13 +3,15 @@ import { type ConsoleEvent, timeOfDay, workerIdOf } from "./events"; import { inboxPath, itemPath } from "./paths"; import { deviceOfLease, + eventsOfLease, holderName, isExpiring, type LeaseRecord, + leasePath, type TokenRecord, } from "./leases"; import { formatDuration } from "./time"; -import type { WaitingRequest } from "./waiting"; +import { requestedDevice, type WaitingRequest } from "./waiting"; import type { Tone } from "./tones"; import { stateEnteredAt, @@ -209,7 +211,9 @@ export interface InboxDetail { readonly title: string; readonly tone: Tone; readonly word: string; - readonly worker: { readonly name: string; readonly to: string }; + // why: the box at the top of the drawer, saying in a sentence what the Inbox found. + readonly what: string; + readonly about: { readonly name: string; readonly to: string; readonly open: string }; readonly facts: readonly InboxFact[]; readonly events: readonly InboxEvent[]; } @@ -258,10 +262,56 @@ export function inboxSubject(item: InboxItem): string { : workerName(item.worker); } -function factsOf(item: WorkerItem, now: number): readonly InboxFact[] { +function factsOf(item: InboxItem, now: number): readonly InboxFact[] { + if (item.condition === "waiting") { + return [ + { label: "Waited", value: formatDuration(item.waitedMs) }, + { label: "Device", value: requestedDevice(item.request.spec) }, + { label: "Request", value: item.request.id }, + ]; + } + if (item.condition === "ending") { + return [ + { label: "Time left", value: timeLeft(item.leftMs) }, + { label: "Device", value: item.model }, + { label: "Holder", value: item.holder }, + { label: "Lease", value: item.lease.id }, + ]; + } return "device" in item ? deviceFacts(item, now) : workerFacts(item, now); } +function timeLeft(leftMs: number): string { + return leftMs <= 0 ? "now" : minutesAndSeconds(leftMs); +} + +// why: each sentence says what the daemon found and what it means, so the drawer opens on the +// reason before the details. +function whatHappened(item: InboxItem): string { + switch (item.condition) { + case "disconnected": + return `${workerName(item.worker)} has lost its connection to the gateway.`; + case "incompatible": + return `${workerName(item.worker)} runs a protocol this gateway cannot talk to.`; + case "drained": + return `${workerName(item.worker)} is drained: it takes no new leases.`; + case "over RAM budget": + return `${workerName(item.worker)} uses more memory than its budget allows.`; + case "quarantined": + return `${item.device.spec.model} is quarantined and cannot be leased until it is dealt with.`; + case "stalled": + return `${item.device.spec.model} has stayed in one state longer than expected.`; + case "absent": + return `${inboxSubject(item)}: the phone cannot be reached.`; + case "waiting": + return `${item.request.requesterId} has waited ${formatDuration(item.waitedMs)} for a device.`; + case "ending": + return `${item.holder}'s lease on ${item.model} ${ + item.leftMs <= 0 ? "ends now" : `ends in ${minutesAndSeconds(item.leftMs)}` + }.`; + } +} + function deviceFacts( item: Extract, now: number, @@ -330,19 +380,50 @@ function workerFacts( ]; } -function namesItem(event: ConsoleEvent, item: WorkerItem): boolean { - if (workerIdOf(event) === item.worker.id) return true; - if (!("device" in item)) return false; +function payloadField(event: ConsoleEvent, field: string): unknown { const { payload } = event; - return ( - typeof payload === "object" && - payload !== null && - (payload as Record).deviceId === item.device.id + return typeof payload === "object" && payload !== null + ? (payload as Record)[field] + : undefined; +} + +function eventsOfItem(item: InboxItem, events: readonly ConsoleEvent[]): readonly ConsoleEvent[] { + if (item.condition === "ending") return eventsOfLease(events, item.lease.id); + if (item.condition === "waiting") { + return events.filter((event) => payloadField(event, "requestId") === item.request.id); + } + return events.filter( + (event) => + workerIdOf(event) === item.worker.id || + ("device" in item && payloadField(event, "deviceId") === item.device.id), ); } +function aboutOf(item: InboxItem): InboxDetail["about"] { + if (item.condition === "waiting") { + return { + name: item.request.requesterId, + open: "Open request", + to: itemPath("/queue", item.request.id), + }; + } + if (item.condition === "ending") { + return { + name: `${item.holder} · ${item.model}`, + open: "Open lease", + to: leasePath(item.lease.id), + }; + } + return { name: workerName(item.worker), open: "Open worker", to: workerPath(item.worker.id) }; +} + +function titleOf(item: InboxItem): string { + if ("device" in item) return `${item.device.spec.model} ${item.device.spec.osVersion}`; + return aboutOf(item).name; +} + function detailOf( - item: WorkerItem, + item: InboxItem, input: { readonly workers: readonly WorkerView[]; readonly events: readonly ConsoleEvent[]; @@ -351,9 +432,12 @@ function detailOf( ): InboxDetail { const { events, now, workers } = input; return { - events: events - .filter((event) => event.timestamp > now - HOUR && namesItem(event, item)) - .sort((a, b) => b.timestamp - a.timestamp || b.seq - a.seq) + about: aboutOf(item), + events: eventsOfItem( + item, + events.filter((event) => event.timestamp > now - HOUR), + ) + .toSorted((a, b) => b.timestamp - a.timestamp || b.seq - a.seq) .slice(0, EVENT_ROWS) .map((event) => { const tone = eventTone(event.event); @@ -368,13 +452,10 @@ function detailOf( }), facts: factsOf(item, now), key: item.key, - title: - "device" in item - ? `${item.device.spec.model} ${item.device.spec.osVersion}` - : workerName(item.worker), + title: titleOf(item), tone: inboxTone(item.condition), + what: whatHappened(item), word: item.condition, - worker: { name: workerName(item.worker), to: workerPath(item.worker.id) }, }; } @@ -401,7 +482,7 @@ export function inboxPageOf(input: { const named = input.key !== undefined; const chosen = named ? items.find((item) => item.key === input.key) : items[0]; const problems = items.filter((item) => inboxGroup(item) !== "Heads-up").length; - if (chosen !== undefined && "worker" in chosen) { + if (chosen !== undefined) { return { named, problems, rows, shown: detailOf(chosen, input) }; } return { named, problems, rows, shown: named ? "resolved" : undefined }; diff --git a/ui/src/screens/inbox/inbox.css b/ui/src/screens/inbox/inbox.css index 2a193bab2..f918ceabd 100644 --- a/ui/src/screens/inbox/inbox.css +++ b/ui/src/screens/inbox/inbox.css @@ -1,14 +1,15 @@ -.fact-label { - margin: 0 0 var(--space-1); - color: var(--text-muted); - font-size: var(--text-xs); +.inbox-drawer { + display: grid; + gap: var(--space-4); + padding: var(--space-4); +} + +.inbox-what p { + margin: 0 0 var(--space-2); } -.fact-value { +.inbox-what p:last-child { margin: 0; - overflow-wrap: anywhere; - font-family: var(--font-mono); - font-size: var(--text-md); } .inbox-events { @@ -70,11 +71,6 @@ } } -.inbox-worker { - min-width: 0; - overflow-wrap: anywhere; -} - .inbox-list { margin: 0; padding: 0; diff --git a/ui/src/screens/inbox/index.tsx b/ui/src/screens/inbox/index.tsx index 2ccd6a375..00872d998 100644 --- a/ui/src/screens/inbox/index.tsx +++ b/ui/src/screens/inbox/index.tsx @@ -1,12 +1,35 @@ import "./inbox.css"; -import { ChoiceChips, Empty, Link, Loaded, Page, Panel, StatusDot, Toolbar } from "../../ds"; -import { INBOX_FILTERS, type InboxFilter, type InboxRow, useInbox } from "../../state/inbox"; +import { + ButtonLink, + ChoiceChips, + Drawer, + Empty, + Facts, + focusAfterClosing, + Link, + Loaded, + Page, + Panel, + Status, + StatusDot, + Toolbar, +} from "../../ds"; +import { + INBOX_FILTERS, + type InboxEvent, + type InboxFilter, + type InboxPage, + type InboxRow, + useInbox, + useInboxDrawer, +} from "../../state/inbox"; const GROUP_ORDER = ["Broken", "Needs a look", "Heads-up"] as const; export function InboxScreen() { - const { choose, filter, rows, view } = useInbox(); + const { choose, filter, rows, urlId, view } = useInbox(); + const { close, fromList } = useInboxDrawer(urlId); return ( } /> - {(page) => } + + {(page) => ( + <> + + {urlId === undefined ? null : ( + + focusAfterClosing({ + fromList, + links: "main .inbox-list a", + path: `/inbox/${encodeURIComponent(urlId)}`, + }) + } + > + + + )} + + )} + ); } @@ -60,3 +105,47 @@ export function InboxBody(props: { ); } + +// why: an address can name an item the daemon has since cleared; the drawer says so instead of +// keeping the details it last held. +export function InboxDrawerBody({ shown }: { readonly shown: InboxPage["shown"] }) { + if (typeof shown !== "object") { + return

        This is no longer in the Inbox.

        ; + } + return ( +
        +
        +

        + {shown.word} +

        +

        {shown.what}

        +
        +
        + +
        + {shown.about.open} + + + +
        + ); +} + +function EventList({ events }: { readonly events: readonly InboxEvent[] }) { + if (events.length === 0) return No events in the last hour.; + return ( +
          + {events.map((event) => ( +
        • + + {event.time} + + {event.name} + + {event.text} + +
        • + ))} +
        + ); +} From f76626749779dcafc97616f1b051eb092efe828f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:52:52 +0200 Subject: [PATCH 35/57] feat(console): the Inbox e2e follows the drawer, and the drawer of a request and a lease is tested (#768) --- e2e/console/inbox.spec.ts | 43 +++++++++++----------------- ui/src/model/inbox.test.ts | 58 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 26 deletions(-) diff --git a/e2e/console/inbox.spec.ts b/e2e/console/inbox.spec.ts index fd2b5b0f6..622439620 100644 --- a/e2e/console/inbox.spec.ts +++ b/e2e/console/inbox.spec.ts @@ -151,6 +151,11 @@ function item(page: Page, condition: string, subject: string): Locator { .filter({ hasText: subject }); } +async function closeDrawer(page: Page): Promise { + await page.getByRole("dialog").getByRole("button", { name: "Close" }).click(); + await expect(page.getByRole("dialog")).toHaveCount(0); +} + function facts(page: Page): Locator { return page.getByRole("group", { name: "Facts" }); } @@ -222,6 +227,7 @@ test.describe("the Inbox view", () => { platform: "ios", queuePosition: 1, requesterId: id, + spec: { platform: "ios" }, stage: "queued", }); await route.fulfill({ @@ -321,7 +327,9 @@ test.describe("the Inbox view", () => { expect(address).toBe(`/inbox/${encodeURIComponent("lease/wrk_a.lse_1/ending")}/`); await page.reload(); - await expect(page.getByRole("heading", { level: 1, name: "Inbox" })).toBeVisible(); + await expect( + page.getByRole("dialog").getByRole("heading", { name: "tok_stub · dev_stub" }), + ).toBeVisible(); expect(new URL(page.url()).pathname).toBe(address); } finally { await host.dispose(); @@ -385,7 +393,10 @@ test.describe("the Inbox view", () => { ); await expect(rows(page)).toHaveCount(1); await expect(page).toHaveURL(/\/inbox$/); - await expect(page.getByRole("heading", { level: 2, name: "worker-b" })).toBeVisible(); + await drained.click(); + await expect( + page.getByRole("dialog").getByRole("heading", { name: "worker-b" }), + ).toBeVisible(); await expect(page.getByRole("link", { name: "Open worker" })).toHaveAttribute( "href", `/fleet/${encodeURIComponent(b?.id ?? "")}`, @@ -420,30 +431,6 @@ test.describe("the Inbox view", () => { } }); - test("an item named in the URL that leaves the Inbox says Resolved. with a link back", async ({ - page, - }) => { - const fleet = await startFleet([{ driverScript: { ios: IOS }, label: "worker-a" }]); - try { - const [a] = await workers(fleet.gateway); - expect((await fleet.gateway.cli(["worker", "drain", a?.id ?? ""])).code).toBe(0); - await openInbox(page, fleet.gateway); - await item(page, "drained", "worker-a").click(); - await expect(page).toHaveURL(/\/inbox\/.+/); - await expect(page.getByRole("heading", { level: 2, name: "worker-a" })).toBeVisible(); - - expect((await fleet.gateway.cli(["worker", "undrain", a?.id ?? ""])).code).toBe(0); - await untilTheDaemonSays(fleet.gateway, (views) => views[0]?.drained === false); - - await expect(page.getByText("Resolved.")).toBeVisible({ timeout: 1_000 }); - await page.getByRole("link", { name: "Back to Inbox" }).click(); - await expect(page).toHaveURL(/\/inbox$/); - await expect(page.getByText("Nothing needs you.")).toBeVisible(); - } finally { - await disposeFleet(fleet); - } - }); - test("stopping a worker adds it as disconnected within a second", async ({ page }) => { const fleet = await startFleet([ { driverScript: { ios: IOS }, label: "worker-a" }, @@ -518,8 +505,11 @@ test.describe("the Inbox view", () => { await expect(facts(page)).toContainText("Gateway protocol"); await expect(facts(page)).toContainText("Worker protocol"); + await closeDrawer(page); + await item(page, "quarantined", "iPhone 16 on worker-a").click(); await expect(facts(page)).toContainText(quarantined?.id ?? ""); + await closeDrawer(page); await item(page, "stalled", "iPhone 16 on worker-a").click(); await expect(facts(page)).toContainText(stalled?.id ?? ""); @@ -578,6 +568,7 @@ test.describe("the Inbox view", () => { await item(page, "quarantined", `iPhone 16 on ${name}`).click(); await expect(facts(page)).toContainText(/Cause\s*Purge failed: Error: erase failed/); + await closeDrawer(page); await item(page, "over RAM budget", name).click(); await expect(facts(page)).toContainText(/Used\s*\d+\.\d\d GiB/); diff --git a/ui/src/model/inbox.test.ts b/ui/src/model/inbox.test.ts index 05cb9eb44..521d09672 100644 --- a/ui/src/model/inbox.test.ts +++ b/ui/src/model/inbox.test.ts @@ -282,6 +282,64 @@ describe("the Inbox items of a lease about to end", () => { }); }); +describe("the drawer of a waiting request and of a lease about to end", () => { + it("says what happened, lists the details and links to the request's and the lease's own page", () => { + const requests: WaitingRequest[] = [ + { + createdAt: NOW - 125_000, + id: "req_1", + queuePosition: 1, + requesterId: "agent-b", + spec: { model: "iPhone 16", platform: "ios" }, + stage: "queued", + }, + ]; + const leases: LeaseRecord[] = [ + { + deviceId: "dev_1", + grantedAt: NOW - 60_000, + id: "wrk_1.lse_1", + idChosenByRequester: false, + lastRenewedAt: NOW - 30_000, + ownerId: "tok_1", + requesterId: "tok_1", + ttlDeadline: NOW + 90_000, + ttlMs: 900_000, + }, + ]; + const workers = [worker({ devices: [device("dev_1")] })]; + const shown = (key: string) => + shownOf(inboxPageOf({ events: [], key, leases, now: NOW, requests, workers })); + + const waiting = shown("request/req_1/waiting"); + const ending = shown("lease/wrk_1.lse_1/ending"); + + expect(waiting.what).toBe("agent-b has waited 2 min 5 s for a device."); + expect(waiting.facts.map((fact) => [fact.label, fact.value])).toEqual([ + ["Waited", "2 min 5 s"], + ["Device", "iOS iPhone 16"], + ["Request", "req_1"], + ]); + expect(waiting.about).toEqual({ + name: "agent-b", + open: "Open request", + to: "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/queue/req_1", + }); + expect(ending.what).toBe("tok_1's lease on iPhone 16 ends in 1:30."); + expect(ending.facts.map((fact) => [fact.label, fact.value])).toEqual([ + ["Time left", "1:30"], + ["Device", "iPhone 16"], + ["Holder", "tok_1"], + ["Lease", "wrk_1.lse_1"], + ]); + expect(ending.about).toEqual({ + name: "tok_1 · iPhone 16", + open: "Open lease", + to: "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/leases/wrk_1.lse_1/", + }); + }); +}); + describe("the order of the Inbox items", () => { it("keeps the order given for problems, puts the longest wait first and the least time left first", () => { const request = (id: string, waitedMs: number): WaitingRequest => ({ From 839dd1d114a07a5ee687030a73913e25d8702e28 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:54:01 +0200 Subject: [PATCH 36/57] test: the sidebar's Inbox count equals the problem items and is hidden at 0 (#768) --- e2e/console/inbox.spec.ts | 67 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/e2e/console/inbox.spec.ts b/e2e/console/inbox.spec.ts index 622439620..5f43b53ed 100644 --- a/e2e/console/inbox.spec.ts +++ b/e2e/console/inbox.spec.ts @@ -578,7 +578,9 @@ test.describe("the Inbox view", () => { } }); - test("the Inbox count shows in the shell from every view", async ({ page }) => { + test("the sidebar's Inbox count equals the problem items and is hidden at 0", async ({ + page, + }) => { const gateway = await startDaemon("gateway"); const hangUps: (() => void)[] = []; try { @@ -588,6 +590,56 @@ test.describe("the Inbox view", () => { gateway, (views) => views.filter((view) => view.connection === "incompatible").length === 2, ); + // why: a request that has waited two minutes is a problem item and counts; a lease about to end + // is a heads-up and does not. Neither can be had quickly from a real daemon, so both are stubbed, + // the waiting list by `waiters` so that it can empty. + let waiters = ["long-waiter"]; + await page.route( + (url) => url.pathname === "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/v1/lease-requests", + async (route: Route) => { + const response = await route.fetch(); + const now = new Date(response.headers().date ?? "").getTime(); + await route.fulfill({ + json: { + requests: waiters.map((id) => ({ + createdAt: now - 125_000, + id, + platform: "ios", + queuePosition: 1, + requesterId: id, + spec: { platform: "ios" }, + stage: "queued", + })), + }, + response, + }); + }, + ); + await page.route( + (url) => url.pathname === "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/v1/leases", + async (route: Route) => { + const response = await route.fetch(); + const now = new Date(response.headers().date ?? "").getTime(); + await route.fulfill({ + json: { + leases: [ + { + deviceId: "dev_stub", + grantedAt: now - 60_000, + id: "lease-soon", + idChosenByRequester: false, + lastRenewedAt: now - 30_000, + ownerId: "tok_stub", + requesterId: "tok_stub", + ttlDeadline: now + 60_000, + ttlMs: 900_000, + }, + ], + }, + response, + }); + }, + ); await page.goto(gateway.url); await signIn(page, gateway.tokens.operator); @@ -600,7 +652,7 @@ test.describe("the Inbox view", () => { .getByRole("link", { name: label }) .click(); await expect(page.getByRole("heading", { level: 1, name: label })).toBeVisible(); - await expect(inboxLink).toHaveAccessibleName("Inbox 2 items"); + await expect(inboxLink).toHaveAccessibleName("Inbox 3 items"); } // why: One worker hangs up and is removed: its item goes, and one from the count. @@ -611,7 +663,18 @@ test.describe("the Inbox view", () => { const removed = await gateway.cli(["worker", "remove", "wrk_old_1"]); expect(removed.code, removed.stderr).toBe(0); await untilTheDaemonSays(gateway, (views) => views.length === 1); + await expect(inboxLink).toHaveAccessibleName("Inbox 2 items"); + + waiters = []; await expect(inboxLink).toHaveAccessibleName("Inbox 1 item"); + + hangUps.shift()?.(); + await untilTheDaemonSays(gateway, (views) => + views.some((view) => view.id === "wrk_old_2" && view.connection === "disconnected"), + ); + const removedLast = await gateway.cli(["worker", "remove", "wrk_old_2"]); + expect(removedLast.code, removedLast.stderr).toBe(0); + await expect(inboxLink).toHaveAccessibleName("Inbox"); } finally { for (const hangUp of hangUps) hangUp(); await gateway.dispose(); From 52c8594db56d1a2108ab9866ea98c8e1f38756d7 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:54:26 +0200 Subject: [PATCH 37/57] feat(console): the sidebar's Inbox count is the problem items (#768) --- ui/src/model/inbox.ts | 7 ++++++- ui/src/state/shell.ts | 9 +++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/ui/src/model/inbox.ts b/ui/src/model/inbox.ts index 9efbef7a2..31b695932 100644 --- a/ui/src/model/inbox.ts +++ b/ui/src/model/inbox.ts @@ -154,6 +154,11 @@ export function inboxGroup(item: InboxItem): InboxGroup { return inboxTone(item.condition) === "error" ? "Broken" : "Needs a look"; } +// why: a heads-up is not a problem yet, so the count the sidebar and Overview show leaves it out. +export function problemCount(items: readonly InboxItem[]): number { + return items.filter((item) => inboxGroup(item) !== "Heads-up").length; +} + // why: the Inbox lists its groups in a fixed order, each keeping the order its items came in. export function inGroupOrder(items: readonly InboxItem[]): readonly InboxItem[] { return GROUPS.flatMap((group) => items.filter((item) => inboxGroup(item) === group)); @@ -481,7 +486,7 @@ export function inboxPageOf(input: { })); const named = input.key !== undefined; const chosen = named ? items.find((item) => item.key === input.key) : items[0]; - const problems = items.filter((item) => inboxGroup(item) !== "Heads-up").length; + const problems = problemCount(items); if (chosen !== undefined) { return { named, problems, rows, shown: detailOf(chosen, input) }; } diff --git a/ui/src/state/shell.ts b/ui/src/state/shell.ts index 2814ec9f5..bae5205e7 100644 --- a/ui/src/state/shell.ts +++ b/ui/src/state/shell.ts @@ -1,16 +1,21 @@ import { useEffect, useState, useSyncExternalStore } from "react"; import type { ConnectionPhase } from "../data/live/connection"; -import { inboxItems } from "../model/inbox"; +import { inboxItems, problemCount } from "../model/inbox"; import { formatDuration } from "../model/time"; import type { Toned } from "../model/tones"; import type { WorkerList } from "../model/workers"; +import { useInboxReads } from "./inbox"; import { useConnection, useLiveResource, useNow } from "./live"; import { useApi, useSession } from "./services"; export function useInboxCount(): number | undefined { const workers = useLiveResource("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/v1/workers").data?.workers; - return workers === undefined ? undefined : inboxItems(workers).length; + const { leases, tokens, waiting } = useInboxReads(); + const now = useNow(); + if (workers === undefined) return undefined; + const requests = waiting.kind === "ready" ? waiting.data.requests : []; + return problemCount(inboxItems(workers, { leases, now: now.server, requests, tokens })); } // why: a 401 at any time signs the operator out; a tab reloaded with a token since revoked finds out From 878f43ed0dab88ed131e467afdaf697ef3030e24 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:55:53 +0200 Subject: [PATCH 38/57] test: on a single host, Overview shows all five numbers and both charts (#768) --- e2e/console/overview.spec.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/e2e/console/overview.spec.ts b/e2e/console/overview.spec.ts index e71cc2035..867c08e0c 100644 --- a/e2e/console/overview.spec.ts +++ b/e2e/console/overview.spec.ts @@ -230,6 +230,28 @@ test.describe("the Overview's figures", () => { } }); + test("on a single host, Overview shows all five numbers and both charts", async ({ page }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await openOverview(page, host); + + for (const label of ["Leased", "Waiting", "Workers", "Wait p95", "Ending soon"]) { + await expect(tile(page, label), label).toBeVisible(); + } + await expect + .poll(() => tileText(page, "Leased")) + .toMatch(/^Leased \| 0 \| of \d+ · \d+ ready$/); + await expect.poll(() => tileText(page, "Workers")).toBe("Workers | 1 | of 1"); + await expect.poll(() => tileText(page, "Waiting")).toMatch(/^Waiting \| 0 \|/); + await expect.poll(() => tileText(page, "Ending soon")).toBe("Ending soon | 0 | under 5 min"); + await expect(page.getByRole("region", { name: "Leases held" })).toBeVisible(); + await expect(page.getByRole("region", { name: "Requests in the queue" })).toBeVisible(); + await expect(page.locator("#main details.chart-data")).toHaveCount(2); + } finally { + await host.dispose(); + } + }); + test("Overview's tiles and links land on /queue, /fleet and /activity, not Not found", async ({ page, }) => { From 422eba68753f241b8e2637af168815f146a67d95 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:57:01 +0200 Subject: [PATCH 39/57] test: axe passes on Overview and Inbox, empty and busy, in light and dark (#768) --- e2e/console/shell.spec.ts | 67 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/e2e/console/shell.spec.ts b/e2e/console/shell.spec.ts index 36643fe14..6aff56dba 100644 --- a/e2e/console/shell.spec.ts +++ b/e2e/console/shell.spec.ts @@ -1,5 +1,5 @@ import { AxeBuilder } from "@axe-core/playwright"; -import type { Page } from "@playwright/test"; +import type { Page, Route } from "@playwright/test"; import { expect, @@ -222,7 +222,7 @@ test.describe("the shell", () => { }); for (const colorScheme of ["light", "dark"] as const) { - test(`the shell passes an automated WCAG AA contrast check in both themes (${colorScheme})`, async ({ + test(`the shell, and Overview and Inbox empty and busy, pass an automated WCAG AA contrast check (${colorScheme})`, async ({ daemon, page, }) => { @@ -248,6 +248,69 @@ test.describe("the shell", () => { await expect(page.getByRole("button", { name: "Sign out" })).toBeVisible(); await expect(page.getByRole("heading", { level: 1, name: "Overview" })).toBeVisible(); expect(await audit()).toEqual([]); + + await page.goto("/inbox"); + await expect(page.getByRole("heading", { level: 1, name: "Inbox" })).toBeVisible(); + await expect(page.getByText("Nothing needs you.")).toBeVisible(); + expect(await audit()).toEqual([]); + + // why: a request that has waited two minutes and a lease about to end fill the Inbox's groups + // and the Overview's panel; neither can be had quickly from a real daemon, so both are stubbed. + await page.route( + (url) => url.pathname === "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/v1/lease-requests", + async (route: Route) => { + const response = await route.fetch(); + const now = new Date(response.headers().date ?? "").getTime(); + await route.fulfill({ + json: { + requests: [ + { + createdAt: now - 125_000, + id: "req_busy", + queuePosition: 1, + requesterId: "busy-agent", + spec: { platform: "ios" }, + stage: "queued", + }, + ], + }, + response, + }); + }, + ); + await page.route( + (url) => url.pathname === "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/v1/leases", + async (route: Route) => { + const response = await route.fetch(); + const now = new Date(response.headers().date ?? "").getTime(); + await route.fulfill({ + json: { + leases: [ + { + deviceId: "dev_busy", + grantedAt: now - 60_000, + id: "lse_busy", + idChosenByRequester: false, + lastRenewedAt: now - 30_000, + ownerId: "tok_busy", + requesterId: "tok_busy", + ttlDeadline: now + 60_000, + ttlMs: 900_000, + }, + ], + }, + response, + }); + }, + ); + await page.goto("/inbox"); + await expect(page.getByRole("region", { name: "Needs a look" })).toBeVisible(); + await expect(page.getByRole("region", { name: "Heads-up" })).toBeVisible(); + expect(await audit()).toEqual([]); + + await page.goto("/"); + await expect(page.getByRole("region", { name: "Needs you" })).toBeVisible(); + expect(await audit()).toEqual([]); }); } }); From 98d56a08094a86cc4d6b692a9cff941e80655c8c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 08:58:18 +0200 Subject: [PATCH 40/57] test: no