From b4ad5d86a6a86221b8339c623a560f671dda5742 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 22:29:43 +0200 Subject: [PATCH 1/4] feat(ui,http,docs): the leases views, lease details and holder labels in the console GET /v1/tokens answers token.list for an operator, so the console names a lease's holder by its token's label. The Leases page lists every lease, a worker's page lists its own, and each lease opens to its details on a gateway and on a single host. Closes #273 --- docs/CONSOLE.md | 47 +++- docs/HTTP-API.md | 20 +- e2e/console/leases.spec.ts | 412 +++++++++++++++++++++++++++++++++ e2e/console/workers.spec.ts | 5 +- e2e/token-route.test.ts | 146 ++++++++++++ src/http/app.ts | 7 + ui/src/views/index.tsx | 3 +- ui/src/views/leases-model.ts | 118 ++++++++++ ui/src/views/leases.test.tsx | 167 +++++++++++++ ui/src/views/leases.tsx | 293 +++++++++++++++++++++++ ui/src/views/worker-detail.tsx | 8 +- 11 files changed, 1217 insertions(+), 9 deletions(-) create mode 100644 e2e/console/leases.spec.ts create mode 100644 e2e/token-route.test.ts create mode 100644 ui/src/views/leases-model.ts create mode 100644 ui/src/views/leases.test.tsx create mode 100644 ui/src/views/leases.tsx diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index 9bc7f5a91..291175fd8 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -9,8 +9,9 @@ The console is for people who operate Simlock. It needs an operator token. Coding agents keep using the CLI, the MCP server, the client and the HTTP API. This version has sign-in, the console's navigation (Workers, Leases, Waiting, -Attention and Events), the Workers pages, the Waiting page and the Attention -page. The other pages say "Coming soon" until their views are built. +Attention and Events), the Workers and Leases pages, the Waiting page and +the Attention page. The other pages say "Coming soon" until their views are +built. ## Turn it on @@ -115,6 +116,7 @@ Select a worker to open its page. It adds: was granted, and a device being provisioned or reclaimed on a connected worker how long that has taken so far. Other states show `—`: the daemon reports no time for them. +- **Leases**: the leases on this worker, as the Leases page shows them. - **Host**: the operating system, the CPU architecture, and the version of each platform tool, such as Xcode or the Android emulator. - **Catalog**: the models and runtimes the worker can lease. It is read again @@ -125,6 +127,47 @@ 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. +## Leases + +**Leases** lists every lease the daemon holds, as `simlock list --leases` +does. On a gateway that is every lease on every worker, including the ones a +worker granted itself. On a single host it is the host's own leases. + +Each lease shows: + +| Fact | What it says | +| --- | --- | +| Holder | Who holds the lease (see below) | +| Worker | The worker the device is on, by its label, or its id when it has none | +| Device | The device's model and id | +| Mode | `slim` or `full` | +| Image tag | The image tag the device was created from, or `—` | +| Granted | How long ago the lease was granted | +| Expires in | How long until the lease expires unless it is renewed. It counts down every second. | +| Last renewed | How long ago the lease was last renewed, or granted if it never was | + +Select a lease to open its page. It shows the same facts, the platform and +runtime, the device's UDID, and the id of the request that was granted the +lease, while the daemon still keeps it. A lease that has been released or has +expired says "Lease not found". + +### Who holds a lease + +A lease taken over the HTTP API belongs to the token that took it. The console +shows that token's label, with the token id beside it: `ci-runner-3 +tok_9f2c`. Give each agent's token a label when you create it, so you can tell +them apart: + +```sh +simlock token create --role agent --label ci-runner-3 +``` + +A token created without `--label` shows as its id alone. So does a lease +taken through the CLI or the MCP server on the host itself: it is held by the +agent id it was taken with, not by a token. On a gateway the labels are the +gateway's own tokens. A lease taken on a worker directly shows its holder's id +as that worker reports it. + ## Waiting **Waiting** lists every request waiting for a device, oldest first, as diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 5b812a04c..bb5c90d7e 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, the token records, 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` — @@ -1123,7 +1123,7 @@ take the host out of rotation or forget it. ### Operator routes -Role: `operator` for all five. +Role: `operator` for all six. An `agent` token gets `403 FORBIDDEN`. `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 @@ -1150,14 +1150,26 @@ an all-or-nothing that leaves the operator guessing. memory. - `GET /v1/events/stream` — Server-Sent Events follow of the event bus (`simlock events --follow`). +- `GET /v1/tokens` — every token this daemon knows (`simlock token list`): -On a **gateway** all five are fleet-wide, which is what makes a single + ```json + { "tokens": [ + { "id": "tok_9f2c", "role": "agent", "label": "ci-runner-3", "createdAt": 1735689600000 } + ] } + ``` + + A token's `id` is the `requesterId` on the leases it takes over HTTP, so a client can + show a lease's holder by the token's `label`. The answer never carries a + secret or a hash. `label` is absent from a token created without one. + +On a **gateway** the first 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, `/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. +`request.dispatched` facts. `/v1/tokens` lists the daemon's own tokens: on a +gateway, the gateway's, since tokens never cross machines. #### `GET /v1/lease-requests` diff --git a/e2e/console/leases.spec.ts b/e2e/console/leases.spec.ts new file mode 100644 index 000000000..ad665b5ef --- /dev/null +++ b/e2e/console/leases.spec.ts @@ -0,0 +1,412 @@ +import type { Locator, Page } from "@playwright/test"; + +import { waitFor } from "../helpers/wait.js"; +import { + disposeFleet, + expect, + type RunningDaemon, + signIn, + startDaemon, + startFleet, + test, +} from "./fixtures.js"; + +/** One lease as `simlock list --leases` prints it, as far as these tests read. */ +interface ListedLease { + readonly id: string; + readonly requesterId: string; + readonly deviceId: string; + readonly ttlDeadline: number; + readonly workerId?: string; +} + +/** A granted lease as `GET /v1/lease-requests/{id}` hands it back. */ +interface GrantedLease { + readonly id: string; + readonly requestId?: string; + readonly udid: string; + readonly device: string; + readonly mode: string; +} + +const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; + +async function listLeases(daemon: RunningDaemon): Promise { + const listed = await daemon.cli(["list", "--leases"]); + expect(listed.code, listed.stderr).toBe(0); + return listed.json as readonly ListedLease[]; +} + +/** A token created with `--label`, as an operator would make one for an agent. */ +async function labelledToken( + daemon: RunningDaemon, + label: string, +): Promise<{ readonly id: string; readonly secret: string }> { + const minted = await daemon.cli(["token", "create", "--role", "agent", "--label", label]); + expect(minted.code, minted.stderr).toBe(0); + const { secret, token } = minted.json as { secret: string; token: { id: string } }; + return { id: token.id, secret }; +} + +/** Takes a lease over HTTP with `secret`, as an agent with that token would. */ +async function leaseOverHttp( + daemon: RunningDaemon, + secret: string, + options: { readonly model?: string; readonly ttlMs?: number } = {}, +): Promise { + const headers = { Authorization: `Bearer ${secret}`, "Content-Type": "application/json" }; + const created = await fetch(new URL("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/v1/lease-requests", daemon.url), { + body: JSON.stringify({ + device: options.model ?? "iPhone 16", + os: "18.4", + platform: "ios", + ...(options.ttlMs === undefined ? {} : { ttlMs: options.ttlMs }), + }), + headers, + method: "POST", + }); + expect(created.status).toBe(201); + let request = ((await created.json()) as { request: { id: string; state: string } }).request; + const id = request.id; + for (let attempt = 0; request.state !== "granted" && attempt < 6; attempt += 1) { + const polled = await fetch(new URL(`/v1/lease-requests/${id}?wait=10`, daemon.url), { + headers, + }); + request = ((await polled.json()) as { request: typeof request }).request; + } + expect(request.state).toBe("granted"); + return (request as unknown as { lease: GrantedLease }).lease; +} + +/** Takes a lease over the local socket, as an agent on the host would: no token names it. */ +async function leaseOverSocket(daemon: RunningDaemon, agent: string, model = "iPhone 16") { + const granted = await daemon.cli([ + "lease", + "--platform", + "ios", + "--device", + model, + "--os", + "18.4", + "--detach", + "--agent-id", + agent, + ]); + expect(granted.code, granted.stderr).toBe(0); +} + +/** + * Waits, asking every 20 ms, until the daemon's own `GET /v1/leases` 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: (leases: readonly ListedLease[]) => boolean, +): Promise { + await waitFor( + async () => { + const response = await fetch(new URL("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/v1/leases", daemon.url), { + headers: { Authorization: `Bearer ${daemon.tokens.operator}` }, + }); + return predicate(((await response.json()) as { leases: ListedLease[] }).leases); + }, + { interval: 20, label: "the daemon's own lease list", timeout: 10_000 }, + ); +} + +async function openLeases(page: Page, daemon: RunningDaemon): Promise { + await page.goto(daemon.url); + await signIn(page, daemon.tokens.operator); + await expect(page.getByRole("heading", { level: 1, name: "Workers" })).toBeVisible(); + await page.getByRole("link", { name: "Leases", exact: true }).click(); + await expect(page.getByRole("heading", { level: 1, name: "Leases" })).toBeVisible(); +} + +/** A lease's row, by its id. */ +function leaseRow(page: Page, id: string): Locator { + return page.getByRole("row").filter({ has: page.getByRole("link", { name: id, exact: true }) }); +} + +/** A lease's cell in the column named `label`. */ +function leaseCell(page: Page, id: string, label: string): Locator { + return leaseRow(page, id).locator(`td[data-label="${label}"]`); +} + +/** The value beside a label in a list of facts. */ +function fact(page: Page, label: string): Locator { + return page + .locator("#main dt", { hasText: new RegExp(`^${label}$`) }) + .locator("xpath=following-sibling::dd[1]"); +} + +/** The table under a heading on a worker's page. */ +function tableUnder(page: Page, heading: string): Locator { + return page + .getByRole("heading", { level: 2, name: heading }) + .locator("xpath=following-sibling::*[1]"); +} + +async function hasHorizontalScroll(page: Page): Promise { + return page.evaluate( + () => document.documentElement.scrollWidth > document.documentElement.clientWidth, + ); +} + +test.describe("the leases views", () => { + test("every lease in simlock list --leases appears in the fleet view", async ({ page }) => { + const fleet = await startFleet([ + { driverScript: { ios: IOS }, label: "worker-a" }, + { driverScript: { ios: { ...IOS, knownModels: ["iPhone 17"] } }, label: "worker-b" }, + ]); + try { + const [workerA] = fleet.workers as [RunningDaemon]; + const ci = await labelledToken(fleet.gateway, "ci-runner-3"); + // Through the gateway with a token, through the gateway's socket, and on a worker itself. + await leaseOverHttp(fleet.gateway, ci.secret); + await leaseOverSocket(fleet.gateway, "console-e2e", "iPhone 17"); + await leaseOverSocket(workerA, "local-agent"); + await waitFor(async () => (await listLeases(fleet.gateway)).length === 3, { + label: "the gateway lists all three leases", + }); + const listed = await listLeases(fleet.gateway); + const workers = ( + (await fleet.gateway.cli(["worker", "list", "--json"])).json as { + workers: { id: string; label: string }[]; + } + ).workers; + + await openLeases(page, fleet.gateway); + + await expect(page.locator("tbody tr")).toHaveCount(listed.length); + for (const lease of listed) { + await expect(leaseRow(page, lease.id), lease.id).toBeVisible(); + const holder = lease.requesterId === ci.id ? `ci-runner-3 ${ci.id}` : lease.requesterId; + await expect(leaseCell(page, lease.id, "Holder")).toHaveText(holder); + const worker = workers.find((candidate) => candidate.id === lease.workerId); + await expect(leaseCell(page, lease.id, "Worker")).toHaveText(worker?.label ?? ""); + await expect(leaseCell(page, lease.id, "Device")).toContainText(lease.deviceId); + await expect(leaseCell(page, lease.id, "Expires in")).toHaveText(/^\d+ min( \d+ s)?$/); + } + expect(listed.map((lease) => lease.requesterId)).toContain(ci.id); + } finally { + await disposeFleet(fleet); + } + }); + + test("a lease taken with a token labelled ci-runner-3 shows ci-runner-3 as its holder", async ({ + page, + }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + const ci = await labelledToken(host, "ci-runner-3"); + const granted = await leaseOverHttp(host, ci.secret); + + await openLeases(page, host); + + await expect(leaseCell(page, granted.id, "Holder")).toHaveText(`ci-runner-3 ${ci.id}`); + } finally { + await host.dispose(); + } + }); + + test("a worker's detail lists only that worker's leases", async ({ page }) => { + const fleet = await startFleet([ + { driverScript: { ios: IOS }, label: "worker-a" }, + { driverScript: { ios: { ...IOS, knownModels: ["iPhone 17"] } }, label: "worker-b" }, + ]); + try { + await leaseOverSocket(fleet.gateway, "agent-a", "iPhone 16"); + await leaseOverSocket(fleet.gateway, "agent-b", "iPhone 17"); + await waitFor(async () => (await listLeases(fleet.gateway)).length === 2, { + label: "the gateway lists both leases", + }); + const listed = await listLeases(fleet.gateway); + const holderOf = { "worker-a": "agent-a", "worker-b": "agent-b" } as const; + + await openLeases(page, fleet.gateway); + for (const label of ["worker-a", "worker-b"] as const) { + await page.getByRole("link", { name: "Workers", exact: true }).click(); + await page.getByRole("link", { name: label, exact: true }).click(); + await expect(page.getByRole("heading", { level: 1, name: label })).toBeVisible(); + + const own = listed.filter((lease) => lease.requesterId === holderOf[label]); + expect(own).toHaveLength(1); + const rows = tableUnder(page, "Leases").locator("tbody tr"); + await expect(rows).toHaveCount(1); + await expect(rows.getByRole("link", { name: own[0]?.id ?? "", exact: true })).toBeVisible(); + } + } finally { + await disposeFleet(fleet); + } + }); + + test("a lease opens to its details on a gateway", async ({ page }) => { + const fleet = await startFleet([{ driverScript: { ios: IOS }, label: "worker-a" }]); + try { + const [workerA] = fleet.workers as [RunningDaemon]; + const ci = await labelledToken(fleet.gateway, "ci-runner-3"); + const granted = await leaseOverHttp(fleet.gateway, ci.secret); + await leaseOverSocket(workerA, "local-agent"); + await waitFor(async () => (await listLeases(fleet.gateway)).length === 2, { + label: "the gateway lists both leases", + }); + const local = (await listLeases(fleet.gateway)).find((lease) => lease.id !== granted.id); + // A lease the gateway issued names its worker in its id. + expect(granted.id).toContain("."); + + await openLeases(page, fleet.gateway); + await page.getByRole("link", { name: granted.id, exact: true }).click(); + + await expect(page.getByRole("heading", { level: 1, name: granted.id })).toBeVisible(); + await expect(fact(page, "Holder")).toHaveText(`ci-runner-3 ${ci.id}`); + await expect(fact(page, "Worker")).toHaveText("worker-a"); + await expect(fact(page, "Device")).toContainText(granted.device); + await expect(fact(page, "UDID")).toHaveText(granted.udid); + await expect(fact(page, "Mode")).toHaveText(granted.mode); + await expect(fact(page, "Request")).toHaveText(granted.requestId ?? ""); + await expect(fact(page, "Expires in")).toHaveText(/^\d+ min( \d+ s)?$/); + // The page's own address survives a reload, though the id holds a `.`. + await page.reload(); + await expect(fact(page, "UDID")).toHaveText(granted.udid); + + // A worker's own lease, which the gateway did not issue, opens too. + await page.getByRole("link", { name: "All leases" }).click(); + await page.getByRole("link", { name: local?.id ?? "", exact: true }).click(); + await expect(page.getByRole("heading", { level: 1, name: local?.id ?? "" })).toBeVisible(); + await expect(fact(page, "Holder")).toHaveText("local-agent"); + await expect(fact(page, "Worker")).toHaveText("worker-a"); + await expect(fact(page, "UDID")).not.toHaveText("—"); + } finally { + await disposeFleet(fleet); + } + }); + + test("a lease opens to its details on a single host", async ({ page }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + const ci = await labelledToken(host, "ci-runner-3"); + const granted = await leaseOverHttp(host, ci.secret); + // A single host is a fleet of one: the host itself, named by its id. + const [view] = ( + (await host.cli(["worker", "list", "--json"])).json as { workers: { id: string }[] } + ).workers; + + await openLeases(page, host); + await page.getByRole("link", { name: granted.id, exact: true }).click(); + + await expect(page.getByRole("heading", { level: 1, name: granted.id })).toBeVisible(); + await expect(fact(page, "Holder")).toHaveText(`ci-runner-3 ${ci.id}`); + await expect(fact(page, "Worker")).toHaveText(view?.id ?? ""); + await expect(fact(page, "UDID")).toHaveText(granted.udid); + await expect(fact(page, "Request")).toHaveText(granted.requestId ?? ""); + await page.reload(); + await expect(fact(page, "UDID")).toHaveText(granted.udid); + } finally { + await host.dispose(); + } + }); + + test("a released lease leaves the view within a second, without a reload", async ({ page }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + await leaseOverSocket(host, "agent-1"); + await leaseOverSocket(host, "agent-2"); + const [released, kept] = (await listLeases(host)) as [ListedLease, ListedLease]; + await openLeases(page, host); + await expect(page.locator("tbody tr")).toHaveCount(2); + + expect((await host.cli(["release", released.id])).code).toBe(0); + await untilTheDaemonSays(host, (leases) => leases.every((lease) => lease.id !== released.id)); + + await expect(leaseRow(page, released.id)).toHaveCount(0, { timeout: 1_000 }); + await expect(leaseRow(page, kept.id)).toBeVisible(); + } finally { + await host.dispose(); + } + }); + + test("a renewed lease shows its new expiry within a second", async ({ page }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + const ci = await labelledToken(host, "ci-runner-3"); + const granted = await leaseOverHttp(host, ci.secret, { ttlMs: 120_000 }); + const [before] = await listLeases(host); + await openLeases(page, host); + const expiry = leaseCell(page, granted.id, "Expires in"); + await expect(expiry).toHaveText(/^1 min \d+ s$/); + + const renewed = await fetch(new URL(`/v1/leases/${granted.id}/renew`, host.url), { + body: JSON.stringify({ ttlMs: 3_600_000 }), + headers: { Authorization: `Bearer ${ci.secret}`, "Content-Type": "application/json" }, + method: "POST", + }); + expect(renewed.status).toBe(200); + await untilTheDaemonSays(host, (leases) => + leases.some( + (lease) => lease.id === granted.id && lease.ttlDeadline > (before?.ttlDeadline ?? 0), + ), + ); + + await expect(expiry).toHaveText(/^59 min \d+ s$/, { timeout: 1_000 }); + } finally { + await host.dispose(); + } + }); + + test("the leases views have no horizontal scroll at 360px wide", async ({ page }) => { + const host = await startDaemon("worker", { driverScript: { ios: IOS } }); + try { + const ci = await labelledToken(host, "ci-runner-3"); + const granted = await leaseOverHttp(host, ci.secret); + await page.setViewportSize({ height: 740, width: 360 }); + await openLeases(page, host); + await expect(leaseRow(page, granted.id)).toBeVisible(); + expect(await hasHorizontalScroll(page)).toBe(false); + + await page.getByRole("link", { name: granted.id, exact: true }).click(); + await expect(fact(page, "UDID")).toHaveText(granted.udid); + expect(await hasHorizontalScroll(page)).toBe(false); + + await page.getByRole("link", { name: "Workers", exact: true }).click(); + await page.locator(".card").getByRole("link").click(); + await expect(tableUnder(page, "Leases").locator("tbody tr")).toHaveCount(1); + expect(await hasHorizontalScroll(page)).toBe(false); + } finally { + await host.dispose(); + } + }); + + test("the leases views are 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", { driverScript: { ios: IOS } }); + try { + const ci = await labelledToken(host, "ci-runner-3"); + const granted = await leaseOverHttp(host, ci.secret); + /** 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 < 30; 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("Leases"); + await expect(page.getByRole("heading", { level: 1, name: "Leases" })).toBeVisible(); + await follow(granted.id); + await expect(page.getByRole("heading", { level: 1, name: granted.id })).toBeVisible(); + await follow("All leases"); + await expect(page.getByRole("heading", { level: 1, name: "Leases" })).toBeVisible(); + } finally { + await host.dispose(); + } + }); +}); diff --git a/e2e/console/workers.spec.ts b/e2e/console/workers.spec.ts index 5c9c34a3e..a24f9959b 100644 --- a/e2e/console/workers.spec.ts +++ b/e2e/console/workers.spec.ts @@ -317,7 +317,10 @@ test.describe("the workers views", () => { await openConsole(page, host); await page.getByRole("link", { name: view?.id ?? "" }).click(); - await expect(page.locator("tbody tr")).toHaveCount(devices.length); + const deviceTable = page + .getByRole("heading", { level: 2, name: "Devices" }) + .locator("xpath=following-sibling::*[1]"); + await expect(deviceTable.locator("tbody tr")).toHaveCount(devices.length); for (const device of devices) { const cells = deviceRow(page, device.id).getByRole("cell"); await expect(cells.nth(1)).toHaveText(device.state); diff --git a/e2e/token-route.test.ts b/e2e/token-route.test.ts new file mode 100644 index 000000000..9a2556b5b --- /dev/null +++ b/e2e/token-route.test.ts @@ -0,0 +1,146 @@ +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; + +/** + * `GET /v1/tokens` answers `token.list` over HTTP, so the console can name a lease's holder by + * its token's label. A real daemon and a real `tokens.json`, so what is proven is what reaches + * the wire, not what a handler returns before the contract's output schema has had its say. + */ + +interface TokenRecord { + readonly id: string; + readonly role: string; + readonly label?: string; + readonly createdAt: number; +} + +interface Minted { + readonly secret: string; + readonly token: TokenRecord; +} + +interface HttpDaemon { + readonly env: TestEnv; + readonly baseUrl: string; +} + +/** A daemon in `mode` with HTTP on, once its listener answers. */ +async function httpDaemon(mode: "worker" | "gateway"): Promise { + const port = await freeLoopbackPort(); + const http = { enabled: true, host: "127.0.0.1", port }; + const env = await withDaemon( + mode === "gateway" + ? { configOverrides: { http, mode: "gateway" }, driver: "none" } + : { configOverrides: { http } }, + ); + const baseUrl = `http://127.0.0.1:${port}`; + // Any CLI call starts the daemon; the listener comes up with it. + expect((await env.cli(["status", "--json"])).code).toBe(0); + await waitFor( + async () => { + try { + return (await fetch(`${baseUrl}/v1/healthz`)).ok; + } catch { + return false; + } + }, + { label: "HTTP listener accepting connections" }, + ); + return { baseUrl, env }; +} + +async function mint(env: TestEnv, role: string, label?: string): Promise { + const minted = await env.cli([ + "token", + "create", + "--role", + role, + ...(label === undefined ? [] : ["--label", label]), + ]); + expect(minted.code, minted.stderr).toBe(0); + return minted.json as Minted; +} + +function getTokens(daemon: HttpDaemon, secret: string): Promise { + return fetch(`${daemon.baseUrl}/v1/tokens`, { headers: { authorization: `Bearer ${secret}` } }); +} + +describe("GET /v1/tokens", () => { + it("GET /v1/tokens answers every token's id, role, label and createdAt for an operator", async () => { + const daemon = await httpDaemon("worker"); + const operator = await mint(daemon.env, "operator", "console"); + const agent = await mint(daemon.env, "agent", "ci-runner-3"); + const unlabelled = await mint(daemon.env, "agent"); + const worker = await mint(daemon.env, "worker", "join"); + + const response = await getTokens(daemon, operator.secret); + + expect(response.status).toBe(200); + const body = (await response.json()) as { tokens: TokenRecord[] }; + expect(body.tokens).toHaveLength(4); + expect(body.tokens).toEqual( + expect.arrayContaining([operator.token, agent.token, unlabelled.token, worker.token]), + ); + // The records `token create` printed, and nothing beside them. + expect(agent.token).toEqual({ + createdAt: expect.any(Number), + id: expect.stringMatching(/^tok_/), + label: "ci-runner-3", + role: "agent", + }); + expect(unlabelled.token).not.toHaveProperty("label"); + }); + + it("GET /v1/tokens never answers a secret or a hash", async () => { + const daemon = await httpDaemon("worker"); + const operator = await mint(daemon.env, "operator"); + const agent = await mint(daemon.env, "agent", "ci-runner-3"); + const stored = JSON.parse(await readFile(join(daemon.env.home, "tokens.json"), "utf8")) as { + hash: string; + }[]; + expect(stored).toHaveLength(2); + + const response = await getTokens(daemon, operator.secret); + + expect(response.status).toBe(200); + const raw = await response.text(); + for (const secret of [operator.secret, agent.secret]) expect(raw).not.toContain(secret); + for (const { hash } of stored) expect(raw).not.toContain(hash); + const { tokens } = JSON.parse(raw) as { tokens: Record[] }; + expect(tokens).toHaveLength(2); + for (const token of tokens) { + for (const key of Object.keys(token)) { + expect(["createdAt", "id", "label", "role"]).toContain(key); + } + } + }); + + it("GET /v1/tokens answers 403 for an agent token", async () => { + const daemon = await httpDaemon("worker"); + const agent = await mint(daemon.env, "agent", "ci-runner-3"); + + const response = await getTokens(daemon, agent.secret); + + expect(response.status).toBe(403); + expect(((await response.json()) as { error: { code: string } }).error.code).toBe("FORBIDDEN"); + }); + + it("GET /v1/tokens works on a gateway and on a worker", async () => { + for (const mode of ["gateway", "worker"] as const) { + const daemon = await httpDaemon(mode); + const operator = await mint(daemon.env, "operator"); + const agent = await mint(daemon.env, "agent", `${mode}-agent`); + + const response = await getTokens(daemon, operator.secret); + + expect(response.status, mode).toBe(200); + const body = (await response.json()) as { tokens: TokenRecord[] }; + expect(body.tokens, mode).toEqual(expect.arrayContaining([operator.token, agent.token])); + expect(body.tokens, mode).toHaveLength(2); + } + }); +}); diff --git a/src/http/app.ts b/src/http/app.ts index 7d5d59747..64183b73f 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -599,6 +599,13 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa c.json(await deps.dispatch("lease.list", {}, buildHttpSession(c.get("identity")))), ); + // The token records, for a console to name a lease's holder by its token's label. `token.list` + // is an admin operation, so an agent token gets `FORBIDDEN`/403 from the shared dispatcher, and + // its output schema has no secret and no hash, so neither can reach the body. + app.get("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/v1/tokens", agentAuth, async (c) => + c.json(await deps.dispatch("token.list", {}, buildHttpSession(c.get("identity")))), + ); + app.get("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/v1/devices", agentAuth, async (c) => { const devices = await deps.dispatch( "list.get", diff --git a/ui/src/views/index.tsx b/ui/src/views/index.tsx index 67fb6cf91..4c1158d07 100644 --- a/ui/src/views/index.tsx +++ b/ui/src/views/index.tsx @@ -2,6 +2,7 @@ import type { ComponentType } from "react"; import { AttentionCount, AttentionView } from "./attention"; import { ComingSoon } from "./coming-soon"; +import { LeasesView } from "./leases"; import { WaitingView } from "./waiting"; import { WorkersView } from "./workers"; @@ -21,7 +22,7 @@ export interface View { export const VIEWS: readonly View[] = [ { path: "/workers", label: "Workers", Component: WorkersView }, - { path: "/leases", label: "Leases", Component: () => }, + { path: "/leases", label: "Leases", Component: LeasesView }, { path: "/waiting", label: "Waiting", Component: WaitingView }, { path: "/attention", label: "Attention", Component: AttentionView, Badge: AttentionCount }, { path: "/events", label: "Events", Component: () => }, diff --git a/ui/src/views/leases-model.ts b/ui/src/views/leases-model.ts new file mode 100644 index 000000000..02d0f49d3 --- /dev/null +++ b/ui/src/views/leases-model.ts @@ -0,0 +1,118 @@ +/** + * The facts the leases views show, computed from `GET /v1/leases`, `GET /v1/tokens`, + * `GET /v1/workers` and, for one lease, `GET /v1/leases/{id}` (ADR 0013 §1). Pure, so the views + * stay rendering and these stay tested. The types are the contract's where it has them, imported + * type-only (ADR 0011 §1); every value is still a claim, so a fact the data lacks shows as + * missing rather than guessed. + */ +import type { z } from "zod"; + +import type { statusLeaseSchema, tokenRecordSchema } from "../../../src/contract/schemas"; +import { type WorkerDevice, type WorkerView, workerName } from "./workers-model"; + +/** One lease as `GET /v1/leases` lists it. `workerId` is set on a gateway and absent on a host. */ +export type LeaseRecord = z.infer; + +export interface LeaseList { + readonly leases: readonly LeaseRecord[]; +} + +export type TokenRecord = z.infer; + +export interface TokenList { + readonly tokens: readonly TokenRecord[]; +} + +/** The fields of `GET /v1/leases/{id}`'s lease that the details page reads. */ +export interface LeaseDetails { + readonly id: string; + readonly requestId?: string; + readonly platform: string; + readonly device: string; + readonly os: string; + readonly udid: string; + readonly deviceId: string; + readonly createdAt: string; + readonly expiresAt: string; + readonly mode: string; + readonly imageTag?: string; + readonly workerId?: string; + readonly worker?: { readonly id: string; readonly label?: string }; +} + +/** Who holds a lease: its token's label when a token has the requester's id, and the id. */ +export interface Holder { + readonly id: string; + readonly label?: string; +} + +/** + * The holder of a lease taken with `requesterId`. Over HTTP a requester's id is its token's id, + * so a token with that id names it. A requester no token matches, such as an agent that leased + * over the local socket, is its id alone. + */ +export function holderOf(requesterId: string, tokens: readonly TokenRecord[]): Holder { + const label = tokens.find((token) => token.id === requesterId)?.label; + return label === undefined ? { id: requesterId } : { id: requesterId, label }; +} + +/** + * The worker a lease lives on. A gateway names it on every lease it lists; a single host names + * none, and every lease there is on its one worker, the host itself. + */ +function workerOfLease( + lease: { readonly workerId?: string | undefined }, + workers: readonly WorkerView[], +): WorkerView | undefined { + if (lease.workerId === undefined) return workers.length === 1 ? workers[0] : undefined; + return workers.find((worker) => worker.id === lease.workerId); +} + +/** The leases on one worker. On a single host no lease names a worker, and all are its own. */ +export function leasesOnWorker( + leases: readonly LeaseRecord[], + workerId: string, +): readonly LeaseRecord[] { + return leases.filter((lease) => lease.workerId === undefined || lease.workerId === workerId); +} + +/** The device a lease holds, as its worker reports it. A device id is matched on its own worker. */ +export function deviceOfLease( + lease: LeaseRecord, + workers: readonly WorkerView[], +): WorkerDevice | undefined { + return workerOfLease(lease, workers)?.devices.find((device) => device.id === lease.deviceId); +} + +/** The name of the worker a lease lives on: its label, else its id, else `undefined`. */ +export function workerNameOfLease( + lease: { + readonly workerId?: string | undefined; + readonly worker?: { readonly label?: string | undefined } | undefined; + }, + workers: readonly WorkerView[], +): string | undefined { + const worker = workerOfLease(lease, workers); + if (worker !== undefined) return workerName(worker); + return lease.worker?.label ?? lease.workerId; +} + +/** + * A lease's page. A gateway's lease id holds a `.`, and the daemon serves the console's page only + * for a path whose last segment has none, so the page's path ends in `/`: a reload, or a pasted + * link, still lands on it. + */ +export function leasePath(id: string): `/${string}` { + return `/leases/${encodeURIComponent(id)}/`; +} + +/** The lease id a page path names, or `undefined` for the list (`/leases`). */ +export function leaseIdFrom(path: string): string | undefined { + const rest = path.replace(/^\/leases\/?/, "").replace(/\/$/, ""); + if (rest === "") return undefined; + try { + return decodeURIComponent(rest); + } catch { + return rest; + } +} diff --git a/ui/src/views/leases.test.tsx b/ui/src/views/leases.test.tsx new file mode 100644 index 000000000..6ba437b75 --- /dev/null +++ b/ui/src/views/leases.test.tsx @@ -0,0 +1,167 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; + +import { LeaseFacts, LeaseTable } from "./leases"; +import { + type LeaseDetails, + leaseIdFrom, + leasePath, + type LeaseRecord, + leasesOnWorker, + type TokenRecord, +} from "./leases-model"; +import type { WorkerView } from "./workers-model"; + +const NOW = Date.parse("2026-10-02T12:00:00Z"); + +function lease(overrides: Partial = {}): LeaseRecord { + return { + deviceId: "dev_1", + grantedAt: NOW - 90_000, + id: "lse_1", + lastRenewedAt: NOW - 30_000, + ownerId: "tok_1", + requesterId: "tok_1", + ttlDeadline: NOW + 125_000, + ttlMs: 215_000, + ...overrides, + }; +} + +function token(overrides: Partial = {}): TokenRecord { + return { + createdAt: NOW - 1_000_000, + id: "tok_1", + label: "ci-runner-3", + role: "agent", + ...overrides, + }; +} + +const HOST: WorkerView = { + catalog: [], + connection: "connected", + devices: [ + { + id: "dev_1", + mode: "slim", + spec: { imageTag: "base", model: "iPhone 16", osVersion: "18.4", platform: "ios" }, + state: "leased", + }, + ], + drained: false, + id: "wrk_host", + label: "mac-mini-1", + lastSeenAt: NOW, + leases: [], +}; + +/** The text of every cell with `data-label="