From a539e561cb583004767a1857c7b3e4eba15e9294 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 22:39:25 +0200 Subject: [PATCH 1/3] feat(ui,core,daemon,cli,docs): the attention view, and a stalled flag on status devices Closes #275 --- docs/CLI.md | 7 +- docs/CONFIGURATION.md | 2 +- docs/CONSOLE.md | 31 ++- docs/HTTP-API.md | 22 +- e2e/console/attention.spec.ts | 410 ++++++++++++++++++++++++++++++++ src/cli/index.test.ts | 31 +++ src/cli/index.ts | 1 + src/contract/schemas.ts | 12 + src/core/doctor.test.ts | 136 ++++++++++- src/core/doctor.ts | 84 +++++-- src/core/index.ts | 2 +- src/daemon/dispatcher.test.ts | 39 +++ src/daemon/dispatcher.ts | 43 +++- src/daemon/main.ts | 4 + src/daemon/server.ts | 4 + src/gateway/service.test.ts | 27 +++ ui/src/shell.tsx | 6 + ui/src/styles.css | 49 ++++ ui/src/views/attention-model.ts | 69 ++++++ ui/src/views/attention.test.tsx | 177 ++++++++++++++ ui/src/views/attention.tsx | 121 ++++++++++ ui/src/views/index.tsx | 5 +- 22 files changed, 1246 insertions(+), 36 deletions(-) create mode 100644 e2e/console/attention.spec.ts create mode 100644 ui/src/views/attention-model.ts create mode 100644 ui/src/views/attention.test.tsx create mode 100644 ui/src/views/attention.tsx diff --git a/docs/CLI.md b/docs/CLI.md index eeb2f78c1..85a8fa055 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1065,7 +1065,12 @@ the background, and is never handed to a new requester. A device currently `provisioning` or `reclaiming` carries a derived `transitionAgeMs` — how long it has been in that state — visible in `status` and `list --devices` well before it crosses the threshold that would make -`doctor` flag it as stalled. +`doctor` flag it as stalled. Once it crosses it, with nothing working on it, +`status` marks it `stalled` +(`Device dev_7: provisioning, mode full (mid-transition 412000ms, stalled)`), +and `--json` and `list --devices` carry `"stalled": true` on it. These are the +devices `doctor` reports as `stalled-transition`; no other device carries the +field. Human-oriented overview: daemon health *and mode*, the web console's address when HTTP is enabled (`Console: http://127.0.0.1:4700/`, see diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 49927d1cf..90d80840b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -58,7 +58,7 @@ edit yourself keeps the mode you give it until the next `config set`; run | `health.maxRecoveryAttempts` | Reboot attempts for one lease before the lease is given up as lost. | `3` | | `health.recoveryBackoffMs` | Base delay between reboot attempts; the monitor applies exponential backoff over it. | `5 seconds` | | `health.maxConcurrentRecoveries` | Cap on simultaneous recovery reboots, so a machine wake (every device reads `stopped` at once) cannot start a boot storm. | `1` | -| `stalledTransition.thresholdMultiplier` | Factor applied to a driver's own `provision + boot` (for `provisioning`) or `reclaim` (for `reclaiming`) estimate to get the stall threshold for `simlock doctor`'s `stalled-transition` finding. | `3` | +| `stalledTransition.thresholdMultiplier` | Factor applied to a driver's own `provision + boot` (for `provisioning`) or `reclaim` (for `reclaiming`) estimate to get the stall threshold: past it, `simlock doctor` reports a `stalled-transition` finding and `simlock status` marks the device `stalled`. | `3` | | `stalledTransition.minimumThresholdMs` | Floor under the multiplied estimate, for a driver whose estimate is near zero. | `1 minute` | | `drivers.ios.deviceRoot` | The CoreSimulator device set Simlock owns and scopes every `simctl` call to. See [Device roots](#device-roots). | `${SIMLOCK_HOME}/devices/ios` | | `drivers.android.deviceRoot` | The AVD home Simlock owns; exported as `ANDROID_AVD_HOME` to every `avdmanager`/`emulator` call. See [Device roots](#device-roots). | `${SIMLOCK_HOME}/devices/android` | diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index 6dd7699df..853c99351 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -9,8 +9,8 @@ The console is for people who operate Simlock. It needs an operator token. Coding agents keep using the CLI, the MCP server, the client and the HTTP API. This version has sign-in, the console's navigation (Workers, Leases, Waiting, -Attention and Events), the Workers pages and the Waiting page. The other -pages say "Coming soon" until their views are built. +Attention and Events), the Workers pages, the Waiting page and the Attention +page. The other pages say "Coming soon" until their views are built. ## Turn it on @@ -147,6 +147,33 @@ host every request shows that host as its worker. A request leaves the list as soon as it gets its device, fails, or is cancelled. +## Attention + +**Attention** lists everything that needs you, in one place. Each item names +its worker and links to that worker's page. An item leaves the list as soon as +its condition clears. The console only shows these; it does not fix them. + +| Item | What it means | +| --- | --- | +| `disconnected` | The gateway has lost its connection to the worker. | +| `incompatible` | The worker and the gateway have no protocol version in common. The worker's page says which versions each speaks. | +| `drained` | The worker gets no new leases (`simlock worker drain`). | +| `over RAM budget` | The devices on the worker use more RAM than its budget allows, as `simlock status` reports with `(over limit)`. | +| `quarantined` | A device Simlock could not clean up. It retries the cleanup in the background and leases the device to no one meanwhile. | +| `stalled` | A device stuck `provisioning` or `reclaiming` for longer than it should take, with nothing working on it. `simlock doctor` reports the same devices. | + +The first three come from a gateway only: a single host has no gateway to lose +or disagree with, and cannot be drained. The other three show on a single host +too. + +The navigation shows how many items there are beside **Attention**, on every +page. It shows no number while there are none. + +Each item shows within about a second of the daemon reporting it. A stalled +device is the exception on a gateway: a device becomes stalled when its time +runs out, not by anything happening, so the gateway sees it the next time it +reads that worker, which it does at least every 30 seconds. + ## Live updates Every page keeps itself current. A change on the daemon, such as a lease diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 16d1a8b27..5b812a04c 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -210,6 +210,18 @@ device, oldest first, in the shape [`GET /v1/lease-requests`](#get-v1lease-requests) answers. A worker always sends it, empty when nothing waits; an older daemon leaves it out. +A device in `devices` that is `provisioning` or `reclaiming` carries +`transitionAgeMs`, how long it has been in that state. One that has been there +past its threshold with nothing working on it also carries +**`stalled: true`**: the same devices `simlock doctor` reports as stalled (see +`stalledTransition.*` in [CONFIGURATION.md](CONFIGURATION.md)). Every other +device has no `stalled` field, and an older daemon sends none. + +```json +{ "id": "dev_7", "state": "provisioning", "mode": "full", "transitionAgeMs": 412000, "stalled": true, + "spec": { "platform": "ios", "model": "iPhone 16", "osVersion": "18.4" } } +``` + On a **gateway** the numbers are the fleet's — capacity summed across connected workers (`ramBudget` over the workers that report one, `overLimit` when any of them is, absent when none does), every gateway-issued and local lease, every device, the @@ -1054,6 +1066,11 @@ which worker has a custom Android profile. `host` is the worker's machine, the s `GET /v1/status` reports, as of the gateway's last refresh: a tool installed or upgraded on the worker shows here without a restart of either side. +`devices` are the worker's devices as its own +[`GET /v1/status`](#get-v1status) reports them, `stalled` included. A device +stalls with no event to report it, so the gateway shows a new stall after its +next periodic refresh of that worker. + `protocol` appears only on an `incompatible` worker: it names both ranges, the worker's and the gateway's, so you can see which side to upgrade. A worker too old to overlap is the ordinary upgrade path, not a fault, and its view @@ -1122,8 +1139,9 @@ an all-or-nothing that leaves the operator guessing. - `GET /v1/leases` — every active lease (`simlock list --leases`). - `GET /v1/lease-requests` — every request waiting for a device (`simlock list --requests`); see below. -- `GET /v1/devices` — every managed device, with state and - `transitionAgeMs` (`simlock list --devices`). +- `GET /v1/devices` — every managed device, with state, + `transitionAgeMs` and `stalled` as [`GET /v1/status`](#get-v1status) + describes them (`simlock list --devices`). - `GET /v1/events?since=` — replay business events newer than `since` (`simlock events --since`). They come from the daemon's event file, so they include events from before a daemon restart and beyond the 1000 diff --git a/e2e/console/attention.spec.ts b/e2e/console/attention.spec.ts new file mode 100644 index 000000000..29b07655e --- /dev/null +++ b/e2e/console/attention.spec.ts @@ -0,0 +1,410 @@ +import type { Locator, Page } from "@playwright/test"; + +import { waitFor } from "../helpers/wait.js"; +import { + disposeFleet, + expect, + joinOldWorker, + NAV_LABELS, + type RunningDaemon, + signIn, + startDaemon, + startFleet, + test, +} from "./fixtures.js"; + +/** What `GET /v1/workers` says, as far as these tests read. */ +interface WorkerView { + readonly id: string; + readonly label?: string; + readonly connection: string; + readonly drained: boolean; + readonly capacity?: { readonly ramBudget?: { readonly overLimit: boolean } }; + readonly devices: readonly { readonly id: string; readonly state: string; stalled?: boolean }[]; +} + +const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; + +/** 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 } } }, +}; + +/** + * A worker whose stall threshold is one second: a device left `provisioning` with nothing + * working on it is stalled a second after it entered that state. + */ +const STALLING = { + config: { stalledTransition: { minimumThresholdMs: 1_000, thresholdMultiplier: 1 } }, + driverScript: { ios: IOS }, +} as const; + +async function workers(daemon: RunningDaemon): Promise { + const response = await fetch(new URL("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/v1/workers", daemon.url), { + headers: { Authorization: `Bearer ${daemon.tokens.operator}` }, + }); + return ((await response.json()) as { workers: WorkerView[] }).workers; +} + +/** + * 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( + daemon: RunningDaemon, + predicate: (views: readonly WorkerView[]) => boolean, + timeout = 30_000, +): Promise { + await waitFor(async () => predicate(await workers(daemon)), { + interval: 20, + label: "the daemon's own worker views", + timeout, + }); +} + +async function lease(daemon: RunningDaemon, agent: string): Promise<{ id: string }> { + const granted = await daemon.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--detach", + "--agent-id", + agent, + ]); + expect(granted.code, granted.stderr).toBe(0); + return (granted.json as { lease: { id: string } }).lease; +} + +/** 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); + const released = await daemon.cli(["release", held.id]); + expect(released.code, released.stderr).toBe(0); + await untilTheDaemonSays(daemon, (views) => + views.some((view) => view.devices.some((device) => device.state === "quarantined")), + ); +} + +/** + * 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. + */ +async function strandProvisioning( + daemon: RunningDaemon, + beforeStart: () => Promise = async () => {}, +): Promise { + await daemon.writeDriverScript({ + ios: { ...FAILING_RECLAIM.ios, latencyMs: { makeReady: 120_000 } }, + }); + daemon.cliBackground([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--detach", + "--agent-id", + "console-e2e-stranded", + ]); + await untilTheDaemonSays(daemon, (views) => + views.some((view) => view.devices.some((device) => device.state === "provisioning")), + ); + await daemon.stop(); + await beforeStart(); + await daemon.start(); +} + +async function openAttention(page: Page, daemon: RunningDaemon): Promise { + await page.goto(daemon.url); + await signIn(page, daemon.tokens.operator); + await page.getByRole("link", { name: "Attention" }).click(); + await expect(page.getByRole("heading", { level: 1, name: "Attention" })).toBeVisible(); +} + +/** The item for `condition` about the worker or device named `subject`. */ +function item(page: Page, condition: string, subject: string): Locator { + return page + .locator(".attention-list li") + .filter({ has: page.locator(".status", { hasText: new RegExp(`^${condition}$`) }) }) + .filter({ hasText: subject }); +} + +/** 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 }) => { + 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(); + const b = (await workers(fleet.gateway)).find((view) => view.label === "worker-b"); + + expect((await fleet.gateway.cli(["worker", "drain", b?.id ?? ""])).code).toBe(0); + await untilTheDaemonSays( + fleet.gateway, + (views) => views.find((view) => view.label === "worker-b")?.drained === true, + ); + + const drained = item(page, "drained", "worker-b"); + await expect(drained).toBeVisible({ timeout: 1_000 }); + await expect(drained.getByRole("link", { name: "worker-b" })).toHaveAttribute( + "href", + `/workers/${encodeURIComponent(b?.id ?? "")}`, + ); + await expect(page.locator(".attention-list li")).toHaveCount(1); + } finally { + await disposeFleet(fleet); + } + }); + + test("undraining it removes it within a second", 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); + const drained = item(page, "drained", "worker-a"); + await expect(drained).toBeVisible(); + + expect((await fleet.gateway.cli(["worker", "undrain", a?.id ?? ""])).code).toBe(0); + 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(); + } 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" }, + { driverScript: { ios: IOS }, label: "worker-b" }, + ]); + try { + await openAttention(page, fleet.gateway); + await expect(page.getByText("Nothing needs attention.")).toBeVisible(); + + await (fleet.workers[1] as RunningDaemon).stop(); + await untilTheDaemonSays( + fleet.gateway, + (views) => views.find((view) => view.label === "worker-b")?.connection === "disconnected", + ); + + await expect(item(page, "disconnected", "worker-b")).toBeVisible({ timeout: 1_000 }); + await expect(item(page, "disconnected", "worker-a")).toHaveCount(0); + } finally { + await disposeFleet(fleet); + } + }); + + test("an incompatible worker, and a worker's quarantined and stalled devices, appear on a gateway", async ({ + page, + }) => { + test.setTimeout(120_000); + const gateway = await startDaemon("gateway"); + 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 + // stall threshold. + const worker = await startDaemon("worker", { + ...STALLING, + config: { + ...STALLING.config, + gateway: { + label: "worker-a", + token: gateway.tokens.worker, + url: `ws://127.0.0.1:${gateway.port}`, + }, + }, + }); + fleet.workers.push(worker); + hangUp = await joinOldWorker(fleet.gateway, { id: "wrk_old", label: "old-worker" }); + 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 + // the worker, every 30 seconds. + await untilTheDaemonSays( + fleet.gateway, + (views) => { + devices = views.find((view) => view.label === "worker-a")?.devices ?? []; + return ( + views.some((view) => view.connection === "incompatible") && + devices.some((device) => device.state === "quarantined") && + devices.some((device) => device.stalled === true) + ); + }, + 45_000, + ); + const quarantined = devices.find((device) => device.state === "quarantined"); + const stalled = devices.find((device) => device.stalled === true); + + await openAttention(page, fleet.gateway); + + await expect(item(page, "incompatible", "old-worker")).toBeVisible(); + await expect( + item(page, "quarantined", `Device ${quarantined?.id} on worker-a`), + ).toBeVisible(); + await expect(item(page, "stalled", `Device ${stalled?.id} on worker-a`)).toContainText( + /stuck provisioning for \d+ (s|min)/, + ); + } finally { + hangUp(); + await disposeFleet(fleet); + } + }); + + test("a quarantined device, a stalled device and a host over its RAM budget appear on a single host", async ({ + page, + }) => { + const host = await startDaemon("worker", STALLING); + try { + const status = await host.cli(["status", "--json"]); + 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 + // has put it over. + await strandProvisioning(host, async () => { + const set = await host.cli([ + "config", + "set", + "ramBudget.iosBytesPerDevice", + `${limitBytes + 1024}`, + ]); + expect(set.code, set.stderr).toBe(0); + }); + let view: WorkerView | undefined; + await untilTheDaemonSays(host, (views) => { + [view] = views; + return ( + view?.capacity?.ramBudget?.overLimit === true && + view.devices.some((device) => device.state === "quarantined") && + view.devices.some((device) => device.stalled === true) + ); + }); + const quarantined = view?.devices.find((device) => device.state === "quarantined"); + const stalled = view?.devices.find((device) => device.stalled === true); + + await openAttention(page, host); + + const name = view?.id ?? ""; + await expect(item(page, "quarantined", `Device ${quarantined?.id} on ${name}`)).toBeVisible(); + await expect(item(page, "stalled", `Device ${stalled?.id} on ${name}`)).toBeVisible(); + await expect(item(page, "over RAM budget", name)).toBeVisible(); + await expect(page.locator(".attention-list li")).toHaveCount(3); + } finally { + await host.dispose(); + } + }); + + test("the attention count shows in the shell from every view", async ({ page }) => { + const gateway = await startDaemon("gateway"); + const hangUps: (() => void)[] = []; + try { + hangUps.push(await joinOldWorker(gateway, { id: "wrk_old_1", label: "old-1" })); + hangUps.push(await joinOldWorker(gateway, { id: "wrk_old_2", label: "old-2" })); + await untilTheDaemonSays( + gateway, + (views) => views.filter((view) => view.connection === "incompatible").length === 2, + ); + await page.goto(gateway.url); + await signIn(page, gateway.tokens.operator); + + const attention = page.getByRole("navigation").getByRole("link", { name: /^Attention/ }); + for (const label of NAV_LABELS) { + await page.getByRole("navigation").getByRole("link", { name: label }).click(); + await expect(page.getByRole("heading", { level: 1, name: label })).toBeVisible(); + await expect(attention.locator(".nav-count")).toHaveText(/^\D*2\D*$/); + await expect(attention).toHaveAccessibleName("Attention 2 items"); + } + + // 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"), + ); + 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"); + } finally { + for (const hangUp of hangUps) hangUp(); + await gateway.dispose(); + } + }); + + test("the Attention view has no horizontal scroll at 360px wide", async ({ page }) => { + const gateway = await startDaemon("gateway"); + let hangUp = () => {}; + try { + hangUp = await joinOldWorker(gateway, { + id: "wrk_with_a_long_id_that_does_not_fit_on_a_phone_0123456789", + label: "a-worker-with-a-label-far-too-long-for-one-line-on-a-phone", + }); + await untilTheDaemonSays(gateway, (views) => views.length === 1); + await page.setViewportSize({ height: 740, width: 360 }); + + await openAttention(page, gateway); + + await expect(page.locator(".attention-list li")).toHaveCount(1); + expect(await hasHorizontalScroll(page)).toBe(false); + } finally { + hangUp(); + await gateway.dispose(); + } + }); + + 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. + 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. */ + const follow = async (link: Locator) => { + for (let step = 0; step < 20; step += 1) { + if (await link.evaluate((element) => element === document.activeElement)) break; + await page.keyboard.press(tab); + } + await expect(link).toBeFocused(); + await page.keyboard.press("Enter"); + }; + await page.goto(gateway.url); + await page.keyboard.press(tab); + await page.keyboard.type(gateway.tokens.operator); + await page.keyboard.press("Enter"); + await expect(page.getByRole("heading", { level: 1, name: "Workers" })).toBeVisible(); + + await follow(page.getByRole("navigation").getByRole("link", { name: /^Attention/ })); + await expect(page.getByRole("heading", { level: 1, name: "Attention" })).toBeVisible(); + + await follow(item(page, "incompatible", "old-worker").getByRole("link")); + await expect(page.getByRole("heading", { level: 1, name: "old-worker" })).toBeVisible(); + } finally { + hangUp(); + await gateway.dispose(); + } + }); +}); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index feb243a9f..140878324 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2952,6 +2952,37 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = ).toContain("RAM budget: 13.00 GiB/12.00 GiB used (over limit)\n"); expect(await print(statusWith())).not.toContain("RAM"); }); + + it("simlock status marks a stalled device", async () => { + const device = (id: string, extra: object) => ({ + id, + mode: "full" as const, + spec: { model: "iPhone 16", osVersion: "18.4", platform: "ios" as const }, + state: "provisioning" as const, + ...extra, + }); + const status: StatusGetOutput = { + ...EMPTY_STATUS, + devices: [ + device("dev_stuck", { stalled: true, transitionAgeMs: 120_000 }), + device("dev_fresh", { transitionAgeMs: 2_000 }), + ], + }; + const output = outputCapture(); + await runCli( + ["status"], + output.environmentWith({ + connectAdmin: async () => fakeClient({ getStatus: () => Promise.resolve(status) }), + }), + ); + + expect(output.stdout).toContain( + "Device dev_stuck: provisioning, mode full (mid-transition 120000ms, stalled)\n", + ); + expect(output.stdout).toContain( + "Device dev_fresh: provisioning, mode full (mid-transition 2000ms)\n", + ); + }); }); describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", () => { diff --git a/src/cli/index.ts b/src/cli/index.ts index 5a58a8d40..11074d81d 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -2325,6 +2325,7 @@ function formatStatus(status: StatusGetOutput, now: number): string { device.transitionAgeMs === undefined ? undefined : `mid-transition ${device.transitionAgeMs}ms`, + device.stalled === true ? "stalled" : undefined, ].filter((marker) => marker !== undefined); const suffix = markers.length === 0 ? "" : ` (${markers.join(", ")})`; const where = device.workerId === undefined ? "" : ` on ${device.workerId}`; diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index eeec54e83..f1f304ca0 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -83,6 +83,9 @@ export const deviceRecordSchema = z.object({ leaseIdentity: leaseIdentitySchema.optional(), /** Decoration added by `status.get`/`list.get`; absent for a device not mid-transition. */ transitionAgeMs: z.number().optional(), + /** Decoration added by `status.get`/`list.get`: `true` for a device whose transition is a + * stall by the rule `doctor` reports; absent otherwise. */ + stalled: z.boolean().optional(), }); /** @@ -106,6 +109,8 @@ export const deviceRecordSchema = z.object({ * - `quarantineAttempts`, `quarantineNextRetryAt`: surfaced as purge-retry progress for a * quarantined device, so a caller waiting on capacity can see why a slot isn't freeing up. * - `transitionAgeMs`: the mid-transition decoration, surfaced as "mid-transition ". + * - `stalled`: the stall decoration, surfaced as "stalled": a caller waiting on capacity can see + * that a slot is held by a transition that is not finishing. * * What stays off, and why: `driverDeviceId` (the driver address of a device the caller does * not hold is not actionable -- a non-owning agent cannot drive it, and a holder already gets @@ -130,6 +135,13 @@ export const statusDeviceSchema = z.object({ quarantineNextRetryAt: z.number().optional(), /** Decoration added by `status.get`; absent for a device not mid-transition. */ transitionAgeMs: z.number().optional(), + /** + * Decoration added by `status.get`: `true` for a device stuck `provisioning` or `reclaiming` + * past its threshold, by the rule `doctor`'s `stalled-transition` finding uses; absent for + * every other device. A worker view copies it, so a gateway reports a worker's stall as the + * worker does. + */ + stalled: z.boolean().optional(), /** * ADR 0005 §20: which worker this device lives on. Additive and gateway-only -- a worker * answers `status.get` about its own devices and has no second machine to name, so it never diff --git a/src/core/doctor.test.ts b/src/core/doctor.test.ts index e3b693825..6ea58316c 100644 --- a/src/core/doctor.test.ts +++ b/src/core/doctor.test.ts @@ -5,7 +5,7 @@ import { FakeClock, MemoryFilesystem } from "../ports/index.js"; import { FakeSystemStats } from "../ports/index.js"; import type { Config } from "./config.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; -import { Doctor, type DoctorFinding, type DoctorReport } from "./doctor.js"; +import { Doctor, type DoctorFinding, type DoctorReport, isStalledTransition } from "./doctor.js"; import { DriverCatalog } from "./driver-catalog.js"; import type { DriverRejection, PrerequisiteCheck } from "./driver.js"; import { FakeDriver } from "./fake-driver.js"; @@ -719,6 +719,140 @@ describe("Doctor", () => { }); describe("stalled transitions", () => { + it("isStalledTransition holds for a provisioning device past its threshold with no claim", async () => { + const clock = new FakeClock(10_000); + const registry = await loadRegistry(clock, new EventBus(clock)); + const driver = new FakeDriver({ + clock, + estimateMs: { boot: 2_000, provision: 1_000 }, + platform: "ios", + }); + const device = await registry.registerDevice({ + driverData: {}, + driverDeviceId: "simlock-stuck", + provisionDuration: 0, + spec: { model: "Phone", osVersion: "1", platform: "ios" }, + }); + const stalled = (now: number) => + isStalledTransition({ + claims: new DeviceOperationClaims(), + config: config().stalledTransition, + device, + driver, + now, + }); + + // threshold = (provision 1_000 + boot 2_000) * thresholdMultiplier 3 = 9_000 + expect(stalled(10_000 + 9_000)).toBe(false); + expect(stalled(10_000 + 9_001)).toBe(true); + // No driver for the platform: nothing to measure against, so no stall. + expect( + isStalledTransition({ + claims: undefined, + config: config().stalledTransition, + device, + driver: undefined, + now: 10_000 + 9_001, + }), + ).toBe(false); + }); + + it("isStalledTransition does not hold for a device with a live operation claim", async () => { + const clock = new FakeClock(10_000); + const registry = await loadRegistry(clock, new EventBus(clock)); + const driver = new FakeDriver({ clock, estimateMs: { reclaim: 2_000 }, platform: "ios" }); + const device = await readyDevice(registry, "simlock-erasing", "ios"); + const lease = await registry.createLease({ + deviceId: device.id, + requesterId: "agent", + ownerId: "agent", + ttlMs: 60_000, + ttlDeadline: 999_999, + }); + await registry.beginRelease(lease.id); + const reclaiming = registry.snapshot.devices.find((entry) => entry.id === device.id); + expect(reclaiming?.state).toBe("reclaiming"); + const claims = new DeviceOperationClaims(); + const claim = claims.tryClaim(device.id, "reclaim"); + const stalled = () => + isStalledTransition({ + claims, + config: config().stalledTransition, + device: reclaiming ?? device, + driver, + // Far past the reclaim threshold (2_000 * 3). + now: clock.now() + 600_000, + }); + + expect(stalled()).toBe(false); + // The same device, the same age, is a stall once no live operation accounts for it. + claim?.release(); + expect(stalled()).toBe(true); + }); + + it("the doctor's stalled-transition finding is unchanged", async () => { + // The finding a stalled provisioning device and a stalled reclaiming device produced + // before the stall test became `isStalledTransition`, field for field, and none a moment + // before each threshold. + const clock = new FakeClock(10_000); + const eventBus = new EventBus(clock); + const registry = await loadRegistry(clock, eventBus); + const driver = new FakeDriver({ + clock, + estimateMs: { boot: 2_000, provision: 1_000, reclaim: 4_000 }, + platform: "ios", + }); + const provisioning = await registry.registerDevice({ + driverData: {}, + driverDeviceId: "simlock-stuck", + provisionDuration: 0, + spec: { model: "Phone", osVersion: "1", platform: "ios" }, + }); + const leased = await readyDevice(registry, "simlock-erasing", "ios"); + const lease = await registry.createLease({ + deviceId: leased.id, + requesterId: "agent", + ownerId: "agent", + ttlMs: 60_000, + ttlDeadline: 999_999, + }); + await registry.beginRelease(lease.id); + const doctor = new Doctor({ clock, config: config(), drivers: [driver], eventBus, registry }); + const stalls = async () => + (await doctor.reconcile()).findings.filter( + (finding) => finding.kind === "stalled-transition", + ); + + // Provisioning threshold: (1_000 + 2_000) * 3 = 9_000. Reclaim: 4_000 * 3 = 12_000. + clock.advance(9_000); + expect(await stalls()).toEqual([]); + clock.advance(1); + expect(await stalls()).toEqual([ + { + ageMs: 9_001, + deviceId: provisioning.id, + enteredAt: 10_000, + kind: "stalled-transition", + platform: "ios", + state: "provisioning", + thresholdMs: 9_000, + }, + ]); + clock.advance(3_000); + expect(await stalls()).toEqual([ + expect.objectContaining({ deviceId: provisioning.id }), + { + ageMs: 12_001, + deviceId: leased.id, + enteredAt: 10_000, + kind: "stalled-transition", + platform: "ios", + state: "reclaiming", + thresholdMs: 12_000, + }, + ]); + }); + it("reports a stalled-transition finding for a provisioning device past its driver-derived threshold", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); diff --git a/src/core/doctor.ts b/src/core/doctor.ts index ecdfd4003..52608501d 100644 --- a/src/core/doctor.ts +++ b/src/core/doctor.ts @@ -793,7 +793,7 @@ function liveDriftFindings( * healthy reclaim into a false stall finding, while one that is too loose only delays a real * one. So this takes the slower branch rather than assuming. */ -function slowestReclaimEstimateMs(driver: Driver, spec: DeviceSpec): number { +function slowestReclaimEstimateMs(driver: Pick, spec: DeviceSpec): number { return Math.max( driver.estimate({ clean: "standard", operation: "reclaim" }, spec), driver.estimate({ clean: "full", operation: "reclaim" }, spec), @@ -810,11 +810,12 @@ function slowestReclaimEstimateMs(driver: Driver, spec: DeviceSpec): number { * registered record remains for reconcile when the driver cannot destroy it"). * * The threshold is `driver.estimate(...) * thresholdMultiplier`, floored at - * `minimumThresholdMs`: not `estimate` itself, because the estimate is tuned for a - * routine run and real-world variance (a cold Android boot, a loaded host) can - * legitimately run well past it without anything having stalled. No driver for the - * device's platform, or no recorded entry time (defensive; see `transitionEnteredAt`), - * means there is nothing to compare against, so no finding rather than a guess. + * `minimumThresholdMs` (see `stallThresholdMs`): not `estimate` itself, because the + * estimate is tuned for a routine run and real-world variance (a cold Android boot, a + * loaded host) can legitimately run well past it without anything having stalled. No + * driver for the device's platform, or no recorded entry time (defensive; see + * `transitionEnteredAt`), means there is nothing to compare against, so no stall rather + * than a guess. * * A device this daemon holds an operation claim on is excluded outright, before any * of that arithmetic: the claim *is* the statement that work is in progress, so a @@ -826,47 +827,82 @@ function slowestReclaimEstimateMs(driver: Driver, spec: DeviceSpec): number { * and contend for the same disk. The estimate the threshold is built from now reflects * that erase rather than the 1s it used to claim (#56), but tuning a threshold against * contended disk speed would still be guessing; the claim answers it exactly. A reclaim - * orphaned by a crash has no claim in the new process, so the case this finding exists to + * orphaned by a crash has no claim in the new process, so the case this test exists to * catch is untouched. + * + * The one place the stall rule lives (architecture rule 10): `doctor`'s + * `stalled-transition` finding and the `stalled` flag `status.get` and `list.get` put on a + * device both ask it. */ -function stalledTransitionFinding( - device: DeviceRecord, - driversByPlatform: ReadonlyMap, - config: Config["stalledTransition"], - now: number, - claims?: Pick, -): DoctorFinding | undefined { +export function isStalledTransition(input: StallInput): boolean { + const { claims, config, device, driver, now } = input; if (device.state !== "provisioning" && device.state !== "reclaiming") { - return undefined; + return false; } if (claims?.isClaimed(device.id) === true) { - return undefined; + return false; } const enteredAt = transitionEnteredAt(device); - const driver = driversByPlatform.get(device.spec.platform); if (enteredAt === undefined || driver === undefined) { - return undefined; + return false; } + return now - enteredAt > stallThresholdMs(device, driver, config); +} + +/** What `isStalledTransition` reads: one device, the driver for its platform (absent when that + * platform has none), the `stalledTransition` config, the operation claims and the time. */ +export interface StallInput { + readonly device: DeviceRecord; + readonly driver: Pick | undefined; + readonly config: Config["stalledTransition"]; + readonly claims: Pick | undefined; + readonly now: number; +} +/** How long `device` may stay in its transition before it is a stall. */ +function stallThresholdMs( + device: DeviceRecord, + driver: Pick, + config: Config["stalledTransition"], +): number { const estimateMs = device.state === "provisioning" ? driver.estimate({ operation: "provision" }, device.spec) + driver.estimate({ operation: "boot" }, device.spec) : slowestReclaimEstimateMs(driver, device.spec); - const thresholdMs = Math.max(estimateMs * config.thresholdMultiplier, config.minimumThresholdMs); - const ageMs = now - enteredAt; - if (ageMs <= thresholdMs) { + return Math.max(estimateMs * config.thresholdMultiplier, config.minimumThresholdMs); +} + +/** The `stalled-transition` finding for a device `isStalledTransition` holds for. */ +function stalledTransitionFinding( + device: DeviceRecord, + driversByPlatform: ReadonlyMap, + config: Config["stalledTransition"], + now: number, + claims?: Pick, +): DoctorFinding | undefined { + const driver = driversByPlatform.get(device.spec.platform); + if (!isStalledTransition({ claims, config, device, driver, now })) { + return undefined; + } + // Narrowing only: `isStalledTransition` holds just for a device in one of these two states, + // with an entry time and a driver. + const enteredAt = transitionEnteredAt(device); + if ( + driver === undefined || + enteredAt === undefined || + (device.state !== "provisioning" && device.state !== "reclaiming") + ) { return undefined; } - return { - ageMs, + ageMs: now - enteredAt, deviceId: device.id, enteredAt, kind: "stalled-transition", platform: device.spec.platform, state: device.state, - thresholdMs, + thresholdMs: stallThresholdMs(device, driver, config), }; } diff --git a/src/core/index.ts b/src/core/index.ts index ce5eea98a..e35e9e131 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -64,7 +64,7 @@ export { export { DriverCatalog, UnknownPassthroughToolError } from "./driver-catalog.js"; // fallow-ignore-next-line unused-type -- wire-visible rejection vocabulary for Simlock's own adb server. export type { AdbServerRejectionReason, DriverRejectionReason } from "./driver.js"; -export { Doctor } from "./doctor.js"; +export { Doctor, isStalledTransition, type StallInput } from "./doctor.js"; export { type HostFacts, HostFactsReader } from "./host-facts.js"; export { ensureOwnedRoot, OWNED_ROOT_MARKER_FILE, OwnedRootError } from "./device-root.js"; export type { EnsureOwnedRootOptions } from "./device-root.js"; diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 6e930cb06..efcf17f8b 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -283,6 +283,7 @@ async function buildDispatcher( queue: engine, reaper, registry, + stalls: { claims: engine.claimReader, drivers: [driver] }, tokens, version: "1.2.3", }); @@ -1135,6 +1136,44 @@ describe("Dispatcher: device mode on every surface", () => { ); }); + it("status marks a stalled device with stalled: true and leaves others without it", async () => { + const { clock, dispatcher, registry } = await buildDispatcher(); + const leased = await dispatcher.dispatch("lease.request", request, session()); + const register = (driverDeviceId: string) => + registry.registerDevice({ + driverData: {}, + driverDeviceId, + provisionDuration: 0, + spec: { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + }); + const stuck = await register("driver-stuck"); + // The fake driver estimates 0, so the threshold is the 60 s floor. The stuck device is past + // it; the fresh one, provisioning too, is not. + clock.advance(60_001); + const fresh = await register("driver-fresh"); + + const status = await dispatcher.dispatch("status.get", {}, session()); + const list = (await dispatcher.dispatch( + "list.get", + { kind: "devices" }, + session({ role: "admin" }), + )) as { id: string; stalled?: boolean }[]; + const { workers } = await dispatcher.dispatch( + "worker.list", + {}, + session({ principal: "operator", role: "admin" }), + ); + + for (const devices of [status.devices, list, workers[0]?.devices ?? []]) { + const byId = new Map(devices.map((device) => [device.id, device])); + expect(byId.get(stuck.id)?.stalled).toBe(true); + expect(byId.get(fresh.id)).toBeDefined(); + expect(byId.get(fresh.id)).not.toHaveProperty("stalled"); + expect(byId.get(leased.device.id)).toBeDefined(); + expect(byId.get(leased.device.id)).not.toHaveProperty("stalled"); + } + }); + it("no lease.request, list.get, or status.get response carries featureProfile or slim", async () => { const { dispatcher } = await buildDispatcher({ driverOptions: { mode: "slim" } }); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index f8c0351bf..951d1c427 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -10,9 +10,12 @@ import { type DeviceRecord, type DeviceRequest, type Doctor, + type Driver, type HostFacts, + isStalledTransition, type Nuke, type Registry, + type StallInput, effectiveAllowDownload, RuntimeMissingError, transitionEnteredAt, @@ -129,6 +132,17 @@ export interface DispatcherOptions { readonly queue: QueueControl; readonly reaper: CleanupReaper; readonly registry: Registry; + /** + * What the `stalled` flag `status.get` and `list.get` put on a device is worked out from + * (`isStalledTransition`, with `config.stalledTransition` and the clock): the drivers this + * daemon runs, and its device operation claims, so a live operation is never read as a + * stall. Optional so the tests that never stall a device need not fabricate either; absent, + * no device is flagged. + */ + readonly stalls?: { + readonly drivers: readonly Pick[]; + readonly claims: NonNullable; + }; /** * ADR 0003 §11: "token create|list|revoke become daemon operations. The daemon is the only * owner of tokens.json." Optional so tests that don't exercise `token.*` (the overwhelming @@ -804,11 +818,34 @@ export class Dispatcher { return this.options.tokens; } - /** Moved verbatim from `DaemonServer`; see its former comment there. */ - #decorateDevice(device: DeviceRecord): DeviceRecord & { readonly transitionAgeMs?: number } { + /** + * A device as `status.get` and `list.get` report it: with `transitionAgeMs` while it is + * mid-transition, and `stalled: true` once that transition is a stall by the rule `doctor` + * reports (`isStalledTransition`). A device that is not stalled carries no `stalled` at all. + */ + #decorateDevice( + device: DeviceRecord, + ): DeviceRecord & { readonly transitionAgeMs?: number; readonly stalled?: true } { const enteredAt = transitionEnteredAt(device); if (enteredAt === undefined) return device; - return { ...device, transitionAgeMs: this.options.clock.now() - enteredAt }; + const now = this.options.clock.now(); + return { + ...device, + transitionAgeMs: now - enteredAt, + ...(this.#isStalled(device, now) ? { stalled: true as const } : {}), + }; + } + + #isStalled(device: DeviceRecord, now: number): boolean { + const stalls = this.options.stalls; + if (stalls === undefined) return false; + return isStalledTransition({ + claims: stalls.claims, + config: this.options.config.stalledTransition, + device, + driver: stalls.drivers.find((driver) => driver.platform === device.spec.platform), + now, + }); } } diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 81a8fbd9c..14a9af4f8 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -392,6 +392,10 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise { await harness.service.stop(); }); + it("a gateway's worker view carries a worker device's stalled flag", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.devices = [ + { + ...deviceFixture("dev_stuck"), + state: "provisioning" as const, + createdAt: 1, + driverData: {}, + stalled: true, + transitionAgeMs: 120_000, + }, + { ...deviceFixture("dev_ready", "ready"), createdAt: 1, driverData: {} }, + ]; + + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.devices).toHaveLength(2)); + + const [stuck, ready] = harness.service.workers.view("wrk_1")?.devices ?? []; + expect(stuck).toMatchObject({ id: "dev_stuck", stalled: true }); + expect(ready?.id).toBe("dev_ready"); + expect(ready).not.toHaveProperty("stalled"); + + await harness.service.stop(); + }); + it("republishes a worker's events with its workerId, into its own ring buffer", async () => { const harness = fleet(); await harness.service.start(); diff --git a/ui/src/shell.tsx b/ui/src/shell.tsx index f337de690..709ecff8d 100644 --- a/ui/src/shell.tsx +++ b/ui/src/shell.tsx @@ -48,6 +48,12 @@ export function Shell() {
  • {entry.label} + {entry.Badge === undefined ? null : ( + <> + {" "} + + + )}
  • ))} diff --git a/ui/src/styles.css b/ui/src/styles.css index 873f4c5ba..99ccbad3a 100644 --- a/ui/src/styles.css +++ b/ui/src/styles.css @@ -322,6 +322,26 @@ input[aria-invalid="true"] { color: var(--text); } +/* A count beside a view's name, such as how many items need attention. A number, not a status: + no status colour, and never the accent. */ +.nav-count { + margin-left: var(--space-1); + padding: 0 var(--space-1); + border: 1px solid var(--border); + color: var(--text); + font-family: var(--font-mono); + font-size: var(--text-xs); +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + .main { grid-area: main; min-width: 0; @@ -398,6 +418,35 @@ input[aria-invalid="true"] { gap: var(--space-1) var(--space-4); } +/* The attention list: one line per item, its status first. */ + +.attention-list { + margin: 0; + padding: 0; + list-style: none; + border-top: 1px solid var(--border); +} + +.attention-list li { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: var(--space-1) var(--space-4); + padding: var(--space-3) 0; + border-bottom: 1px solid var(--border); + overflow-wrap: anywhere; +} + +.attention-list .status { + flex: none; + min-width: 10rem; +} + +.attention-list .status + span { + flex: 1 1 16rem; + min-width: 0; +} + /* Cards: one per worker. */ .cards { diff --git a/ui/src/views/attention-model.ts b/ui/src/views/attention-model.ts new file mode 100644 index 000000000..c0effee0b --- /dev/null +++ b/ui/src/views/attention-model.ts @@ -0,0 +1,69 @@ +/** + * What needs the operator's attention, worked out from `GET /v1/workers` (ADR 0013 §1) and + * nothing else. Pure, so the Attention view and the count in the shell read one list, and an + * item leaves it the moment the data no longer says it. + */ +import type { WorkerDevice, WorkerView } from "./workers-model"; + +/** One thing that needs attention. `condition` is the word the console shows for it. */ +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; + }; + +/** + * Every item, worker by worker in the order the daemon lists them: the worker's own conditions + * first, then its devices'. 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 []; + }); +} diff --git a/ui/src/views/attention.test.tsx b/ui/src/views/attention.test.tsx new file mode 100644 index 000000000..985cc65b4 --- /dev/null +++ b/ui/src/views/attention.test.tsx @@ -0,0 +1,177 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; + +import { AttentionList } from "./attention"; +import { attentionItems } from "./attention-model"; +import type { WorkerDevice, WorkerView } from "./workers-model"; + +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 { + id, + mode: "full", + spec: { model: "iPhone 16", osVersion: "18.4", platform: "ios" }, + state: "ready", + ...overrides, + }; +} + +function capacity(ramBudget?: { usedBytes: number; limitBytes: number; overLimit: boolean }) { + const entry = { 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 }), + }; +} + +/** Each item as ` `, the facts a test compares. */ +function summary(workers: readonly WorkerView[]): string[] { + return attentionItems(workers).map((item) => + [item.worker.id, "device" in item ? item.device.id : "-", item.condition].join(" "), + ); +} + +/** The text a screen shows, without markup. */ +function text(html: string): string { + return html + .replace(/<[^>]+>/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +describe("the attention list", () => { + it("the attention list holds a disconnected, an incompatible and a drained worker", () => { + const workers = [ + worker({ id: "wrk_ok" }), + worker({ connection: "disconnected", id: "wrk_gone" }), + worker({ connection: "incompatible", id: "wrk_old" }), + worker({ drained: true, id: "wrk_drained" }), + // Both at once are two items: each clears on its own. + 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("the attention list holds a quarantined device and a stalled device", () => { + const workers = [ + worker({ + devices: [ + device("dev_ready"), + device("dev_quarantined", { state: "quarantined" }), + device("dev_stuck", { stalled: true, state: "reclaiming", transitionAgeMs: 300_000 }), + // Mid-transition but not stalled: in progress, not a problem. + device("dev_busy", { state: "provisioning", transitionAgeMs: 2_000 }), + ], + }), + ]; + + expect(summary(workers)).toEqual([ + "wrk_1 dev_quarantined quarantined", + "wrk_1 dev_stuck stalled", + ]); + }); + + it("the attention list holds a worker over its RAM 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", + }), + // No RAM budget kept, or capacity never read: nothing to be over. + worker({ capacity: capacity(), id: "wrk_none" }), + worker({ id: "wrk_unread" }), + ]; + + expect(summary(workers)).toEqual(["wrk_over - over RAM budget"]); + const shown = text( + renderToStaticMarkup(), + ); + expect(shown).toBe("over RAM budget wrk_over : 13.00 GiB of 12.00 GiB used."); + }); + + it("an item leaves the attention list 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 over = capacity({ ...ramBudget, overLimit: true }); + const before = worker({ + capacity: over, + 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); + } + }); + + it("each item names its worker and links to its page", () => { + const workers = [ + worker({ connection: "disconnected", id: "wrk/1", label: "mac-mini-1" }), + worker({ + devices: [ + device("dev_stuck", { stalled: true, state: "provisioning", transitionAgeMs: 90_000 }), + ], + id: "wrk_2", + lastSeenAt: NOW - 10_000, + }), + ]; + + const html = renderToStaticMarkup(); + + expect(html).toContain('mac-mini-1'); + expect(html).toContain('wrk_2'); + expect(text(html)).toContain( + "disconnected mac-mini-1 : the gateway has lost its connection to this worker.", + ); + // 90 s in when the worker answered, 10 s ago. + expect(text(html)).toContain( + "stalled Device dev_stuck on wrk_2 : stuck provisioning for 1 min 40 s.", + ); + }); + + it("says so when nothing needs attention", () => { + const html = renderToStaticMarkup(); + + expect(text(html)).toBe("Nothing needs attention."); + }); +}); diff --git a/ui/src/views/attention.tsx b/ui/src/views/attention.tsx new file mode 100644 index 000000000..14387f24f --- /dev/null +++ b/ui/src/views/attention.tsx @@ -0,0 +1,121 @@ +import type { ReactNode } from "react"; + +import { useLiveResource, useNow } from "../live/live-context"; +import { Loaded } from "../live/route-state"; +import { formatDuration } from "../live/time"; +import { Link } from "../router"; +import { Status, type Tone } from "../status"; +import { type AttentionItem, attentionItems } from "./attention-model"; +import { + stateEnteredAt, + type WorkerList, + type WorkerView, + workerName, + workerPath, +} from "./workers-model"; + +/** + * Everything that needs the operator's attention, in one list, fed by `GET /v1/workers` + * (ADR 0013 §1) like the workers views. An item shows within a second of the daemon reporting + * it and leaves when the daemon stops reporting it. + */ +export function AttentionView() { + const state = useLiveResource("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/v1/workers"); + const now = useNow(); + return ( +
    +

    Attention

    + + {(list) => } + +
    + ); +} + +/** + * How many items need attention, beside the view's name in the navigation, on every page. + * Nothing while there are none, or before the first answer. + */ +export function AttentionCount() { + const { data } = useLiveResource("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/v1/workers"); + if (data === undefined) return null; + const count = attentionItems(data.workers).length; + if (count === 0) return null; + return ( + + {count} + {count === 1 ? " item" : " items"} + + ); +} + +export function AttentionList(props: { + readonly items: readonly AttentionItem[]; + /** The daemon's time now, for how long a device has been stalled. */ + readonly now: number; +}) { + const { items, now } = props; + if (items.length === 0) return

    Nothing needs attention.

    ; + return ( +
      + {items.map((item) => ( +
    • + {item.condition} + + : {describe(item, now)} + +
    • + ))} +
    + ); +} + +const TONES: Readonly> = { + disconnected: "error", + drained: "warn", + incompatible: "error", + "over RAM budget": "warn", + quarantined: "error", + stalled: "warn", +}; + +/** The worker the item is about, as a link to its page, and the device when it is a device. */ +function Subject({ item }: { readonly item: AttentionItem }) { + const worker = ; + if (!("device" in item)) return worker; + return ( + <> + Device {item.device.id} on {worker} + + ); +} + +function WorkerLink({ worker }: { readonly worker: WorkerView }) { + return {workerName(worker)}; +} + +function describe(item: AttentionItem, now: number): ReactNode { + switch (item.condition) { + case "disconnected": + return "the gateway has lost its connection to this worker."; + case "incompatible": + return "this worker and the gateway have no protocol version in common."; + case "drained": + return "this worker gets no new leases."; + case "over RAM budget": + return `${gibibytes(item.usedBytes)} of ${gibibytes(item.limitBytes)} used.`; + case "quarantined": + return "Simlock is retrying its cleanup, and leases it to no one meanwhile."; + case "stalled": { + const since = stateEnteredAt(item.device, item.worker); + return since === undefined + ? `stuck ${item.device.state}.` + : `stuck ${item.device.state} for ${formatDuration(now - since)}.`; + } + } +} + +/** Bytes as `simlock status` writes its RAM budget: GiB with two decimals. */ +function gibibytes(bytes: number): string { + return `${(bytes / 1024 ** 3).toFixed(2)} GiB`; +} diff --git a/ui/src/views/index.tsx b/ui/src/views/index.tsx index 1f12dc56c..67fb6cf91 100644 --- a/ui/src/views/index.tsx +++ b/ui/src/views/index.tsx @@ -1,5 +1,6 @@ import type { ComponentType } from "react"; +import { AttentionCount, AttentionView } from "./attention"; import { ComingSoon } from "./coming-soon"; import { WaitingView } from "./waiting"; import { WorkersView } from "./workers"; @@ -14,13 +15,15 @@ export interface View { readonly path: `/${string}`; readonly label: string; readonly Component: ComponentType; + /** Shown beside `label` in the nav on every page, such as how many items need attention. */ + readonly Badge?: ComponentType; } export const VIEWS: readonly View[] = [ { path: "/workers", label: "Workers", Component: WorkersView }, { path: "/leases", label: "Leases", Component: () => }, { path: "/waiting", label: "Waiting", Component: WaitingView }, - { path: "/attention", label: "Attention", Component: () => }, + { path: "/attention", label: "Attention", Component: AttentionView, Badge: AttentionCount }, { path: "/events", label: "Events", Component: () => }, ]; From 3de2479eaec506f90aa5bcfd7de815548eb3e352 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 23:00:47 +0200 Subject: [PATCH 2/3] fix(ui,daemon,docs): answer the first round of review findings --- docs/CONSOLE.md | 5 ++++- e2e/console/attention.spec.ts | 15 ++++++++++--- src/daemon/dispatcher.test.ts | 37 ++++++++++++++++++++++++++++++++- ui/src/views/attention.test.tsx | 20 ++++++++++++++++++ 4 files changed, 72 insertions(+), 5 deletions(-) diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index 853c99351..9bc7f5a91 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -151,7 +151,10 @@ cancelled. **Attention** lists everything that needs you, in one place. Each item names its worker and links to that worker's page. An item leaves the list as soon as -its condition clears. The console only shows these; it does not fix them. +the daemon reports that its condition cleared. A gateway keeps a disconnected +worker's devices and RAM use as the worker last reported them, so their items +stay until the worker reconnects or is removed. The console only shows these; +it does not fix them. | Item | What it means | | --- | --- | diff --git a/e2e/console/attention.spec.ts b/e2e/console/attention.spec.ts index 29b07655e..c9f39545e 100644 --- a/e2e/console/attention.spec.ts +++ b/e2e/console/attention.spec.ts @@ -20,7 +20,12 @@ interface WorkerView { readonly connection: string; readonly drained: boolean; readonly capacity?: { readonly ramBudget?: { readonly overLimit: boolean } }; - readonly devices: readonly { readonly id: string; readonly state: string; stalled?: boolean }[]; + readonly devices: readonly { + readonly id: string; + readonly state: string; + readonly stalled?: boolean; + readonly transitionAgeMs?: number; + }[]; } const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; @@ -299,11 +304,15 @@ test.describe("the attention view", () => { return ( view?.capacity?.ramBudget?.overLimit === true && view.devices.some((device) => device.state === "quarantined") && - view.devices.some((device) => device.stalled === true) + view.devices.some( + (device) => device.state === "provisioning" && (device.transitionAgeMs ?? 0) > 1_000, + ) ); }); const quarantined = view?.devices.find((device) => device.state === "quarantined"); - const stalled = view?.devices.find((device) => device.stalled === true); + const stalled = view?.devices.find((device) => device.state === "provisioning"); + // 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); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index efcf17f8b..1b8ea5b22 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -69,6 +69,15 @@ function resolvePassthroughOverride( return override ?? engine; } +/** The claims the stall test reads: a test's own, or the engine's. Pulled out of + * `buildDispatcher` for the same reason as `resolvePassthroughOverride`. */ +function resolveClaimsOverride( + engine: LeaseEngine, + override: { isClaimed(deviceId: string): boolean } | undefined, +): { isClaimed(deviceId: string): boolean } { + return override ?? engine.claimReader; +} + function resolveEventHistoryOverride( eventBus: EventBus, filesystem: MemoryFilesystem, @@ -185,6 +194,8 @@ async function buildDispatcher( readonly gatewayLabel?: string; /** The `http` block; disabled by default. */ readonly http?: Config["http"]; + /** Stands in for the engine's operation claims in the stall test, so a test can hold one. */ + readonly claims?: { isClaimed(deviceId: string): boolean }; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -283,7 +294,7 @@ async function buildDispatcher( queue: engine, reaper, registry, - stalls: { claims: engine.claimReader, drivers: [driver] }, + stalls: { claims: resolveClaimsOverride(engine, overrides.claims), drivers: [driver] }, tokens, version: "1.2.3", }); @@ -1174,6 +1185,30 @@ describe("Dispatcher: device mode on every surface", () => { } }); + it("status leaves stalled off a device past its threshold that a live operation holds", async () => { + // The same rule as `doctor`: a claim says work is in progress, however long it takes. + const claimed = new Set(); + const { clock, dispatcher, registry } = await buildDispatcher({ + claims: { isClaimed: (deviceId) => claimed.has(deviceId) }, + }); + const device = await registry.registerDevice({ + driverData: {}, + driverDeviceId: "driver-booting", + provisionDuration: 0, + spec: { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + }); + clock.advance(60_001); + const stalled = async () => + (await dispatcher.dispatch("status.get", {}, session())).devices.find( + (entry) => entry.id === device.id, + )?.stalled; + + claimed.add(device.id); + expect(await stalled()).toBeUndefined(); + claimed.delete(device.id); + expect(await stalled()).toBe(true); + }); + it("no lease.request, list.get, or status.get response carries featureProfile or slim", async () => { const { dispatcher } = await buildDispatcher({ driverOptions: { mode: "slim" } }); diff --git a/ui/src/views/attention.test.tsx b/ui/src/views/attention.test.tsx index 985cc65b4..15c6cf53c 100644 --- a/ui/src/views/attention.test.tsx +++ b/ui/src/views/attention.test.tsx @@ -169,6 +169,26 @@ describe("the attention list", () => { ); }); + it("a stalled device on a disconnected worker shows no time in its state", () => { + // A gateway keeps a disconnected worker's devices as last reported, with an age it can no + // longer count from. + const workers = [ + worker({ + connection: "disconnected", + devices: [ + device("dev_stuck", { stalled: true, state: "reclaiming", transitionAgeMs: 90_000 }), + ], + lastSeenAt: NOW - 10_000, + }), + ]; + + const shown = text( + renderToStaticMarkup(), + ); + + expect(shown).toContain("stalled Device dev_stuck on wrk_1 : stuck reclaiming."); + }); + it("says so when nothing needs attention", () => { const html = renderToStaticMarkup(); From 06159a017556abda2263dfceec05bc443b0b3194 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 23:12:59 +0200 Subject: [PATCH 3/3] fix(ui,core,daemon): answer the second round of review findings --- e2e/console/attention.spec.ts | 2 +- src/core/doctor.ts | 6 ++--- src/daemon/dispatcher.test.ts | 45 +++++++++++++++++++++++++++++------ 3 files changed, 42 insertions(+), 11 deletions(-) diff --git a/e2e/console/attention.spec.ts b/e2e/console/attention.spec.ts index c9f39545e..8a88af022 100644 --- a/e2e/console/attention.spec.ts +++ b/e2e/console/attention.spec.ts @@ -368,7 +368,7 @@ test.describe("the attention view", () => { try { hangUp = await joinOldWorker(gateway, { id: "wrk_with_a_long_id_that_does_not_fit_on_a_phone_0123456789", - label: "a-worker-with-a-label-far-too-long-for-one-line-on-a-phone", + label: "aworkerwithalabelfartoolongforonelineonaphonewithnohyphensinit", }); await untilTheDaemonSays(gateway, (views) => views.length === 1); await page.setViewportSize({ height: 740, width: 360 }); diff --git a/src/core/doctor.ts b/src/core/doctor.ts index 52608501d..a641fc4d8 100644 --- a/src/core/doctor.ts +++ b/src/core/doctor.ts @@ -134,7 +134,7 @@ export interface DoctorOptions { /** * Read-only view of the per-device operation claims. A device this daemon holds a * claim on is work in progress by definition, which is what keeps a healthy - * backgrounded reclaim from being read as a stall -- see `stalledTransitionFinding`. + * backgrounded reclaim from being read as a stall -- see `isStalledTransition`. */ readonly claims?: Pick; /** @@ -718,7 +718,7 @@ function registryDriftFindings( // including erasing it, so neither run state nor marks are compared. // // A device this daemon holds an operation claim on is excluded the same way, the same - // live-versus-orphaned test `stalledTransitionFinding` already applies (see its comment). A + // live-versus-orphaned test `isStalledTransition` already applies (see its comment). A // lease-path boot from `shutdown` runs `makeReady` while the committed record still says // `shutdown` -- observed reality goes `running` before the transition that would update // `expectedRunState` ever commits. Without this guard a concurrent `doctor --fix` reads that @@ -726,7 +726,7 @@ function registryDriftFindings( // afterwards finds the record changed underneath it and silently drops its // `address`/`driverData`/`mode`, dropping the waiter. The claim is held for the // whole boot, so it exactly brackets the window this needs to cover -- unlike - // `stalledTransitionFinding`, this applies regardless of `device.state`, since the record can + // `isStalledTransition`, this applies regardless of `device.state`, since the record can // be `shutdown`, `ready`, or `leased` while a claimed operation is in flight against it. const expected = expectedRunState(device.state); const observed = observedDevices.get(deviceKey); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 1b8ea5b22..e88122e1b 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -69,13 +69,21 @@ function resolvePassthroughOverride( return override ?? engine; } -/** The claims the stall test reads: a test's own, or the engine's. Pulled out of - * `buildDispatcher` for the same reason as `resolvePassthroughOverride`. */ -function resolveClaimsOverride( +/** What the stall test reads: a test's own claims or the engine's, and this driver after any + * other platforms' a test lists. Pulled out of `buildDispatcher` for the same reason as + * `resolvePassthroughOverride`. */ +function stallOptions( engine: LeaseEngine, - override: { isClaimed(deviceId: string): boolean } | undefined, -): { isClaimed(deviceId: string): boolean } { - return override ?? engine.claimReader; + driver: FakeDriver, + overrides: { + readonly claims?: { isClaimed(deviceId: string): boolean }; + readonly otherStallDrivers?: readonly FakeDriver[]; + }, +) { + return { + claims: overrides.claims ?? engine.claimReader, + drivers: [...(overrides.otherStallDrivers ?? []), driver], + }; } function resolveEventHistoryOverride( @@ -196,6 +204,8 @@ async function buildDispatcher( readonly http?: Config["http"]; /** Stands in for the engine's operation claims in the stall test, so a test can hold one. */ readonly claims?: { isClaimed(deviceId: string): boolean }; + /** Other platforms' drivers, listed before this one's in the stall test's driver list. */ + readonly otherStallDrivers?: readonly FakeDriver[]; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -294,7 +304,7 @@ async function buildDispatcher( queue: engine, reaper, registry, - stalls: { claims: resolveClaimsOverride(engine, overrides.claims), drivers: [driver] }, + stalls: stallOptions(engine, driver, overrides), tokens, version: "1.2.3", }); @@ -1209,6 +1219,27 @@ describe("Dispatcher: device mode on every surface", () => { expect(await stalled()).toBe(true); }); + it("status measures a stall against the driver for the device's own platform", async () => { + // Android's estimate puts its threshold at 30 min; the iOS fake's 0 leaves the 60 s floor. + const android = new FakeDriver({ + clock: new FakeClock(1_000), + estimateMs: { boot: 300_000, provision: 300_000 }, + platform: "android", + }); + const { clock, dispatcher, registry } = await buildDispatcher({ otherStallDrivers: [android] }); + const device = await registry.registerDevice({ + driverData: {}, + driverDeviceId: "driver-ios-stuck", + provisionDuration: 0, + spec: { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + }); + clock.advance(60_001); + + const status = await dispatcher.dispatch("status.get", {}, session()); + + expect(status.devices.find((entry) => entry.id === device.id)?.stalled).toBe(true); + }); + it("no lease.request, list.get, or status.get response carries featureProfile or slim", async () => { const { dispatcher } = await buildDispatcher({ driverOptions: { mode: "slim" } });