From 3a441c64fa5e6885bed2c82fa6c96e9042def506 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 22:40:39 +0200 Subject: [PATCH 1/4] feat(contract,core,gateway,http,cli,ui,docs): the waiting requests view and simlock list --requests --- docs/CLI.md | 33 +++- docs/CONSOLE.md | 30 +++- docs/HTTP-API.md | 69 +++++++-- e2e/console/waiting.spec.ts | 232 ++++++++++++++++++++++++++++ e2e/waiting-requests.test.ts | 103 ++++++++++++ src/cli/index.ts | 50 +++++- src/contract/operations.ts | 15 +- src/contract/schemas.ts | 39 ++++- src/contract/worker-view.ts | 5 +- src/core/lease-engine.ts | 8 +- src/core/lease-ports.ts | 3 + src/core/lease-request-book.ts | 49 ++++++ src/core/wait-queue.ts | 21 +++ src/daemon/dispatcher.test.ts | 124 +++++++++++++++ src/daemon/dispatcher.ts | 3 + src/gateway/aggregate.ts | 3 + src/gateway/dispatcher.test.ts | 112 ++++++++++++++ src/gateway/dispatcher.ts | 28 +++- src/gateway/fleet-coordinator.ts | 8 + src/gateway/queue.ts | 6 + src/gateway/service.test.ts | 41 +++++ src/gateway/worker-registry.test.ts | 31 ++++ src/gateway/worker-registry.ts | 10 +- src/http/app.test.ts | 31 ++++ src/http/app.ts | 11 ++ ui/src/status.tsx | 3 + ui/src/views/index.tsx | 3 +- ui/src/views/waiting-model.ts | 45 ++++++ ui/src/views/waiting.test.tsx | 110 +++++++++++++ ui/src/views/waiting.tsx | 92 +++++++++++ 30 files changed, 1278 insertions(+), 40 deletions(-) create mode 100644 e2e/console/waiting.spec.ts create mode 100644 e2e/waiting-requests.test.ts create mode 100644 ui/src/views/waiting-model.ts create mode 100644 ui/src/views/waiting.test.tsx create mode 100644 ui/src/views/waiting.tsx diff --git a/docs/CLI.md b/docs/CLI.md index e82c6192f..bc3e93313 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -910,7 +910,11 @@ component installs waiting or running on that worker, whoever started them, in the shape [`simlock status`](#simlock-status) describes. It is re-read when an install on that worker starts, finishes or fails, and on every periodic refresh, so an install queued behind another may appear only then. -A disconnected or incompatible worker lists none. `catalog` is what that +A disconnected or incompatible worker lists none. `waiting` lists the +requests waiting in that worker's own queue, the same ones +[`simlock list --requests`](#simlock-list---devices--leases--rules--requests) +run on that worker prints. It is re-read on every lease event on that worker, +and a disconnected or incompatible worker lists none. `catalog` is what that worker can lease, each model with the runtimes it pairs with, and lists a newly installed component as soon as its install ends. `host` is the machine: operating system, its version, CPU architecture, and the version of @@ -1127,10 +1131,10 @@ depth, plus a `workers` array of worker views (the same records [`simlock worker list`](#simlock-worker-listdrainundrainremove) prints). See [Against a gateway](#against-a-gateway). -## `simlock list [--devices|--leases|--rules]` +## `simlock list [--devices|--leases|--rules|--requests]` Scriptable listings of managed devices, active leases, or registered cleanup -rules. Defaults to `--devices`. Against a gateway, `--devices` and `--leases` +rules, and the requests waiting for a device. Defaults to `--devices`. Against a gateway, `--devices` and `--leases` are the fleet's (each record naming its `workerId`) while `--rules` lists nothing at all: cleanup rules run where the devices and the reaper are, and a gateway has neither. Each lease record's `requesterId` is the @@ -1146,6 +1150,29 @@ a device's driver address or a driver's private data, and does not invent one. `--rules` lists nothing on a gateway — cleanup rules are a machine's own configuration, and a gateway runs no reaper. +`--requests` prints one line per request waiting for a device, oldest first, +rather than JSON: + +``` +Request req_7: agent-b, ios iPhone 16 18.4 mode slim, queued at 2, waiting 12s +Request req_9: local-agent on 2b026432-7743-4a08-98fc-ce494d11866f, ios iPhone 16, starting, waiting 3s +``` + +Each line names the request, the agent that sent it, the device it asked for +(only the fields it named), where it stands, and how long it has waited. +`queued at 2` is its place in the queue, counting from 1, the requests ahead +of it that are already starting included. `starting` means a device is being +found, created, booted or downloaded for it. With nothing waiting it prints +`No requests are waiting.` A granted, failed or cancelled request is not +listed. + +Against a gateway, `--requests` lists the gateway's own queue first, then +the requests waiting in each worker's own queue, from that worker's local +agents, with ` on `. A request the gateway has sent to a worker is +listed once, as the gateway's. A disconnected worker's requests are not +listed. A worker's request is stamped by that worker's clock, so if that +clock is off, its time waited is off by as much. + ## `simlock catalog [--platform ] [--json]` Lists what can actually be leased, so an agent can pick a valid `--device` diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index ff35979f0..c64876aa2 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), and the Workers pages. The other pages say "Coming -soon" until their views are built. +Attention and Events), the Workers pages and the Waiting page. The other +pages say "Coming soon" until their views are built. ## Turn it on @@ -125,14 +125,36 @@ Select a worker to open its page. It adds: A page the daemon cannot answer on a single host says "Not available on a single host" in place of its content. +## Waiting + +**Waiting** lists every request waiting for a device, oldest first, as +`simlock list --requests` does. Each shows: + +| Fact | What it says | +| --- | --- | +| Requester | The agent that asked | +| Device | The platform and model it asked for, and the runtime, mode and image tag when it named them | +| Worker | The worker whose own queue it waits in, or `—` for a request in a gateway's queue | +| Stage | `queued` while it waits its turn, `starting` while a device is being found, created, booted or downloaded for it | +| Place in queue | Where it stands, counting from 1, the requests ahead of it that are already starting included; `—` while starting | +| Waiting for | How long since the daemon received it | + +On a gateway the list has the gateway's own queue and, for each connected +worker, the requests its own agents sent to it directly. A request the +gateway has passed to a worker shows once, as the gateway's. On a single +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. + ## Live updates Every page keeps itself current. A change on the daemon, such as a lease being granted or a worker disconnecting, shows within about a second, with no reload. Durations count up every second on their own. They are measured by the clock of the daemon the console talks to, so a browser whose clock is -wrong still shows them right. On a gateway, a worker's lease and install times -come from that worker's clock: if it is far from the gateway's, its durations +wrong still shows them right. On a gateway, a worker's lease, install and +waiting times come from that worker's clock: if it is far from the gateway's, its durations are off by as much. A hidden tab stops asking the daemon for anything. When you come back to it, diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index d34a4f77c..1062d90e4 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -67,7 +67,7 @@ Three roles: | Role | Can | |---|---| | `agent` | catalog, status, installed components, its own lease requests and leases, `exec` on its own lease | -| `operator` | everything `agent` can, plus every other requester's leases/devices, the worker routes, event replay/stream, and releasing any lease | +| `operator` | everything `agent` can, plus every other requester's leases/devices, every waiting request, the worker routes, event replay/stream, and releasing any lease | | `worker` | open an uplink at [`/v1/uplink`](#get-v1uplink-websocket-upgrade), and nothing else | A valid token with the wrong role for a route is `403 FORBIDDEN`, not `401` — @@ -205,12 +205,18 @@ An install leaves the list as soon as it ends, whether it succeeded, failed or timed out. A worker always sends the field, empty when nothing is installing; an older daemon leaves it out. +**`waiting`** lists the requests waiting in this daemon's own queue for a +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. + 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 connected workers' installs (the 16 oldest across the fleet), the gateway -queue's depth — every lease, device and install carries the **`workerId`** it lives -on, and an additive **`workers`** array carries one +queue's depth and the requests waiting in it — every lease, device and install +carries the **`workerId`** it lives on, and an additive **`workers`** array +carries one [worker view](#worker-routes) per worker: ```json @@ -1035,6 +1041,12 @@ install queued behind another may appear only then. A worker that does not send one shows an empty list; a disconnected or incompatible worker shows none. +`waiting` is the worker's own `waiting` list from its +[`GET /v1/status`](#get-v1status): the requests waiting in that worker's +queue. It is re-read on every lease event on that worker. A worker that does +not send one shows an empty list; a disconnected or incompatible worker shows +none. + `catalog` is what that worker can lease, each model with the runtimes it pairs with, and lists a newly installed component as soon as its install ends. Its `customModels` are that worker's own, so this is where you see @@ -1094,7 +1106,7 @@ take the host out of rotation or forget it. ### Operator routes -Role: `operator` for all four. +Role: `operator` for all five. `DELETE /v1/leases/{id}` with an `operator` token already releases any single lease, on a gateway as anywhere else. The fleet-wide form of that — the CLI's @@ -1108,6 +1120,8 @@ could reach are still released — a partial result, said plainly, rather than 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/events?since=` — replay business events newer than @@ -1119,12 +1133,49 @@ an all-or-nothing that leaves the operator guessing. - `GET /v1/events/stream` — Server-Sent Events follow of the event bus (`simlock events --follow`). -On a **gateway** all four are fleet-wide, which is what makes a single +On a **gateway** all five are fleet-wide, which is what makes a single console possible: `/v1/leases` and `/v1/devices` return every connected -worker's, each record carrying the `workerId` it lives on, and the two event -routes carry the workers' republished events (also `workerId`-tagged) -interleaved with the gateway's own `worker.*` and `request.dispatched` -facts. +worker's, each record carrying the `workerId` it lives on, +`/v1/lease-requests` returns the gateway's queue and every connected +worker's, and the two event routes carry the workers' republished events +(also `workerId`-tagged) interleaved with the gateway's own `worker.*` and +`request.dispatched` facts. + +#### `GET /v1/lease-requests` + +Every request still waiting for a device, oldest first, whoever sent it. An +`agent` token gets `403 FORBIDDEN`: an agent reads back only its own request, +with [`GET /v1/lease-requests/{id}`](#get-v1lease-requestsid). + +```json +{ "requests": [ + { "id": "req_7", "requesterId": "agent-b", + "spec": { "platform": "ios", "model": "iPhone 16", "osVersion": "18.4", "mode": "slim" }, + "createdAt": 1790864071200, "stage": "queued", "queuePosition": 1 }, + { "id": "req_9", "requesterId": "local-agent", + "spec": { "platform": "android", "model": "Pixel 8" }, + "createdAt": 1790864075000, "stage": "starting", "workerId": "3f81a2c4" } +] } +``` + +- `spec` is the device as the request named it: `platform` and `model`, and + `osVersion`, `mode` and `imageTag` only when the request named them. +- `createdAt` is when the daemon holding the request received it, in + milliseconds since the epoch. +- `stage` is `queued` while the request holds a place in the queue, and + `starting` while a device is being found, created, booted or downloaded for + it. +- `queuePosition` is set only while `queued`: its place in the queue counting + from 1, the requests ahead of it that are already starting included. It is + the request's place now, not the one its `queued` progress first reported. +- A request leaves the list as soon as it is granted, fails or is cancelled. + The request's idempotency key and owner are never listed. + +On a **gateway** the list is the gateway's own queue first, without +`workerId`, then the requests waiting in each connected worker's own queue, +from that worker's local agents, each with the **`workerId`** whose queue it +is in. A request the gateway has sent to a worker is listed once, as the +gateway's own. A worker's `createdAt` comes from that worker's clock. ## Errors diff --git a/e2e/console/waiting.spec.ts b/e2e/console/waiting.spec.ts new file mode 100644 index 000000000..14c4d30e0 --- /dev/null +++ b/e2e/console/waiting.spec.ts @@ -0,0 +1,232 @@ +import type { Locator, Page } from "@playwright/test"; + +import { waitFor } from "../helpers/wait.js"; +import { expect, type RunningDaemon, signIn, startDaemon, test } from "./fixtures.js"; + +/** What `GET /v1/lease-requests` answers, as far as these tests read. */ +interface WaitingRequest { + readonly requesterId: string; + readonly queuePosition?: number; + readonly workerId?: string; +} + +const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; +/** One iOS device and no more, so a second request waits. */ +const ONE_DEVICE = { limits: { ios: { maxDevices: 1, maxRunning: 1 }, maxRunning: 1 } }; +const LEASE = ["lease", "--platform", "ios", "--device", "iPhone 16", "--os", "18.4"] as const; + +/** Leases the host's one device for `agent`, and answers the lease id. */ +async function holdTheDevice(daemon: RunningDaemon, agent: string): Promise { + const granted = await daemon.cli([...LEASE, "--agent-id", agent, "--detach"]); + expect(granted.code, granted.stderr).toBe(0); + return (granted.json as { lease: { id: string } }).lease.id; +} + +/** The daemon's own `GET /v1/lease-requests`, asked as an operator. */ +async function waiting(daemon: RunningDaemon): Promise { + const response = await fetch(new URL("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/v1/lease-requests", daemon.url), { + headers: { Authorization: `Bearer ${daemon.tokens.operator}` }, + }); + expect(response.status).toBe(200); + return ((await response.json()) as { requests: WaitingRequest[] }).requests; +} + +/** + * Waits, asking every 20 ms, until the daemon's own list 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: (requests: readonly WaitingRequest[]) => boolean, +): Promise { + await waitFor(async () => predicate(await waiting(daemon)), { + interval: 20, + label: "the daemon's own waiting requests", + timeout: 10_000, + }); +} + +async function openWaiting(page: Page, daemon: RunningDaemon): Promise { + await page.goto(new URL("/waiting", daemon.url).toString()); + await signIn(page, daemon.tokens.operator); + await expect(page.getByRole("heading", { level: 1, name: "Waiting" })).toBeVisible(); +} + +/** A waiting request's row, by its requester. */ +function row(page: Page, requester: string): Locator { + return page + .getByRole("row") + .filter({ has: page.getByRole("cell", { name: requester, exact: true }) }); +} + +function cell(scope: Locator, label: string): Locator { + return scope.locator(`td[data-label="${label}"]`); +} + +/** Whether the page itself scrolls sideways. */ +async function hasHorizontalScroll(page: Page): Promise { + return page.evaluate( + () => document.documentElement.scrollWidth > document.documentElement.clientWidth, + ); +} + +test.describe("the Waiting view", () => { + test("a request waiting for a device appears with its requester, spec, time waited and queue position", async ({ + page, + }) => { + const host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); + try { + await holdTheDevice(host, "holder"); + host.cliBackground([...LEASE, "--agent-id", "agent-b"]); + await untilTheDaemonSays(host, (requests) => requests.length === 1); + host.cliBackground([...LEASE, "--agent-id", "agent-c", "--mode", "slim"]); + await untilTheDaemonSays(host, (requests) => requests.length === 2); + + await openWaiting(page, host); + + const b = row(page, "agent-b"); + await expect(cell(b, "Device")).toHaveText("iOS iPhone 16, runtime 18.4"); + await expect(cell(b, "Stage")).toHaveText("queued"); + await expect(cell(b, "Place in queue")).toHaveText("1"); + await expect(cell(b, "Waiting for")).toHaveText(/^\d+ s$/); + const c = row(page, "agent-c"); + await expect(cell(c, "Device")).toHaveText("iOS iPhone 16, runtime 18.4, mode slim"); + await expect(cell(c, "Place in queue")).toHaveText("2"); + // The time waited counts on in the browser, with no reload. + const before = await cell(c, "Waiting for").textContent(); + await expect(cell(c, "Waiting for")).not.toHaveText(before ?? "", { timeout: 3_000 }); + } finally { + await host.dispose(); + } + }); + + test("on a gateway, the fleet queue's requests and a worker's own appear, the worker's with that worker", async ({ + page, + }) => { + const gateway = await startDaemon("gateway"); + let worker: RunningDaemon | undefined; + try { + worker = await startDaemon("worker", { + config: { + ...ONE_DEVICE, + gateway: { + label: "worker-a", + token: gateway.tokens.worker, + url: `ws://127.0.0.1:${String(gateway.port)}`, + }, + }, + driverScript: { ios: IOS }, + }); + // A local agent on the worker takes its one device, and a second one waits in the + // worker's own queue. A fleet request for a model no worker lists waits in the gateway's. + await holdTheDevice(worker, "local-a"); + worker.cliBackground([...LEASE, "--agent-id", "local-b"]); + gateway.cliBackground([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 99", + "--agent-id", + "fleet-c", + ]); + await untilTheDaemonSays( + gateway, + (requests) => + requests.some((request) => request.requesterId === "fleet-c") && + requests.some((request) => request.requesterId === "local-b"), + ); + + await openWaiting(page, gateway); + + await expect(cell(row(page, "local-b"), "Worker")).toHaveText("worker-a"); + await expect(cell(row(page, "local-b"), "Place in queue")).toHaveText("1"); + await expect(cell(row(page, "fleet-c"), "Device")).toHaveText("iOS iPhone 99"); + await expect(cell(row(page, "fleet-c"), "Place in queue")).toHaveText("1"); + await expect(cell(row(page, "fleet-c"), "Worker")).toHaveText("—"); + } finally { + await worker?.dispose(); + await gateway.dispose(); + } + }); + + test("a waiting request leaves the view within a second of being granted", async ({ page }) => { + const host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); + try { + const held = await holdTheDevice(host, "holder"); + host.cliBackground([...LEASE, "--agent-id", "agent-b"]); + await untilTheDaemonSays(host, (requests) => requests.length === 1); + await openWaiting(page, host); + await expect(row(page, "agent-b")).toBeVisible(); + + expect((await host.cli(["release", held])).code).toBe(0); + await untilTheDaemonSays(host, (requests) => requests.length === 0); + + await expect(row(page, "agent-b")).toHaveCount(0, { timeout: 1_000 }); + await expect(page.getByText("No requests are waiting.")).toBeVisible(); + } finally { + await host.dispose(); + } + }); + + test("the Waiting view has no horizontal scroll at 360px wide", async ({ page }) => { + const host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); + try { + await holdTheDevice(host, "holder"); + host.cliBackground([ + ...LEASE, + "--agent-id", + "an-agent-with-a-rather-long-requester-id-0123456789", + "--mode", + "slim", + ]); + await untilTheDaemonSays(host, (requests) => requests.length === 1); + await page.setViewportSize({ height: 740, width: 360 }); + + await openWaiting(page, host); + + await expect(page.locator("tbody tr")).toHaveCount(1); + expect(await hasHorizontalScroll(page)).toBe(false); + } finally { + await host.dispose(); + } + }); + + test("the Waiting 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 host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); + try { + await holdTheDevice(host, "holder"); + host.cliBackground([...LEASE, "--agent-id", "agent-b"]); + await untilTheDaemonSays(host, (requests) => requests.length === 1); + const listed = await host.cli(["worker", "list", "--json"]); + const hostId = (listed.json as { workers: { id: string }[] }).workers[0]?.id ?? ""; + /** Tabs forward until the link named `label` has focus, and follows it with Enter. */ + const follow = async (label: string) => { + const link = page.getByRole("link", { name: label, exact: true }); + 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(host.url); + await page.keyboard.press(tab); + await page.keyboard.type(host.tokens.operator); + await page.keyboard.press("Enter"); + await expect(page.getByRole("heading", { level: 1, name: "Workers" })).toBeVisible(); + + await follow("Waiting"); + await expect(page.getByRole("heading", { level: 1, name: "Waiting" })).toBeVisible(); + await expect(row(page, "agent-b")).toBeVisible(); + + // The request's worker opens that worker's page. + await follow(hostId); + await expect(page.getByRole("heading", { level: 1, name: hostId })).toBeVisible(); + } finally { + await host.dispose(); + } + }); +}); diff --git a/e2e/waiting-requests.test.ts b/e2e/waiting-requests.test.ts new file mode 100644 index 000000000..29170c6e9 --- /dev/null +++ b/e2e/waiting-requests.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, it } from "vitest"; + +import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; + +/** + * `simlock list --requests`: every request waiting for a device, one line each, on a single host + * and on a gateway, where a request in a worker's own queue names that worker. + */ + +const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; +const LEASE = ["lease", "--platform", "ios", "--device", "iPhone 16", "--os", "18.4"] as const; +/** One iOS device and no more, so a second request waits. */ +const ONE_DEVICE = { ios: { maxDevices: 1, maxRunning: 1 }, maxRunning: 1 }; + +/** The lines `simlock list --requests` prints, once there are `count` of them. */ +async function requestLines(env: TestEnv, count: number): Promise { + let lines: string[] = []; + await waitFor( + async () => { + const listed = await env.cli(["list", "--requests"]); + expect(listed.code, listed.stderr).toBe(0); + lines = listed.stdout.trimEnd().split("\n"); + return lines.length === count && lines.every((line) => line.startsWith("Request ")); + }, + { label: `${String(count)} waiting request lines` }, + ); + return lines; +} + +describe("simlock list --requests", () => { + it("simlock list --requests prints one line per waiting request", async () => { + const env = await withDaemon({ + configOverrides: { limits: ONE_DEVICE }, + driverScript: { ios: IOS }, + }); + expect((await env.cli([...LEASE, "--agent-id", "holder", "--detach"])).code).toBe(0); + const empty = await env.cli(["list", "--requests"]); + expect(empty.stdout).toBe("No requests are waiting.\n"); + + env.cliBackground([...LEASE, "--agent-id", "agent-b"]); + await requestLines(env, 1); + env.cliBackground([...LEASE, "--agent-id", "agent-c", "--mode", "slim"]); + const lines = await requestLines(env, 2); + + expect(lines[0]).toMatch( + /^Request \S+: agent-b, ios iPhone 16 18\.4, queued at 1, waiting \d+s$/, + ); + expect(lines[1]).toMatch( + /^Request \S+: agent-c, ios iPhone 16 18\.4 mode slim, queued at 2, waiting \d+s$/, + ); + }); + + it("on a gateway, lists the fleet queue and a request in a worker's own queue with that worker", async () => { + const port = await freeLoopbackPort(); + const gateway = await withDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + driver: "none", + }); + const minted = await gateway.cli(["token", "create", "--role", "worker"]); + expect(minted.code).toBe(0); + const worker = await withDaemon({ + configOverrides: { + gateway: { + label: "worker-a", + token: (minted.json as { secret: string }).secret, + url: `ws://127.0.0.1:${String(port)}`, + }, + limits: ONE_DEVICE, + }, + driverScript: { ios: IOS }, + }); + let workerId = ""; + await waitFor( + async () => { + const listed = await gateway.cli(["worker", "list", "--json"]); + const views = (listed.json as { workers?: { id: string; catalog: unknown[] }[] }).workers; + workerId = views?.[0]?.id ?? ""; + return views?.length === 1 && JSON.stringify(views[0]?.catalog).includes("iPhone 16"); + }, + { label: "the worker joined the gateway and its catalog arrived", timeout: 30_000 }, + ); + + // A local agent on the worker takes its one device, and a second one waits in the worker's + // own queue. A fleet request then waits in the gateway's. + expect((await worker.cli([...LEASE, "--agent-id", "local-a", "--detach"])).code).toBe(0); + worker.cliBackground([...LEASE, "--agent-id", "local-b"]); + await requestLines(worker, 1); + gateway.cliBackground([...LEASE, "--agent-id", "fleet-c"]); + + const lines = await requestLines(gateway, 2); + + expect(lines).toEqual([ + expect.stringMatching( + /^Request \S+: fleet-c, ios iPhone 16 18\.4, queued at 1, waiting \d+s$/, + ), + expect.stringMatching( + new RegExp( + `^Request \\S+: local-b on ${workerId}, ios iPhone 16 18\\.4, queued at 1, waiting \\d+s$`, + ), + ), + ]); + }); +}); diff --git a/src/cli/index.ts b/src/cli/index.ts index 04b1e0572..5a58a8d40 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -2,6 +2,8 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { parseArgs } from "node:util"; +import type { z } from "zod"; + import { EVENT_FILE_NAME, type EventEnvelope, eventKey, readEventFile } from "../bus/index.js"; import { loadConfig, type ConfigOverrides } from "../core/index.js"; import { @@ -38,7 +40,7 @@ import { type StatusGetOutput, type WorkerView, } from "../admin/index.js"; -import type { Role } from "../contract/index.js"; +import { type Role, waitingRequestSchema } from "../contract/index.js"; import type { PassthroughCommand } from "../client/index.js"; import { awaitWithin, @@ -50,6 +52,8 @@ import { followLog, type Signals } from "./follow-log.js"; import { spawnPassthrough } from "./passthrough.js"; import { ERROR_TABLE } from "../contract/index.js"; +type WaitingRequestEntry = z.infer; + const USAGE = `Usage: simlock [options] Commands: @@ -1290,17 +1294,23 @@ async function runList( devices: { type: "boolean" }, help: { type: "boolean", short: "h" }, leases: { type: "boolean" }, + requests: { type: "boolean" }, rules: { type: "boolean" }, }); if (values.help) { - environment.stdout.write("Usage: simlock list [--devices|--leases|--rules]\n"); + environment.stdout.write("Usage: simlock list [--devices|--leases|--rules|--requests]\n"); return 0; } - if ([values.devices, values.leases, values.rules].filter(Boolean).length > 1) - throw new UsageError("list accepts only one of --devices, --leases, or --rules"); - const kind = values.leases ? "leases" : values.rules ? "rules" : "devices"; + if ([values.devices, values.leases, values.rules, values.requests].filter(Boolean).length > 1) + throw new UsageError("list accepts only one of --devices, --leases, --rules, or --requests"); const client = await connectDaemonClient(environment, token); try { + if (values.requests) { + const requests = waitingRequestSchema.array().parse(await client.list({ kind: "requests" })); + environment.stdout.write(`${formatWaitingRequests(requests, environment.clock.now())}\n`); + return 0; + } + const kind = values.leases ? "leases" : values.rules ? "rules" : "devices"; writeResult(environment, await client.list({ kind })); return 0; } finally { @@ -1308,6 +1318,36 @@ async function runList( } } +/** + * One line per waiting request: `Request req_7: agent-b on wrk_1, ios iPhone 16 18.4 mode slim, + * queued at 2, waiting 12s` -- the request, who sent it, the worker whose queue it waits in, the + * device it asked for, where it stands, and for how long. + */ +function formatWaitingRequests(requests: readonly WaitingRequestEntry[], now: number): string { + if (requests.length === 0) return "No requests are waiting."; + return requests + .map((request) => { + const { spec } = request; + const device = [ + spec.platform, + spec.model, + spec.osVersion, + spec.mode === undefined ? undefined : `mode ${spec.mode}`, + spec.imageTag === undefined ? undefined : `image tag ${spec.imageTag}`, + ] + .filter((part) => part !== undefined) + .join(" "); + const where = request.workerId === undefined ? "" : ` on ${request.workerId}`; + const stage = + request.queuePosition === undefined + ? request.stage + : `${request.stage} at ${String(request.queuePosition)}`; + const waited = Math.max(0, Math.round((now - request.createdAt) / 1000)); + return `Request ${request.id}: ${request.requesterId}${where}, ${device}, ${stage}, waiting ${String(waited)}s`; + }) + .join("\n"); +} + async function runCatalog( argv: readonly string[], environment: CliEnvironment, diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 77d9ffa91..d59fae97f 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -34,6 +34,7 @@ import { statusLeaseSchema, tokenRecordSchema, tokenRoleSchema, + waitingRequestSchema, workerViewSchema, } from "./schemas.js"; @@ -124,6 +125,13 @@ export const statusGet = defineOperation({ * installs, each with its `workerId`. Optional because an older daemon sends none. */ installs: statusInstallsSchema.optional(), + /** + * The requests waiting for a device in this daemon's own queue, oldest first: a worker's + * local queue, a gateway's fleet queue. A gateway lists its workers' own queues on each + * worker view and in `list.get`'s `requests`, not here. Optional because an older daemon + * sends none. + */ + waiting: z.array(waitingRequestSchema).optional(), /** * ADR 0005 §20: one entry per worker view, additive and gateway-only. Absent (not empty) * from a worker's answer -- a worker has no fleet, and an empty array would read as "a @@ -498,19 +506,22 @@ export const leaseReleaseAll = defineOperation({ * * Arm order is load-bearing: a full record matches the first arm, so a worker's answer is * unchanged. `rules` is per-machine cleanup configuration, so a gateway answers it with an - * empty list rather than inventing a fleet-wide rule set. + * empty list rather than inventing a fleet-wide rule set. `requests` lists the requests waiting + * for a device: a worker's own, or on a gateway the fleet queue's and then each worker's, each + * of those with its `workerId`. */ // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. export const listGet = defineOperation({ name: "list.get", role: "admin", effect: "read", - input: z.object({ kind: z.enum(["devices", "leases", "rules"]).optional() }), + input: z.object({ kind: z.enum(["devices", "leases", "rules", "requests"]).optional() }), output: z.union([ z.array(deviceRecordSchema), z.array(statusDeviceSchema), z.array(statusLeaseSchema), z.array(cleanupRuleSummarySchema), + z.array(waitingRequestSchema), ]), }); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index e90e184b7..4f0293cd4 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -241,18 +241,21 @@ export const leaseGrantSchema = z.object({ * a request back in, whichever frontend sent it. `grant` is the grant the request was answered * with, stored as granted -- a later renew does not move its `ttlDeadline`. */ +/** The device a lease request named, with every field it left out left out. */ +const requestedDeviceSchema = z.object({ + platform: platformSchema, + model: z.string(), + osVersion: z.string().optional(), + mode: deviceModeSchema.optional(), + imageTag: imageTagSchema.optional(), +}); + export const leaseRequestRecordSchema = z.object({ id: z.string(), requesterId: z.string(), ownerId: z.string(), idempotencyKey: z.string().optional(), - request: z.object({ - platform: platformSchema, - model: z.string(), - osVersion: z.string().optional(), - mode: deviceModeSchema.optional(), - imageTag: imageTagSchema.optional(), - }), + request: requestedDeviceSchema, createdAt: z.number(), state: z.enum(["open", "granted", "failed", "cancelled"]), settledAt: z.number().optional(), @@ -260,6 +263,24 @@ export const leaseRequestRecordSchema = z.object({ failure: z.object({ code: z.string(), message: z.string() }).optional(), }); +/** + * A request still waiting for a device (`list.get` with `requests`, `status.get`'s `waiting`). + * `stage` is `queued` while the request holds a place in the queue, with that place in + * `queuePosition`, counted from 1 the way `lease.queued` counts it; `starting` while a device is + * being found, made, booted or downloaded for it. `workerId` names the worker whose own queue + * the request waits in; only a gateway sets it. The request's idempotency key and owner are + * never part of it: a key lets its holder replay the request, and neither is the operator's. + */ +export const waitingRequestSchema = z.object({ + id: z.string(), + requesterId: z.string(), + spec: requestedDeviceSchema, + createdAt: z.number(), + stage: z.enum(["queued", "starting"]), + queuePosition: z.number().int().positive().optional(), + workerId: z.string().optional(), +}); + /** * The scoped command `simlock simctl` / `simlock adb` runs on the caller's behalf. The command * is spawned as-is, so the shape is validated at the boundary like every other output: an @@ -878,6 +899,10 @@ export const workerViewSchema = z.object({ /** ADR 0010 §7: the `installs` of the worker's last `status.get`. Empty for a worker whose * status lists none, including one too old to list them. */ installs: workerInstallsSchema.optional(), + /** The `waiting` of the worker's last `status.get`: the requests waiting in its own queue, + * copied as `installs` is. Empty for a worker too old to list them; absent for a + * disconnected or incompatible one, which the gateway cannot ask. */ + waiting: z.array(waitingRequestSchema).optional(), }); /** diff --git a/src/contract/worker-view.ts b/src/contract/worker-view.ts index 74e535b36..dac3545e3 100644 --- a/src/contract/worker-view.ts +++ b/src/contract/worker-view.ts @@ -47,7 +47,7 @@ export interface WorkerReads { * reads that carry them were made. */ export type WorkerViewReport = Pick< WorkerView, - "capacity" | "devices" | "health" | "host" | "installs" | "leases" | "queueDepth" + "capacity" | "devices" | "health" | "host" | "installs" | "leases" | "queueDepth" | "waiting" > & Partial>; @@ -67,6 +67,9 @@ export function workerViewFields(reads: WorkerReads): WorkerViewReport { installs: status.installs ?? [], leases: status.leases, queueDepth: status.queueDepth, + // Copied as `installs` is: the requests waiting in the worker's own queue. A worker too old + // to list them reports none. + waiting: status.waiting ?? [], devices: viewDevicesSchema.parse(reads.devices), ...(catalog === undefined ? {} : { catalog: catalog.platforms }), ...(config === undefined diff --git a/src/core/lease-engine.ts b/src/core/lease-engine.ts index 8697b2055..f2847a898 100644 --- a/src/core/lease-engine.ts +++ b/src/core/lease-engine.ts @@ -27,7 +27,7 @@ import { LeaseExpiryScheduler } from "./lease-expiry-scheduler.js"; import { LeaseHealthMonitor } from "./lease-health-monitor.js"; import { LeaseLifecycle } from "./lease-lifecycle.js"; import { LeaseReleaseCoordinator } from "./lease-release-coordinator.js"; -import { LeaseRequestBook } from "./lease-request-book.js"; +import { LeaseRequestBook, type WaitingRequest } from "./lease-request-book.js"; import { ManagedDeviceLifecycle } from "./managed-device-lifecycle.js"; import { NukeService } from "./nuke-service.js"; import { QuarantineCoordinator } from "./quarantine-coordinator.js"; @@ -379,6 +379,12 @@ export class LeaseEngine { await this.#startup.converge(); } + /** Every request waiting for a device on this host, for `list.get` and `status.get`. */ + // fallow-ignore-next-line unused-class-member -- reached through the QueueControl port by the dispatcher (same as the sibling queueDepth). + waitingRequests(): readonly WaitingRequest[] { + return this.requests.waiting(this.#queue.places()); + } + /** Cancels a single pending request by requester id, for the HTTP lease-request delete route. */ // fallow-ignore-next-line unused-class-member -- reached through the QueueControl port by DaemonServer (same as the sibling queueDepth). async cancelPending(requesterId: string): Promise<"cancelled" | "not-found" | "not-cancellable"> { diff --git a/src/core/lease-ports.ts b/src/core/lease-ports.ts index ca6fc93fe..2dd81b870 100644 --- a/src/core/lease-ports.ts +++ b/src/core/lease-ports.ts @@ -2,6 +2,7 @@ import type { CapacityPlatform, RamBudget, RunningCapacity } from "./capacity/in import type { LeaseRecord, Platform } from "./domain.js"; import type { DeviceRequest, PassthroughCommand, PassthroughContext } from "./driver.js"; import type { PlatformCatalog } from "./driver-catalog.js"; +import type { WaitingRequest } from "./lease-request-book.js"; import type { LeaseGrant, LeaseRequestOptions } from "./wait-queue.js"; /** Client-requestable subset only -- deliberately excludes the internally-originated @@ -28,6 +29,8 @@ export interface QueueControl { * `lease.cancel`'s `authorize` hook so a proxy connection (one principal, many * `requesterId`s) can cancel what it created, per ADR §4/§9. */ pendingRequestOwner(requesterId: string): string | undefined; + /** Every request still waiting for a device, oldest first (`LeaseRequestBook#waiting`). */ + waitingRequests(): readonly WaitingRequest[]; } /** Read-only capacity view used by daemon status. */ diff --git a/src/core/lease-request-book.ts b/src/core/lease-request-book.ts index dedd1c463..6a3cf3a9e 100644 --- a/src/core/lease-request-book.ts +++ b/src/core/lease-request-book.ts @@ -5,6 +5,7 @@ import type { SerializedDecision } from "./serialized-decision.js"; import { type LeaseProgress, type LeaseRequestOptions, + type QueuePlace, RequestCancelledError, } from "./wait-queue.js"; @@ -153,6 +154,41 @@ export class InMemoryLeaseRequestStore implements LeaseRequestStore, "createdAt" | "id" | "request" | "requesterId">, + place: QueuePlace, +): WaitingRequest { + return { + createdAt: record.createdAt, + id: record.id, + requesterId: record.requesterId, + spec: { ...record.request }, + ...(place.queuePosition === undefined + ? { stage: "starting" } + : { queuePosition: place.queuePosition, stage: "queued" }), + }; +} + /** The same `(requesterId, idempotencyKey)` arrived again naming a different device. */ export class IdempotencyConflictError extends Error { constructor( @@ -353,6 +389,19 @@ export class LeaseRequestBook open.watchers.delete(listener); } + /** + * Every stored request that is still open and that a live wait in `places` is driving, oldest + * first. A request whose wait has ended is not listed, even before its result is written; nor is + * an open record no wait drives, such as one a restarted daemon has not settled yet. + */ + waiting(places: readonly QueuePlace[]): WaitingRequest[] { + const byId = new Map(places.map((place) => [place.id, place])); + return this.options.store.leaseRequests().flatMap((record) => { + const place = byId.get(record.id); + return isSettled(record) || place === undefined ? [] : [waitingRequest(record, place)]; + }); + } + /** The id of the stored request that was granted `leaseId`, while that record is retained. */ requestIdForLease(leaseId: string): string | undefined { return this.options.store diff --git a/src/core/wait-queue.ts b/src/core/wait-queue.ts index 158afd464..cc8d15dc0 100644 --- a/src/core/wait-queue.ts +++ b/src/core/wait-queue.ts @@ -86,6 +86,12 @@ export class ForeignWaiterError extends Error { export type WaiterState = "new" | "queued" | "processing" | "granted" | "rejected"; +/** Where a waiter stands (`WaitQueue#places`): `queuePosition` only while it is `queued`. */ +export interface QueuePlace { + readonly id: string; + readonly queuePosition?: number; +} + export interface Waiter { readonly id: string; readonly request: DeviceRequest; @@ -150,6 +156,21 @@ export class WaitQueue { return [...this.#waiters]; } + /** + * Every waiter not yet granted or rejected, oldest first, with its place in the FIFO while it + * is `queued`: its 1-based index there, counting the waiters ahead of it that are already being + * worked on, which is how a `queued` progress report and `lease.queued` count. A waiter being + * worked on (`new` or `processing`) has no place. Read now, not as last reported: a waiter + * moves up as the ones ahead of it leave. + */ + places(): readonly QueuePlace[] { + return [...this.#pendingWaiters].map((waiter) => + waiter.state === "queued" + ? { id: waiter.id, queuePosition: this.#waiters.indexOf(waiter) + 1 } + : { id: waiter.id }, + ); + } + hasPendingRequester(requesterId: string): boolean { return this.#pendingRequesters.has(requesterId); } diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index b5810f42f..6e930cb06 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1494,6 +1494,130 @@ describe("Dispatcher: status.get installs in progress", () => { }); }); +describe("Dispatcher: list.get requests and status.get waiting", () => { + const IOS_REQUEST = { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" } as const; + + /** A lease request from `requesterId`, left running: it resolves once granted. */ + function request( + dispatcher: Dispatcher, + requesterId: string, + extra: Record = {}, + ): Promise { + return dispatcher.dispatch( + "lease.request", + { ...IOS_REQUEST, requesterId, ...extra }, + session({ principal: "host" }), + ); + } + + /** Fills iOS's two devices (`testConfig`), so the next request queues. */ + async function fillIos(dispatcher: Dispatcher): Promise { + await request(dispatcher, "holder-1"); + await request(dispatcher, "holder-2"); + } + + const requests = (dispatcher: Dispatcher) => + dispatcher.dispatch("list.get", { kind: "requests" }, session({ role: "admin" })); + + it("list.get requests on a worker returns every open request with its queue position", async () => { + const { clock, dispatcher, engine } = await buildDispatcher(); + await fillIos(dispatcher); + const firstAt = clock.now(); + void request(dispatcher, "agent-a", { idempotencyKey: "key-a", mode: "full" }); + await expect.poll(() => engine.queueDepth).toBe(1); + clock.advance(5_000); + void request(dispatcher, "agent-b"); + await expect.poll(() => engine.queueDepth).toBe(2); + + const listed = await requests(dispatcher); + + expect(listed).toEqual([ + { + createdAt: firstAt, + id: expect.any(String), + queuePosition: 1, + requesterId: "agent-a", + spec: { ...IOS_REQUEST, mode: "full" }, + stage: "queued", + }, + { + createdAt: firstAt + 5_000, + id: expect.any(String), + queuePosition: 2, + requesterId: "agent-b", + spec: IOS_REQUEST, + stage: "queued", + }, + ]); + // The idempotency key and the owner stay the requester's. + expect(JSON.stringify(listed)).not.toContain("key-a"); + expect(JSON.stringify(listed)).not.toContain('"host"'); + }); + + it("a request that is starting a device has stage starting and no queue position", async () => { + const { dispatcher } = await buildDispatcher({ + driverOptions: { latencyMs: { provision: 60_000 } }, + }); + void request(dispatcher, "agent-a"); + + await expect.poll(async () => (await requests(dispatcher)).length).toBe(1); + + expect(await requests(dispatcher)).toEqual([ + { + createdAt: expect.any(Number), + id: expect.any(String), + requesterId: "agent-a", + spec: IOS_REQUEST, + stage: "starting", + }, + ]); + }); + + it("a granted, failed or cancelled request is not listed", async () => { + const { clock, dispatcher, engine, registry } = await buildDispatcher(); + await fillIos(dispatcher); + const timedOut = request(dispatcher, "agent-timeout", { timeoutMs: 1_000 }); + const cancelled = request(dispatcher, "agent-cancel"); + await expect.poll(() => engine.queueDepth).toBe(2); + expect(await requests(dispatcher)).toHaveLength(2); + + clock.advance(1_000); + await expect(timedOut).rejects.toMatchObject({ name: "QueueTimeoutError" }); + await dispatcher.dispatch( + "lease.cancel", + { requesterId: "agent-cancel" }, + session({ principal: "host" }), + ); + await expect(cancelled).rejects.toThrow(); + + await expect + .poll(() => registry.leaseRequests().map((record) => record.state)) + .toEqual(["granted", "granted", "failed", "cancelled"]); + expect(await requests(dispatcher)).toEqual([]); + }); + + it("status.get waiting matches list.get requests on a worker", async () => { + const { dispatcher, engine } = await buildDispatcher({ + driverOptions: { latencyMs: { provision: 60_000 } }, + }); + // Both iOS devices are being made: the two requests start, the third queues behind them. + void request(dispatcher, "agent-a"); + void request(dispatcher, "agent-b"); + void request(dispatcher, "agent-c"); + await expect.poll(() => engine.queueDepth).toBe(1); + + const listed = await requests(dispatcher); + const { waiting } = await dispatcher.dispatch("status.get", {}, session()); + + expect(listed.map((entry) => ("stage" in entry ? entry.stage : undefined))).toEqual([ + "starting", + "starting", + "queued", + ]); + expect(waiting).toEqual(listed); + }); +}); + /** Lets every settled promise and queued continuation run. */ async function flushPromises(): Promise { for (let count = 0; count < 100; count += 1) await Promise.resolve(); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index d13751685..f8c0351bf 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -352,6 +352,7 @@ export class Dispatcher { installs: [...this.options.components.inProgress()], leases: [...snapshot.leases], queueDepth: this.options.queue.queueDepth, + waiting: [...this.options.queue.waitingRequests()], }; }; @@ -611,6 +612,8 @@ export class Dispatcher { return [...snapshot.leases]; case "rules": return this.options.reaper.rules; + case "requests": + return [...this.options.queue.waitingRequests()]; case "devices": case undefined: return snapshot.devices.map((device) => this.#decorateDevice(device)); diff --git a/src/gateway/aggregate.ts b/src/gateway/aggregate.ts index 49482b373..68c7269e1 100644 --- a/src/gateway/aggregate.ts +++ b/src/gateway/aggregate.ts @@ -47,6 +47,8 @@ export interface AggregateStatusOptions { readonly host: StatusOutput["host"]; /** The gateway's fleet queue depth -- 0 until #118 gives it a queue. */ readonly queueDepth: number; + /** The requests waiting in the fleet queue. Each worker's own are on its view. */ + readonly waiting?: StatusOutput["waiting"]; /** * #118: rewrites each view's leases to gateway-facing form (its own id, fleet-level * `requesterId`, `worker`) for the ones this gateway actually issued -- see @@ -92,6 +94,7 @@ export function aggregateStatus( ), ), queueDepth: options.queueDepth, + waiting: [...(options.waiting ?? [])], workers: [...views], }; } diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index c1f1db780..6858be923 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -1079,3 +1079,115 @@ describe("GatewayDispatcher", () => { } }); }); + +describe("GatewayDispatcher: waiting requests", () => { + const SPEC = { model: "iPhone 17", platform: "ios" as const }; + + /** A request a worker lists in its own `status.get`'s `waiting`. */ + function onWorker(id: string, requesterId: string, queuePosition?: number) { + return { + createdAt: 500, + id, + requesterId, + spec: SPEC, + ...(queuePosition === undefined + ? { stage: "starting" as const } + : { queuePosition, stage: "queued" as const }), + }; + } + + /** Lets the coordinator's admission and dispatch pass run. */ + async function settle(): Promise { + for (let count = 0; count < 20; count += 1) await Promise.resolve(); + } + + const listRequests = (dispatcher: GatewayDispatcher) => + dispatcher.dispatch("list.get", { kind: "requests" }, session()); + + it("list.get requests on a gateway returns the fleet queue and each worker's waiting requests with their workerId", async () => { + const { coordinator, dispatcher, workers } = harness(); + // No worker is connected, so the fleet request waits in the gateway's own queue. + void dispatcher.dispatch( + "lease.request", + { ...SPEC, idempotencyKey: "key-1", requesterId: "fleet-agent" }, + session({ principal: "fleet-owner", role: "agent" }), + ); + await settle(); + expect(coordinator.queueDepth).toBe(1); + // Two workers whose own queues hold their local agents' requests. Neither lists a model, + // so neither takes the fleet request. + for (const [workerId, requestId] of [ + ["wrk_1", "req_w1"], + ["wrk_2", "req_w2"], + ] as const) { + workers.connected(workerId, undefined, "0.3.0"); + workers.refresh(workerId, { waiting: [onWorker(requestId, `local-${workerId}`, 1)] }); + } + await settle(); + + const listed = await listRequests(dispatcher); + + expect(listed).toEqual([ + { + createdAt: 1_000, + id: expect.any(String), + queuePosition: 1, + requesterId: "fleet-agent", + spec: SPEC, + stage: "queued", + }, + { ...onWorker("req_w1", "local-wrk_1", 1), workerId: "wrk_1" }, + { ...onWorker("req_w2", "local-wrk_2", 1), workerId: "wrk_2" }, + ]); + expect(JSON.stringify(listed)).not.toContain("key-1"); + expect(JSON.stringify(listed)).not.toContain("fleet-owner"); + // `status.get` carries the fleet queue only; each worker's own is on its view. + const status = await dispatcher.dispatch("status.get", {}, session()); + expect(status.waiting).toEqual([listed[0]]); + }); + + it("a fleet request dispatched to a worker is listed once, by the gateway", async () => { + const { dispatcher, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_1", client); + // The worker takes the request and never answers, so it stays mid-dispatch. + client.requestLeaseQueue.push({ kind: "hang" }); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { + capacity: { + ...statusFixture().capacity, + ios: { ...statusFixture().capacity.ios, limit: 4, maxRunning: 4 }, + }, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + }); + void dispatcher.dispatch( + "lease.request", + { ...SPEC, requesterId: "fleet-agent" }, + session({ principal: "fleet-owner", role: "agent" }), + ); + await settle(); + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + // The worker lists the request it was sent under the gateway's requester id, beside a + // local agent's own. + workers.refresh("wrk_1", { + waiting: [ + onWorker("req_from_gateway", `${GATEWAY_REQUESTER_PREFIX}fleet-agent`), + onWorker("req_local", "local-agent", 1), + ], + }); + + const listed = await listRequests(dispatcher); + + expect(listed).toEqual([ + { + createdAt: 1_000, + id: expect.any(String), + requesterId: "fleet-agent", + spec: SPEC, + stage: "starting", + }, + { ...onWorker("req_local", "local-agent", 1), workerId: "wrk_1" }, + ]); + }); +}); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index ad0780b96..9a3349a41 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -142,11 +142,13 @@ export interface GatewayDispatcherOptions { | "ownerId" | "leaseRequesterId" | "pendingRequestOwner" + | "waitingRequests" >; /** #118: read-only access for `lease.list`/`list.get`/`status.get`'s lease projection * (`FleetLeaseIndex#project`/`#all`) -- kept separate from `coordinator` because this - * dispatcher only ever *reads* it, never mutates it. */ - readonly leaseIndex: Pick; + * dispatcher only ever *reads* it, never mutates it. `requesterPrefix` marks the requests + * this gateway sent a worker, which `list.get`'s `requests` already lists as its own. */ + readonly leaseIndex: Pick; } export class GatewayDispatcher { @@ -241,8 +243,9 @@ export class GatewayDispatcher { const status = aggregateStatus(this.options.workers.views(), { health: this.options.health(), host: this.options.host, - // ADR 0005 §20: the gateway's own fleet queue depth. + // ADR 0005 §20: the gateway's own fleet queue depth, and the requests waiting in it. queueDepth: this.options.coordinator.queueDepth, + waiting: [...this.options.coordinator.waitingRequests()], leaseIndex: this.options.leaseIndex, }); // ADR 0011 §3: a gateway serves the console on its own listener, as a worker does. @@ -363,6 +366,8 @@ export class GatewayDispatcher { return this.#fleetLeases(); case "rules": return []; + case "requests": + return this.#fleetWaiting(); case "devices": case undefined: return this.options.workers @@ -371,6 +376,23 @@ export class GatewayDispatcher { } }; + /** + * The fleet queue's requests, then each worker's own queue, each of those with its `workerId`. + * A worker lists a request this gateway sent it under the gateway's own requester id (ADR 0005 + * §27); the gateway already lists that request, so the worker's copy is left out. + */ + #fleetWaiting() { + const prefix = this.options.leaseIndex.requesterPrefix; + const onWorkers = this.options.workers + .views() + .flatMap((view) => + (view.waiting ?? []) + .filter((request) => !request.requesterId.startsWith(prefix)) + .map((request) => ({ ...request, workerId: view.id })), + ); + return [...this.options.coordinator.waitingRequests(), ...onWorkers]; + } + /** Every lease every worker's view reports, each projected through the lease index -- rewritten * to its gateway id/requester/`worker` for a lease this gateway issued (test: "lease.list * rewrites ids only for gateway-issued leases"), passed through with only `workerId` added for diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index 7c77c2ae6..c92c6bf6a 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -57,6 +57,7 @@ import { InMemoryLeaseRequestStore, LeaseRequestBook, type LeaseRequestLimits, + type WaitingRequest, } from "../core/lease-request-book.js"; import { SerializedDecision } from "../core/serialized-decision.js"; import type { Clock, IdGenerator, Logger } from "../ports/index.js"; @@ -182,6 +183,13 @@ export class FleetLeaseCoordinator { return this.#queue.depth; } + /** Every request waiting in the fleet queue, or being dispatched, oldest first. Read by the + * same function a worker lists its own with (`LeaseRequestBook#waiting`). */ + // fallow-ignore-next-line unused-class-member -- reached only through `GatewayDispatcher`'s `Pick`-typed `coordinator` option. + waitingRequests(): readonly WaitingRequest[] { + return this.requests.waiting(this.#queue.places()); + } + // fallow-ignore-next-line unused-class-member -- reached only through `GatewayDispatcher`'s `Pick`-typed `coordinator` option (`authorizeLookups.ownerId`); the audit cannot follow a call through a structural type. ownerId(gatewayLeaseId: string): string | undefined { return this.options.leaseIndex.ownerId(gatewayLeaseId); diff --git a/src/gateway/queue.ts b/src/gateway/queue.ts index 1de7754b1..a7a4be877 100644 --- a/src/gateway/queue.ts +++ b/src/gateway/queue.ts @@ -20,6 +20,7 @@ import { WaitQueue, type LeaseProgress, type LeaseRequestOptions, + type QueuePlace, type WaiterState, } from "../core/wait-queue.js"; @@ -105,6 +106,11 @@ export class FleetQueue { return this.#queue.list().map((waiter) => asFleet(waiter)); } + /** Where each waiter not yet settled stands. See `WaitQueue#places`. */ + places(): readonly QueuePlace[] { + return this.#queue.places(); + } + hasPendingRequester(requesterId: string): boolean { return this.#queue.hasPendingRequester(requesterId); } diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 5dcbed4c3..3d02fd925 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -183,6 +183,14 @@ describe("GatewayService", () => { ...statusFixture().capacity, global: { maxRunning: 4, overLimit: false, reserved: 1, running: 2, warm: 1 }, }; + const waiting = { + createdAt: 600, + id: "req_1", + queuePosition: 1, + requesterId: "local-agent", + spec: { model: "iPhone 17", platform: "ios" as const }, + stage: "queued" as const, + }; worker.status = statusFixture({ capacity, daemon: { health: "starting", mode: "worker" }, @@ -190,6 +198,7 @@ describe("GatewayService", () => { installs: [install], leases: [leaseFixture("lease_1", "dev_1")], queueDepth: 3, + waiting: [waiting], }); worker.devices = [ { ...deviceFixture("dev_1", "leased"), createdAt: 1, driverData: { private: true } }, @@ -222,6 +231,7 @@ describe("GatewayService", () => { leases: [leaseFixture("lease_1", "dev_1")], queueDepth: 3, version: "9.8.7", + waiting: [waiting], }); await harness.service.stop(); @@ -507,6 +517,37 @@ describe("GatewayService", () => { await harness.service.stop(); }); + describe("waiting requests on the view", () => { + it("a worker's lease.queued event refreshes its view's waiting list on the gateway", async () => { + const worker = new ScriptedWorkerClient(); + const harness = fleet(); + await harness.service.start(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(worker.subscribed).toBe(true)); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.downloads).toBeDefined(), + ); + expect(harness.service.workers.view("wrk_1")?.waiting).toEqual([]); + + const queued = { + createdAt: 500, + id: "req_1", + queuePosition: 1, + requesterId: "local-agent", + spec: { model: "iPhone 17", platform: "ios" as const }, + stage: "queued" as const, + }; + worker.status = statusFixture({ queueDepth: 1, waiting: [queued] }); + worker.pushEvent({ event: "lease.queued" }); + + // Well inside the periodic refresh, which this test never lets come round. + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.waiting).toEqual([queued]), + ); + await harness.service.stop(); + }); + }); + describe("installs in progress on the view (ADR 0010 §7)", () => { const install = { component: "26.4", diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index 6c84ae862..ad21b2186 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -369,6 +369,37 @@ describe("WorkerRegistry", () => { expect(workers.view("wrk_2")?.installs).toBeUndefined(); }); + it("drops a worker's waiting requests from its view when it disconnects or turns incompatible", () => { + const { workers } = registry(); + const waiting = [ + { + createdAt: 1, + id: "req_1", + queuePosition: 1, + requesterId: "local-agent", + spec: { model: "iPhone 17", platform: "ios" as const }, + stage: "queued" as const, + }, + ]; + workers.connected("wrk_1", undefined, "0.3.0"); + workers.connected("wrk_2", undefined, "0.3.0"); + workers.refresh("wrk_1", { waiting }); + workers.refresh("wrk_2", { waiting }); + expect(workers.view("wrk_1")?.waiting).toEqual(waiting); + + workers.disconnected("wrk_1"); + const incompatible = workers.incompatible( + "wrk_2", + undefined, + { gateway: PROTOCOL_VERSION_RANGE, worker: { min: 4, max: 4 } }, + "0.2.0", + ); + + expect(workers.view("wrk_1")?.waiting).toBeUndefined(); + expect(incompatible.waiting).toBeUndefined(); + expect(workers.view("wrk_2")?.waiting).toBeUndefined(); + }); + it("keeps a disconnected view with the leases it last reported", () => { const { clock, events, workers } = registry(); workers.connected("wrk_1", "mac-mini-1", "0.3.0"); diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index f95af493b..11d4a84b1 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -39,6 +39,7 @@ export type WorkerViewSnapshot = Pick< | "leases" | "queueDepth" | "version" + | "waiting" >; /** A worker's device in the shape a grant carries it: what `GET /v1/leases/{id}` builds a lease @@ -235,8 +236,8 @@ export class WorkerRegistry { }; // ADR 0008 §8: host facts come from `status.get`, which an incompatible worker is never // asked. A view left over from an earlier, compatible session must not keep showing them, - // nor the installs that status listed (ADR 0010 §7). - const { host: _stale, installs: _staleInstalls, ...withoutHost } = view; + // nor the installs or waiting requests that status listed (ADR 0010 §7). + const { host: _stale, installs: _staleInstalls, waiting: _staleWaiting, ...withoutHost } = view; this.#workers.set(workerId, withoutHost); this.#notifyViewsChanged(); return withoutHost; @@ -345,8 +346,9 @@ export class WorkerRegistry { const existing = this.#workers.get(workerId); if (existing === undefined || existing.connection === "disconnected") return; // ADR 0010 §7: an install on a worker nobody can reach is not known to be in progress, so - // the view stops listing it rather than showing it running for ever. - const { installs: _unknown, ...withoutInstalls } = existing; + // the view stops listing it rather than showing it running for ever. The same goes for the + // requests waiting in that worker's own queue. + const { installs: _unknown, waiting: _unknownWaiting, ...withoutInstalls } = existing; this.#workers.set(workerId, { ...withoutInstalls, connection: "disconnected", diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 292fded73..2292f38e3 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -8,6 +8,7 @@ import { RequesterAlreadyLeasedError, UnknownLeaseError, } from "../core/index.js"; +import { runDispatch } from "../daemon/dispatch.js"; import { DispatchError, DoctorUnavailableError } from "../daemon/dispatcher.js"; import { describeLeaseRequestFailure, StartupFailedError } from "../daemon/error-code.js"; import { OwnerRoutedFactBus } from "../daemon/owner-routed-facts.js"; @@ -1665,6 +1666,36 @@ describe("operator-only listing routes", () => { expect(operatorBody.leases.map((lease) => lease.id).sort()).toEqual(["lse_1", "lse_2"]); }); + it("GET /v1/lease-requests answers 403 for an agent token", async () => { + const { app, dispatcher } = buildHarness(); + const waiting = { + createdAt: 900, + id: "req_1", + queuePosition: 1, + requesterId: "agent-b", + spec: { model: "iPhone 16", platform: "ios" }, + stage: "queued", + }; + // `list.get`'s own role check, through the contract's real pipeline: the route adds none. + dispatcher.handlers["list.get"] = (input, session) => + runDispatch("list.get", input, session, { + handlers: { + "list.get": (listInput) => { + expect(listInput).toEqual({ kind: "requests" }); + return [waiting]; + }, + }, + }); + + const asAgent = await app.request("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/v1/lease-requests", { headers: agentAuth }); + const asOperator = await app.request("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/v1/lease-requests", { headers: operatorAuth }); + + expect(asAgent.status).toBe(403); + expect(((await asAgent.json()) as { error: { code: string } }).error.code).toBe("FORBIDDEN"); + expect(asOperator.status).toBe(200); + expect(await asOperator.json()).toEqual({ requests: [waiting] }); + }); + it("GET /v1/devices dispatches list.get(kind: devices)", async () => { const { app, dispatcher } = buildHarness(); dispatcher.handlers["list.get"] = (input) => { diff --git a/src/http/app.ts b/src/http/app.ts index 041be2c20..7d5d59747 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -282,6 +282,17 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa return c.json({ request: serializeRequest(outcome.view) }, 201); }); + // Every request waiting for a device, whoever sent it. Operator-role in effect: `list.get` is + // an admin operation, so an agent token gets `FORBIDDEN`/403 from the shared dispatcher. + app.get("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/v1/lease-requests", agentAuth, async (c) => { + const requests = await deps.dispatch( + "list.get", + { kind: "requests" }, + buildHttpSession(c.get("identity")), + ); + return c.json({ requests }); + }); + app.get("/v1/lease-requests/:id", agentAuth, async (c) => { const id = c.req.param("id"); const initial = tracker.get(id); diff --git a/ui/src/status.tsx b/ui/src/status.tsx index 4076f5d23..3160fa664 100644 --- a/ui/src/status.tsx +++ b/ui/src/status.tsx @@ -34,6 +34,8 @@ const HEALTH: Tones = { running: "ok", starting: "warn", failed: "error" }; const INSTALL_STATES: Tones = { downloading: "ok", waiting: "idle" }; +const WAITING_STAGES: Tones = { queued: "idle", starting: "ok" }; + /** * Each status the daemon sends, as a word and a tone. Wire input is a claim: a word this * console does not know, from a newer daemon, still shows as itself, in the neutral tone. @@ -46,3 +48,4 @@ export const deviceStateStatus = (state: string) => statusOf(DEVICE_STATES, stat export const connectionStatus = (connection: string) => statusOf(CONNECTIONS, connection); export const healthStatus = (health: string) => statusOf(HEALTH, health); export const installStatus = (state: string) => statusOf(INSTALL_STATES, state); +export const waitingStageStatus = (stage: string) => statusOf(WAITING_STAGES, stage); diff --git a/ui/src/views/index.tsx b/ui/src/views/index.tsx index b4071f5a4..1f12dc56c 100644 --- a/ui/src/views/index.tsx +++ b/ui/src/views/index.tsx @@ -1,6 +1,7 @@ import type { ComponentType } from "react"; import { ComingSoon } from "./coming-soon"; +import { WaitingView } from "./waiting"; import { WorkersView } from "./workers"; /** @@ -18,7 +19,7 @@ export interface View { export const VIEWS: readonly View[] = [ { path: "/workers", label: "Workers", Component: WorkersView }, { path: "/leases", label: "Leases", Component: () => }, - { path: "/waiting", label: "Waiting", Component: () => }, + { path: "/waiting", label: "Waiting", Component: WaitingView }, { path: "/attention", label: "Attention", Component: () => }, { path: "/events", label: "Events", Component: () => }, ]; diff --git a/ui/src/views/waiting-model.ts b/ui/src/views/waiting-model.ts new file mode 100644 index 000000000..2ca41ccc2 --- /dev/null +++ b/ui/src/views/waiting-model.ts @@ -0,0 +1,45 @@ +/** + * The facts the Waiting view shows, computed from `GET /v1/lease-requests` and `GET /v1/workers`. + * Pure, so the view stays rendering and these stay tested. The types are the contract's, imported + * type-only (ADR 0011 §1). + */ +import type { z } from "zod"; + +import type { waitingRequestSchema } from "../../../src/contract/schemas"; +import { platformName, type WorkerView } from "./workers-model"; + +export type WaitingRequest = z.infer; + +export interface WaitingList { + readonly requests: readonly WaitingRequest[]; +} + +/** + * The device a request asked for, with only the fields it named: `iOS iPhone 16, runtime 18.4, + * mode slim, image tag google_apis`. + */ +export function requestedDevice(spec: WaitingRequest["spec"]): string { + return [ + `${platformName(spec.platform)} ${spec.model}`, + spec.osVersion === undefined ? undefined : `runtime ${spec.osVersion}`, + spec.mode === undefined ? undefined : `mode ${spec.mode}`, + spec.imageTag === undefined ? undefined : `image tag ${spec.imageTag}`, + ] + .filter((part) => part !== undefined) + .join(", "); +} + +/** + * The worker whose own queue a request waits in: the one it names, or on a single host the one + * worker whose view lists it. `undefined` for a request in a gateway's queue, which no worker + * holds yet, and for a worker the console has no view of. + */ +export function waitingOn( + request: WaitingRequest, + workers: readonly WorkerView[], +): WorkerView | undefined { + if (request.workerId !== undefined) { + return workers.find((worker) => worker.id === request.workerId); + } + return workers.find((worker) => worker.waiting?.some((entry) => entry.id === request.id)); +} diff --git a/ui/src/views/waiting.test.tsx b/ui/src/views/waiting.test.tsx new file mode 100644 index 000000000..53d4b173c --- /dev/null +++ b/ui/src/views/waiting.test.tsx @@ -0,0 +1,110 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; + +import { WaitingTable } from "./waiting"; +import { requestedDevice, type WaitingRequest } from "./waiting-model"; +import type { WorkerView } from "./workers-model"; + +const NOW = Date.parse("2026-10-02T12:00:00Z"); + +function request(overrides: Partial = {}): WaitingRequest { + return { + createdAt: NOW - 75_000, + id: "req_1", + queuePosition: 1, + requesterId: "agent-b", + spec: { model: "iPhone 16", platform: "ios" }, + stage: "queued", + ...overrides, + }; +} + +function worker(overrides: Partial = {}): WorkerView { + return { + catalog: [], + connection: "connected", + devices: [], + drained: false, + id: "wrk_1", + lastSeenAt: NOW, + leases: [], + ...overrides, + }; +} + +/** The text a screen shows, without markup. */ +function text(html: string): string { + return html + .replace(/<[^>]+>/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +describe("the Waiting view", () => { + it("writes the device a request asked for with only the fields it named", () => { + expect(requestedDevice({ model: "iPhone 16", platform: "ios" })).toBe("iOS iPhone 16"); + expect( + requestedDevice({ + imageTag: "google_apis", + mode: "slim", + model: "Pixel 8", + osVersion: "35", + platform: "android", + }), + ).toBe("Android Pixel 8, runtime 35, mode slim, image tag google_apis"); + }); + + it("names the worker a request waits on: by its workerId, or on a single host the worker whose view lists it", () => { + const onGateway = request({ id: "req_w", workerId: "wrk_2" }); + const onHost = request({ id: "req_h" }); + const inFleetQueue = request({ id: "req_f", requesterId: "fleet-agent" }); + const workers = [ + worker({ id: "wrk_1", label: "host", waiting: [onHost] }), + worker({ id: "wrk_2", label: "worker-b" }), + ]; + + const html = renderToStaticMarkup( + , + ); + + expect(html).toContain('href="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/workers/wrk_2"'); + expect(text(html)).toContain("agent-b iOS iPhone 16 worker-b queued 1 1 min 15 s"); + expect(html).toContain('href="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/workers/wrk_1"'); + expect(text(html)).toContain("agent-b iOS iPhone 16 host queued"); + expect(text(html)).toContain("fleet-agent iOS iPhone 16 — queued"); + }); + + it("names a worker the console has no view of by its id", () => { + const html = renderToStaticMarkup( + , + ); + + expect(text(html)).toContain("agent-b iOS iPhone 16 wrk_gone queued"); + expect(html).not.toContain("href="); + }); + + it("shows a starting request with no place in the queue, and a stage it does not know as its raw word", () => { + const starting = request({ id: "req_s", stage: "starting" }); + delete (starting as { queuePosition?: number }).queuePosition; + // A stage a newer daemon may send, which this console has never heard of. + const unknown = { + ...request({ id: "req_u" }), + stage: "hibernating", + } as unknown as WaitingRequest; + + const html = renderToStaticMarkup( + , + ); + + expect(text(html)).toContain("starting — 1 min 15 s"); + expect(html).toContain('class="status status-ok"'); + expect(text(html)).toContain("hibernating 1"); + expect(html).toContain('class="status status-idle"'); + }); + + it("says so when nothing is waiting", () => { + const html = renderToStaticMarkup(); + + expect(text(html)).toBe("No requests are waiting."); + }); +}); diff --git a/ui/src/views/waiting.tsx b/ui/src/views/waiting.tsx new file mode 100644 index 000000000..2e78e3188 --- /dev/null +++ b/ui/src/views/waiting.tsx @@ -0,0 +1,92 @@ +import { useLiveResource, useNow } from "../live/live-context"; +import { Loaded } from "../live/route-state"; +import { formatDuration } from "../live/time"; +import { Link } from "../router"; +import { Status, waitingStageStatus } from "../status"; +import { requestedDevice, type WaitingList, type WaitingRequest, waitingOn } from "./waiting-model"; +import { type WorkerList, type WorkerView, workerName, workerPath } from "./workers-model"; + +/** + * Every request waiting for a device, from `GET /v1/lease-requests`. `GET /v1/workers` names + * the worker each one waits on. Time waited counts in the browser (ADR 0013 §4). + */ +export function WaitingView() { + const requests = useLiveResource("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/v1/lease-requests"); + const workers = useLiveResource("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/v1/workers"); + const now = useNow(); + return ( +
+

Waiting

+ + {(list) => ( + + )} + +
+ ); +} + +/** One row per waiting request. On a phone each row stacks into a block of labelled lines. */ +export function WaitingTable(props: { + readonly requests: readonly WaitingRequest[]; + readonly workers: readonly WorkerView[]; + /** The daemon's time now, for how long each request has waited. */ + readonly now: number; +}) { + const { now, requests, workers } = props; + if (requests.length === 0) return

No requests are waiting.

; + return ( + + + + + + + + + + + + + {requests.map((request) => { + const stage = waitingStageStatus(request.stage); + return ( + + + + + + + + + ); + })} + +
RequesterDeviceWorkerStagePlace in queueWaiting for
+ {request.requesterId} + {requestedDevice(request.spec)} + + + {stage.word} + + {request.queuePosition ?? "—"} + + {formatDuration(now - request.createdAt)} +
+ ); +} + +function WorkerCell(props: { + readonly request: WaitingRequest; + readonly workers: readonly WorkerView[]; +}) { + const worker = waitingOn(props.request, props.workers); + if (worker === undefined) { + return {props.request.workerId ?? "—"}; + } + return {workerName(worker)}; +} From d32f99baa2665da8a3e49ceb8981833b55c9a922 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 22:47:34 +0200 Subject: [PATCH 2/4] fix(ui,docs,e2e): answer the spec review --- docs/HTTP-API.md | 5 ++--- e2e/console/waiting.spec.ts | 27 ++++++++++----------------- ui/src/views/waiting-model.ts | 14 +++++++++++--- ui/src/views/waiting.test.tsx | 7 +++++-- 4 files changed, 28 insertions(+), 25 deletions(-) diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 1062d90e4..9d0f29a83 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -67,7 +67,7 @@ Three roles: | Role | Can | |---|---| | `agent` | catalog, status, installed components, its own lease requests and leases, `exec` on its own lease | -| `operator` | everything `agent` can, plus every other requester's leases/devices, every waiting request, the worker routes, event replay/stream, and releasing any lease | +| `operator` | everything `agent` can, plus every other requester's leases/devices, the worker routes, event replay/stream, and releasing any lease | | `worker` | open an uplink at [`/v1/uplink`](#get-v1uplink-websocket-upgrade), and nothing else | A valid token with the wrong role for a route is `403 FORBIDDEN`, not `401` — @@ -1144,8 +1144,7 @@ worker's, and the two event routes carry the workers' republished events #### `GET /v1/lease-requests` Every request still waiting for a device, oldest first, whoever sent it. An -`agent` token gets `403 FORBIDDEN`: an agent reads back only its own request, -with [`GET /v1/lease-requests/{id}`](#get-v1lease-requestsid). +`agent` token gets `403 FORBIDDEN`. ```json { "requests": [ diff --git a/e2e/console/waiting.spec.ts b/e2e/console/waiting.spec.ts index 14c4d30e0..2e6557ced 100644 --- a/e2e/console/waiting.spec.ts +++ b/e2e/console/waiting.spec.ts @@ -117,31 +117,24 @@ test.describe("the Waiting view", () => { }, driverScript: { ios: IOS }, }); - // A local agent on the worker takes its one device, and a second one waits in the - // worker's own queue. A fleet request for a model no worker lists waits in the gateway's. + // A local agent on the worker takes the fleet's one device, and a second one waits in the + // worker's own queue. A further lease through the gateway then waits in the gateway's. await holdTheDevice(worker, "local-a"); worker.cliBackground([...LEASE, "--agent-id", "local-b"]); - gateway.cliBackground([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 99", - "--agent-id", - "fleet-c", - ]); - await untilTheDaemonSays( - gateway, - (requests) => - requests.some((request) => request.requesterId === "fleet-c") && - requests.some((request) => request.requesterId === "local-b"), + await untilTheDaemonSays(gateway, (requests) => + requests.some((request) => request.requesterId === "local-b"), + ); + gateway.cliBackground([...LEASE, "--agent-id", "fleet-c"]); + await untilTheDaemonSays(gateway, (requests) => + requests.some((request) => request.requesterId === "fleet-c"), ); await openWaiting(page, gateway); await expect(cell(row(page, "local-b"), "Worker")).toHaveText("worker-a"); await expect(cell(row(page, "local-b"), "Place in queue")).toHaveText("1"); - await expect(cell(row(page, "fleet-c"), "Device")).toHaveText("iOS iPhone 99"); + await expect(cell(row(page, "fleet-c"), "Device")).toHaveText("iOS iPhone 16, runtime 18.4"); + await expect(cell(row(page, "fleet-c"), "Stage")).toHaveText("queued"); await expect(cell(row(page, "fleet-c"), "Place in queue")).toHaveText("1"); await expect(cell(row(page, "fleet-c"), "Worker")).toHaveText("—"); } finally { diff --git a/ui/src/views/waiting-model.ts b/ui/src/views/waiting-model.ts index 2ca41ccc2..5f05c388e 100644 --- a/ui/src/views/waiting-model.ts +++ b/ui/src/views/waiting-model.ts @@ -31,8 +31,12 @@ export function requestedDevice(spec: WaitingRequest["spec"]): string { /** * The worker whose own queue a request waits in: the one it names, or on a single host the one - * worker whose view lists it. `undefined` for a request in a gateway's queue, which no worker - * holds yet, and for a worker the console has no view of. + * worker, the host itself, whose view lists the same request. `undefined` for a request in a + * gateway's queue, which no worker holds yet, and for a worker the console has no view of. + * + * A single host names no worker on its requests, so the request is found in the host's view by + * its id and requester. A gateway's own request never matches a worker's: its id comes from the + * gateway, and a worker lists the copy the gateway sent it under the gateway's requester id. */ export function waitingOn( request: WaitingRequest, @@ -41,5 +45,9 @@ export function waitingOn( if (request.workerId !== undefined) { return workers.find((worker) => worker.id === request.workerId); } - return workers.find((worker) => worker.waiting?.some((entry) => entry.id === request.id)); + return workers.find((worker) => + worker.waiting?.some( + (entry) => entry.id === request.id && entry.requesterId === request.requesterId, + ), + ); } diff --git a/ui/src/views/waiting.test.tsx b/ui/src/views/waiting.test.tsx index 53d4b173c..2a00e91b4 100644 --- a/ui/src/views/waiting.test.tsx +++ b/ui/src/views/waiting.test.tsx @@ -54,13 +54,16 @@ describe("the Waiting view", () => { ).toBe("Android Pixel 8, runtime 35, mode slim, image tag google_apis"); }); - it("names the worker a request waits on: by its workerId, or on a single host the worker whose view lists it", () => { + it("names the worker a request waits on: by its workerId, or on a single host the worker whose view lists the same request", () => { const onGateway = request({ id: "req_w", workerId: "wrk_2" }); const onHost = request({ id: "req_h" }); const inFleetQueue = request({ id: "req_f", requesterId: "fleet-agent" }); + // The copy a gateway sent worker-b, under the gateway's requester id: never the same request, + // even under the same id. + const sentOn = request({ id: "req_f", requesterId: "gw:gateway-1:fleet-agent" }); const workers = [ worker({ id: "wrk_1", label: "host", waiting: [onHost] }), - worker({ id: "wrk_2", label: "worker-b" }), + worker({ id: "wrk_2", label: "worker-b", waiting: [sentOn] }), ]; const html = renderToStaticMarkup( From dae72223ce328e2641da0efe91a28c3828e84bc5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 22:53:55 +0200 Subject: [PATCH 3/4] fix(core,contract,cli,docs): answer the code review --- docs/CLIENT.md | 22 ++++++++++++ src/cli/index.test.ts | 62 ++++++++++++++++++++++++++++++++++ src/contract/schemas.ts | 10 +++--- src/core/lease-request-book.ts | 9 ++--- src/core/wait-queue.test.ts | 27 +++++++++++++++ 5 files changed, 121 insertions(+), 9 deletions(-) diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 4668a3440..d76cde08b 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -470,6 +470,28 @@ const { installs = [] } = await client.getStatus(); its entry in `workers` and on `listWorkers()`, beside its `downloads.timeoutMs`. +## What is waiting: `getStatus().waiting` + +`getStatus()` lists the requests waiting for a device in the daemon's own +queue, oldest first: + +```ts +const { waiting = [] } = await client.getStatus(); +// [{ id: "req_7", requesterId: "agent-b", spec: { platform: "ios", model: "iPhone 16" }, +// createdAt: 1790864071200, stage: "queued", queuePosition: 1 }] +``` + +- `stage` is `queued` while the request holds a place in the queue, with + `queuePosition` counting from 1, and `starting` while a device is being + found, created, booted or downloaded for it. `spec` has only the fields the + request named. +- A request leaves the list as soon as it is granted, fails or is cancelled. + The field is absent only from an older daemon. +- On a gateway the list is the gateway's own queue. Each worker's own is on + its entry in `workers` and on `listWorkers()`. The admin client's + `list({ kind: "requests" })` lists both, each worker's entries with their + `workerId`, the same list as `GET /v1/lease-requests`. + ## One connection, no reconnect, no retry This is the one thing to internalize before building anything on top of this diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index c10a4e337..29153c744 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -4916,3 +4916,65 @@ function testConfig(): Config { }, }; } + +describe("simlock list --requests", () => { + it("prints a starting request without a place in the queue, and one on a worker with that worker", async () => { + const output = outputCapture(); + const asked: unknown[] = []; + const client = fakeClient({ + list: async (input) => { + asked.push(input); + return [ + { + createdAt: -12_000, + id: "req_1", + requesterId: "agent-b", + spec: { imageTag: "google_apis", model: "Pixel 8", platform: "android" }, + stage: "starting", + }, + { + createdAt: -3_400, + id: "req_2", + queuePosition: 2, + requesterId: "local-agent", + spec: { model: "iPhone 16", osVersion: "18.4", platform: "ios" }, + stage: "queued", + workerId: "wrk_1", + }, + ]; + }, + }); + + await expect( + runCli(["list", "--requests"], output.environmentWith({ connectAdmin: async () => client })), + ).resolves.toBe(0); + + expect(asked).toEqual([{ kind: "requests" }]); + expect(output.stdout).toBe( + "Request req_1: agent-b, android Pixel 8 image tag google_apis, starting, waiting 12s\n" + + "Request req_2: local-agent on wrk_1, ios iPhone 16 18.4, queued at 2, waiting 3s\n", + ); + }); + + it.each([["--devices"], ["--leases"], ["--rules"]])( + "exits 2 with USAGE for --requests beside %s, without asking the daemon", + async (other) => { + const output = outputCapture(); + let listed = 0; + const client = fakeClient({ + list: () => { + listed += 1; + return Promise.resolve([]); + }, + }); + + await expect( + runCli( + ["list", "--requests", other], + output.environmentWith({ connectAdmin: async () => client }), + ), + ).resolves.toBe(2); + expect(listed).toBe(0); + }, + ); +}); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 4f0293cd4..8513188ae 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -236,11 +236,6 @@ export const leaseGrantSchema = z.object({ timing: leaseTimingSchema, }); -/** - * One stored lease request (`LeaseRequestRecord`, src/core/domain.ts): the shape a frontend reads - * a request back in, whichever frontend sent it. `grant` is the grant the request was answered - * with, stored as granted -- a later renew does not move its `ttlDeadline`. - */ /** The device a lease request named, with every field it left out left out. */ const requestedDeviceSchema = z.object({ platform: platformSchema, @@ -250,6 +245,11 @@ const requestedDeviceSchema = z.object({ imageTag: imageTagSchema.optional(), }); +/** + * One stored lease request (`LeaseRequestRecord`, src/core/domain.ts): the shape a frontend reads + * a request back in, whichever frontend sent it. `grant` is the grant the request was answered + * with, stored as granted -- a later renew does not move its `ttlDeadline`. + */ export const leaseRequestRecordSchema = z.object({ id: z.string(), requesterId: z.string(), diff --git a/src/core/lease-request-book.ts b/src/core/lease-request-book.ts index 6a3cf3a9e..d78e1fe9f 100644 --- a/src/core/lease-request-book.ts +++ b/src/core/lease-request-book.ts @@ -390,15 +390,16 @@ export class LeaseRequestBook [place.id, place])); return this.options.store.leaseRequests().flatMap((record) => { const place = byId.get(record.id); - return isSettled(record) || place === undefined ? [] : [waitingRequest(record, place)]; + return place === undefined ? [] : [waitingRequest(record, place)]; }); } diff --git a/src/core/wait-queue.test.ts b/src/core/wait-queue.test.ts index 3aae5e859..85f7f0583 100644 --- a/src/core/wait-queue.test.ts +++ b/src/core/wait-queue.test.ts @@ -90,6 +90,33 @@ describe("WaitQueue", () => { expect(third.state).toBe("queued"); }); + it("places a queued waiter by its index in the queue, counting the waiters ahead that are already being worked on", async () => { + const { queue } = createQueue(); + const starting = createWaiter(queue, "starting"); + const second = createWaiter(queue, "second"); + const third = createWaiter(queue, "third"); + const unqueued = createWaiter(queue, "unqueued"); + for (const waiter of [starting, second, third]) queue.enqueue(waiter); + queue.markProcessing(starting); + queue.markProcessing(unqueued); + + expect(queue.places()).toEqual([ + { id: starting.id }, + { id: second.id, queuePosition: 2 }, + { id: third.id, queuePosition: 3 }, + { id: unqueued.id }, + ]); + + // The waiter ahead is granted: the ones behind it move up, and a settled one is gone. + queue.resolve(starting, grant()); + await starting.promise; + expect(queue.places()).toEqual([ + { id: second.id, queuePosition: 1 }, + { id: third.id, queuePosition: 2 }, + { id: unqueued.id }, + ]); + }); + it("tracks pending requesters and rejects duplicate requesters", async () => { const { queue } = createQueue(); const waiter = createWaiter(queue, "agent"); From b311f1752885584dbe69bcfd9392dbdf60ba2bc6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 23:08:20 +0200 Subject: [PATCH 4/4] fix(gateway,core,cli,docs,e2e): answer the second round of review findings --- docs/CLI.md | 5 ++-- docs/CLIENT.md | 5 ++-- docs/CONSOLE.md | 2 +- docs/HTTP-API.md | 4 +-- e2e/console/waiting.spec.ts | 6 +++- e2e/waiting-requests.test.ts | 46 ++++++++++++++--------------- src/cli/index.test.ts | 18 +++++++++-- src/contract/schemas.ts | 5 ++-- src/core/lease-request-book.test.ts | 34 +++++++++++++++++++++ src/core/lease-request-book.ts | 4 +-- src/gateway/dispatcher.ts | 8 ++--- src/gateway/lease-index.ts | 8 ++++- ui/src/views/waiting.test.tsx | 3 ++ 13 files changed, 106 insertions(+), 42 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index bc3e93313..eeb2f78c1 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1161,8 +1161,9 @@ Request req_9: local-agent on 2b026432-7743-4a08-98fc-ce494d11866f, ios iPhone 1 Each line names the request, the agent that sent it, the device it asked for (only the fields it named), where it stands, and how long it has waited. `queued at 2` is its place in the queue, counting from 1, the requests ahead -of it that are already starting included. `starting` means a device is being -found, created, booted or downloaded for it. With nothing waiting it prints +of it that are already starting included. `starting` means the daemon is working +on it: placing it as it arrives, or finding, creating, booting or downloading +a device for it. With nothing waiting it prints `No requests are waiting.` A granted, failed or cancelled request is not listed. diff --git a/docs/CLIENT.md b/docs/CLIENT.md index d76cde08b..cf7637fe8 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -482,8 +482,9 @@ const { waiting = [] } = await client.getStatus(); ``` - `stage` is `queued` while the request holds a place in the queue, with - `queuePosition` counting from 1, and `starting` while a device is being - found, created, booted or downloaded for it. `spec` has only the fields the + `queuePosition` counting from 1, and `starting` while the daemon is + working on it: placing it as it arrives, or finding, creating, booting or + downloading a device for it. `spec` has only the fields the request named. - A request leaves the list as soon as it is granted, fails or is cancelled. The field is absent only from an older daemon. diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index c64876aa2..6dd7699df 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -135,7 +135,7 @@ single host" in place of its content. | Requester | The agent that asked | | Device | The platform and model it asked for, and the runtime, mode and image tag when it named them | | Worker | The worker whose own queue it waits in, or `—` for a request in a gateway's queue | -| Stage | `queued` while it waits its turn, `starting` while a device is being found, created, booted or downloaded for it | +| Stage | `queued` while it waits its turn, `starting` while the daemon is working on it: placing it as it arrives, or finding, creating, booting or downloading a device for it | | Place in queue | Where it stands, counting from 1, the requests ahead of it that are already starting included; `—` while starting | | Waiting for | How long since the daemon received it | diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 9d0f29a83..16d1a8b27 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1162,8 +1162,8 @@ Every request still waiting for a device, oldest first, whoever sent it. An - `createdAt` is when the daemon holding the request received it, in milliseconds since the epoch. - `stage` is `queued` while the request holds a place in the queue, and - `starting` while a device is being found, created, booted or downloaded for - it. + `starting` while the daemon is working on it: placing it as it arrives, or + finding, creating, booting or downloading a device for it. - `queuePosition` is set only while `queued`: its place in the queue counting from 1, the requests ahead of it that are already starting included. It is the request's place now, not the one its `queued` progress first reported. diff --git a/e2e/console/waiting.spec.ts b/e2e/console/waiting.spec.ts index 2e6557ced..dc60a5bf5 100644 --- a/e2e/console/waiting.spec.ts +++ b/e2e/console/waiting.spec.ts @@ -147,12 +147,16 @@ test.describe("the Waiting view", () => { const host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); try { const held = await holdTheDevice(host, "holder"); - host.cliBackground([...LEASE, "--agent-id", "agent-b"]); + const waiter = host.cliBackground([...LEASE, "--agent-id", "agent-b"]); await untilTheDaemonSays(host, (requests) => requests.length === 1); await openWaiting(page, host); await expect(row(page, "agent-b")).toBeVisible(); expect((await host.cli(["release", held])).code).toBe(0); + const grant = JSON.parse(await waiter.firstStdoutLine(10_000)) as { + lease: { requesterId: string }; + }; + expect(grant.lease.requesterId).toBe("agent-b"); await untilTheDaemonSays(host, (requests) => requests.length === 0); await expect(row(page, "agent-b")).toHaveCount(0, { timeout: 1_000 }); diff --git a/e2e/waiting-requests.test.ts b/e2e/waiting-requests.test.ts index 29170c6e9..78ac21960 100644 --- a/e2e/waiting-requests.test.ts +++ b/e2e/waiting-requests.test.ts @@ -12,19 +12,25 @@ const LEASE = ["lease", "--platform", "ios", "--device", "iPhone 16", "--os", "1 /** One iOS device and no more, so a second request waits. */ const ONE_DEVICE = { ios: { maxDevices: 1, maxRunning: 1 }, maxRunning: 1 }; -/** The lines `simlock list --requests` prints, once there are `count` of them. */ -async function requestLines(env: TestEnv, count: number): Promise { +/** + * Waits until `simlock list --requests` prints exactly one line per pattern, each matching its + * own. A request that has just arrived is listed as `starting` until the daemon has placed it, + * so a line is read again until it settles. + */ +async function untilListed(env: TestEnv, patterns: readonly RegExp[]): Promise { let lines: string[] = []; await waitFor( async () => { const listed = await env.cli(["list", "--requests"]); expect(listed.code, listed.stderr).toBe(0); lines = listed.stdout.trimEnd().split("\n"); - return lines.length === count && lines.every((line) => line.startsWith("Request ")); + return ( + lines.length === patterns.length && + patterns.every((pattern, index) => pattern.test(lines[index] ?? "")) + ); }, - { label: `${String(count)} waiting request lines` }, + { label: "the waiting request lines" }, ); - return lines; } describe("simlock list --requests", () => { @@ -37,17 +43,15 @@ describe("simlock list --requests", () => { const empty = await env.cli(["list", "--requests"]); expect(empty.stdout).toBe("No requests are waiting.\n"); + const b = /^Request \S+: agent-b, ios iPhone 16 18\.4, queued at 1, waiting \d+s$/; env.cliBackground([...LEASE, "--agent-id", "agent-b"]); - await requestLines(env, 1); + await untilListed(env, [b]); env.cliBackground([...LEASE, "--agent-id", "agent-c", "--mode", "slim"]); - const lines = await requestLines(env, 2); - expect(lines[0]).toMatch( - /^Request \S+: agent-b, ios iPhone 16 18\.4, queued at 1, waiting \d+s$/, - ); - expect(lines[1]).toMatch( + await untilListed(env, [ + b, /^Request \S+: agent-c, ios iPhone 16 18\.4 mode slim, queued at 2, waiting \d+s$/, - ); + ]); }); it("on a gateway, lists the fleet queue and a request in a worker's own queue with that worker", async () => { @@ -84,19 +88,15 @@ describe("simlock list --requests", () => { // own queue. A fleet request then waits in the gateway's. expect((await worker.cli([...LEASE, "--agent-id", "local-a", "--detach"])).code).toBe(0); worker.cliBackground([...LEASE, "--agent-id", "local-b"]); - await requestLines(worker, 1); + await untilListed(worker, [ + /^Request \S+: local-b, ios iPhone 16 18\.4, queued at 1, waiting \d+s$/, + ]); gateway.cliBackground([...LEASE, "--agent-id", "fleet-c"]); - const lines = await requestLines(gateway, 2); - - expect(lines).toEqual([ - expect.stringMatching( - /^Request \S+: fleet-c, ios iPhone 16 18\.4, queued at 1, waiting \d+s$/, - ), - expect.stringMatching( - new RegExp( - `^Request \\S+: local-b on ${workerId}, ios iPhone 16 18\\.4, queued at 1, waiting \\d+s$`, - ), + await untilListed(gateway, [ + /^Request \S+: fleet-c, ios iPhone 16 18\.4, queued at 1, waiting \d+s$/, + new RegExp( + `^Request \\S+: local-b on ${workerId}, ios iPhone 16 18\\.4, queued at 1, waiting \\d+s$`, ), ]); }); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 29153c744..feb243a9f 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -4918,7 +4918,7 @@ function testConfig(): Config { } describe("simlock list --requests", () => { - it("prints a starting request without a place in the queue, and one on a worker with that worker", async () => { + it("prints a starting request without a place in the queue, one on a worker with that worker, and a future timestamp as waiting 0s", async () => { const output = outputCapture(); const asked: unknown[] = []; const client = fakeClient({ @@ -4941,6 +4941,16 @@ describe("simlock list --requests", () => { stage: "queued", workerId: "wrk_1", }, + { + // Stamped by a worker whose clock runs ahead of this one. + createdAt: 5_000, + id: "req_3", + queuePosition: 1, + requesterId: "skewed-agent", + spec: { model: "iPhone 16", platform: "ios" }, + stage: "queued", + workerId: "wrk_2", + }, ]; }, }); @@ -4952,7 +4962,8 @@ describe("simlock list --requests", () => { expect(asked).toEqual([{ kind: "requests" }]); expect(output.stdout).toBe( "Request req_1: agent-b, android Pixel 8 image tag google_apis, starting, waiting 12s\n" + - "Request req_2: local-agent on wrk_1, ios iPhone 16 18.4, queued at 2, waiting 3s\n", + "Request req_2: local-agent on wrk_1, ios iPhone 16 18.4, queued at 2, waiting 3s\n" + + "Request req_3: skewed-agent on wrk_2, ios iPhone 16, queued at 1, waiting 0s\n", ); }); @@ -4975,6 +4986,9 @@ describe("simlock list --requests", () => { ), ).resolves.toBe(2); expect(listed).toBe(0); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toMatchObject({ + error: { code: "USAGE" }, + }); }, ); }); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 8513188ae..eeec54e83 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -266,8 +266,9 @@ export const leaseRequestRecordSchema = z.object({ /** * A request still waiting for a device (`list.get` with `requests`, `status.get`'s `waiting`). * `stage` is `queued` while the request holds a place in the queue, with that place in - * `queuePosition`, counted from 1 the way `lease.queued` counts it; `starting` while a device is - * being found, made, booted or downloaded for it. `workerId` names the worker whose own queue + * `queuePosition`, counted from 1 the way `lease.queued` counts it; `starting` while the daemon is + * working on it: placing it as it arrives, or finding, making, booting or downloading a device + * for it. `workerId` names the worker whose own queue * the request waits in; only a gateway sets it. The request's idempotency key and owner are * never part of it: a key lets its holder replay the request, and neither is the operator's. */ diff --git a/src/core/lease-request-book.test.ts b/src/core/lease-request-book.test.ts index 509a5bb65..fd42275c6 100644 --- a/src/core/lease-request-book.test.ts +++ b/src/core/lease-request-book.test.ts @@ -394,6 +394,40 @@ describe("LeaseRequestBook", () => { expect(() => book.replay(different, keyed)).toThrow(IdempotencyConflictError); }); + it("lists an open request only while a wait drives it, never one left open with nothing behind it", async () => { + const store = memoryStore(); + const book = bookOver(store); + // An open record no wait drives, as a restarted daemon finds one before settling it. + const orphan = await store.createLeaseRequest({ + ownerId: "agent", + request, + requesterId: "lost", + }); + const { id } = await book.admit(request, keyed, () => ({ promise: new Promise(() => {}) })); + + expect(book.waiting([{ id: orphan.id }, { id, queuePosition: 1 }])).toEqual([ + { createdAt: 1_000, id: orphan.id, requesterId: "lost", spec: request, stage: "starting" }, + { + createdAt: 1_000, + id, + queuePosition: 1, + requesterId: "agent", + spec: request, + stage: "queued", + }, + ]); + expect(book.waiting([{ id, queuePosition: 1 }])).toEqual([ + { + createdAt: 1_000, + id, + queuePosition: 1, + requesterId: "agent", + spec: request, + stage: "queued", + }, + ]); + }); + it("replays a repeat naming the same mode", async () => { const book = bookOver(memoryStore()); await book.admit({ ...request, mode: "slim" }, keyed, () => granted("lse_1")); diff --git a/src/core/lease-request-book.ts b/src/core/lease-request-book.ts index d78e1fe9f..023089d5a 100644 --- a/src/core/lease-request-book.ts +++ b/src/core/lease-request-book.ts @@ -156,8 +156,8 @@ export class InMemoryLeaseRequestStore implements LeaseRequestStore; /** #118: read-only access for `lease.list`/`list.get`/`status.get`'s lease projection * (`FleetLeaseIndex#project`/`#all`) -- kept separate from `coordinator` because this - * dispatcher only ever *reads* it, never mutates it. `requesterPrefix` marks the requests + * dispatcher only ever *reads* it, never mutates it. `isGatewayRequester` marks the requests * this gateway sent a worker, which `list.get`'s `requests` already lists as its own. */ - readonly leaseIndex: Pick; + readonly leaseIndex: Pick; } export class GatewayDispatcher { @@ -382,12 +382,12 @@ export class GatewayDispatcher { * §27); the gateway already lists that request, so the worker's copy is left out. */ #fleetWaiting() { - const prefix = this.options.leaseIndex.requesterPrefix; + const { leaseIndex } = this.options; const onWorkers = this.options.workers .views() .flatMap((view) => (view.waiting ?? []) - .filter((request) => !request.requesterId.startsWith(prefix)) + .filter((request) => !leaseIndex.isGatewayRequester(request.requesterId)) .map((request) => ({ ...request, workerId: view.id })), ); return [...this.options.coordinator.waitingRequests(), ...onWorkers]; diff --git a/src/gateway/lease-index.ts b/src/gateway/lease-index.ts index 0f9407d70..e75f9dcb9 100644 --- a/src/gateway/lease-index.ts +++ b/src/gateway/lease-index.ts @@ -93,6 +93,12 @@ export class FleetLeaseIndex { return this.gatewayRequesterPrefix; } + /** Whether a worker-reported requester id is one this gateway sent (§14/§27): the one place + * the gateway answers that, for its leases and for the requests waiting on its workers. */ + isGatewayRequester(requesterId: string): boolean { + return requesterId.startsWith(this.gatewayRequesterPrefix); + } + /** Every entry, for `lease.release-all` (§34's own-leases-only filter) and for a caller * reconciling worker ids that disappeared entirely (`forgetWorker`). */ all(): readonly FleetLeaseEntry[] { @@ -209,7 +215,7 @@ export class FleetLeaseIndex { #addReported(workerId: string, leases: readonly WorkerReportedLease[]): ReadonlySet { const reported = new Set(); for (const lease of leases) { - if (!lease.requesterId.startsWith(this.gatewayRequesterPrefix)) continue; + if (!this.isGatewayRequester(lease.requesterId)) continue; const gatewayLeaseId = `${workerId}.${lease.id}`; reported.add(gatewayLeaseId); this.#missingSince.delete(gatewayLeaseId); diff --git a/ui/src/views/waiting.test.tsx b/ui/src/views/waiting.test.tsx index 2a00e91b4..496d96c1d 100644 --- a/ui/src/views/waiting.test.tsx +++ b/ui/src/views/waiting.test.tsx @@ -61,9 +61,12 @@ describe("the Waiting view", () => { // The copy a gateway sent worker-b, under the gateway's requester id: never the same request, // even under the same id. const sentOn = request({ id: "req_f", requesterId: "gw:gateway-1:fleet-agent" }); + // Another request from the same requester, under another id: not this one either. + const another = request({ id: "req_x", requesterId: "fleet-agent" }); const workers = [ worker({ id: "wrk_1", label: "host", waiting: [onHost] }), worker({ id: "wrk_2", label: "worker-b", waiting: [sentOn] }), + worker({ id: "wrk_3", label: "worker-c", waiting: [another] }), ]; const html = renderToStaticMarkup(