From c90819714c5878dbd62ccdef5bf9132179b2f32e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 18:44:31 +0200 Subject: [PATCH 1/6] =?UTF-8?q?test:=20reproduce=20#186=20=E2=80=94=20GET?= =?UTF-8?q?=20/v1/leases/{id}=20on=20a=20gateway=20serves=20the=20lease=20?= =?UTF-8?q?it=20granted=20over=20HTTP,=20naming=20its=20worker?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- e2e/gateway-smoke.test.ts | 68 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/e2e/gateway-smoke.test.ts b/e2e/gateway-smoke.test.ts index 03fb76964..4370dc445 100644 --- a/e2e/gateway-smoke.test.ts +++ b/e2e/gateway-smoke.test.ts @@ -338,6 +338,74 @@ describe("gateway smoke", () => { await fetch(`${baseUrl}/v1/leases/${leaseId}`, { headers: auth, method: "DELETE" }); }); + + // #186: the gateway issued this lease and still holds it, so its single-lease read answers it + // rather than `404 UNKNOWN_LEASE`, in the shape `docs/HTTP-API.md` gives a gateway lease: the + // lease the request resource reports, plus `workerId`/`worker` naming the machine it lives on. + it("serves GET /v1/leases/{id} for a lease the gateway granted over HTTP: the granted lease, naming its worker (#186)", async () => { + const { baseUrl, gateway } = await startFleet( + [{ label: "worker-a", models: ["Pixel 8"] }], + "smoke-agent", + ); + const auth = await agentAuth(gateway); + await waitFor( + async () => { + try { + return (await fetch(`${baseUrl}/v1/healthz`)).ok; + } catch { + return false; + } + }, + { label: "the gateway's HTTP port accepting connections" }, + ); + + const created = await fetch(`${baseUrl}/v1/lease-requests`, { + body: JSON.stringify({ device: "Pixel 8", platform: "android" }), + headers: auth, + method: "POST", + }); + expect(created.status).toBe(201); + const requestId = ((await created.json()) as { request: { id: string } }).request.id; + + let grantedLease: { id: string } | undefined; + await waitFor( + async () => { + const polled = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, { + headers: auth, + }); + const view = (await polled.json()) as { + request: { state: string; lease?: { id: string } }; + }; + grantedLease = view.request.lease; + return view.request.state === "granted"; + }, + { label: "the fleet granted the lease request", timeout: 30_000 }, + ); + if (grantedLease === undefined) + throw new Error("expected the granted request to carry a lease"); + + const listed = await gateway.cli(["worker", "list", "--json"]); + expect(listed.code).toBe(0); + const workerA = (listed.json as { workers: WorkerView[] }).workers.find( + (view) => view.label === "worker-a", + ); + if (workerA === undefined) throw new Error("expected worker-a in the gateway's worker list"); + + const fetched = await fetch(`${baseUrl}/v1/leases/${grantedLease.id}`, { headers: auth }); + expect({ body: await fetched.json(), status: fetched.status }).toEqual({ + body: { + lease: { + ...grantedLease, + worker: { id: workerA.id, label: "worker-a" }, + workerId: workerA.id, + }, + }, + status: 200, + }); + + await fetch(`${baseUrl}/v1/leases/${grantedLease.id}`, { headers: auth, method: "DELETE" }); + }); + it("queues a fleet-wide FIFO behind a full worker, refuses --no-wait, and serves the waiter on release", async () => { // One worker that can run exactly one device, so the fleet's whole capacity is one lease. // ADR §10: the gateway keeps a single fleet-wide queue and reports the same codes and From 2e0fa45e6c136c3dd0d9aab1304c1c599102e461 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 18:56:04 +0200 Subject: [PATCH 2/6] =?UTF-8?q?test:=20reproduce=20#253=20=E2=80=94=20a=20?= =?UTF-8?q?gateway's=20lease-request=20resource=20returns=20the=20granted?= =?UTF-8?q?=20lease=20with=20workerId=20and=20worker?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- e2e/gateway-smoke.test.ts | 94 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/e2e/gateway-smoke.test.ts b/e2e/gateway-smoke.test.ts index 4370dc445..48d964e06 100644 --- a/e2e/gateway-smoke.test.ts +++ b/e2e/gateway-smoke.test.ts @@ -406,6 +406,100 @@ describe("gateway smoke", () => { await fetch(`${baseUrl}/v1/leases/${grantedLease.id}`, { headers: auth, method: "DELETE" }); }); + // #253: `docs/HTTP-API.md` ("The lease object") gives a gateway-issued lease `workerId` and + // `worker`, and the request resource embeds that object once `granted`. It is handed out in + // two places: the `201` when the grant lands before any progress, and the stored request read + // back. The first request provisions, so its `201` is not granted; it warms the device. The + // second finds that device free and is granted inside its own `201`. All three leases count. + it("returns workerId and worker on a gateway-granted lease, in POST /v1/lease-requests' 201 and in GET /v1/lease-requests/{id} (#253)", async () => { + const { baseUrl, gateway } = await startFleet( + [{ label: "worker-a", models: ["Pixel 8"] }], + "smoke-agent", + ); + const auth = await agentAuth(gateway); + await waitFor( + async () => { + try { + return (await fetch(`${baseUrl}/v1/healthz`)).ok; + } catch { + return false; + } + }, + { label: "the gateway's HTTP port accepting connections" }, + ); + + const listed = await gateway.cli(["worker", "list", "--json"]); + expect(listed.code).toBe(0); + const workerA = (listed.json as { workers: WorkerView[] }).workers.find( + (view) => view.label === "worker-a", + ); + if (workerA === undefined) throw new Error("expected worker-a in the gateway's worker list"); + + interface RequestBody { + readonly request: { + readonly id: string; + readonly state: string; + readonly lease?: Record; + }; + } + const submit = async (): Promise => { + const created = await fetch(`${baseUrl}/v1/lease-requests`, { + body: JSON.stringify({ device: "Pixel 8", platform: "android" }), + headers: auth, + method: "POST", + }); + expect(created.status).toBe(201); + return (await created.json()) as RequestBody; + }; + const readGranted = async (requestId: string): Promise => { + let body: RequestBody | undefined; + await waitFor( + async () => { + const polled = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, { + headers: auth, + }); + body = (await polled.json()) as RequestBody; + return body.request.state === "granted"; + }, + { label: "the fleet granted the lease request", timeout: 30_000 }, + ); + if (body === undefined) throw new Error("expected the granted request to be read back"); + return body; + }; + const release = async (body: RequestBody): Promise => { + const leaseId = body.request.lease?.id; + if (typeof leaseId !== "string") throw new Error("expected the granted lease to have an id"); + const released = await fetch(`${baseUrl}/v1/leases/${leaseId}`, { + headers: auth, + method: "DELETE", + }); + expect(released.status).toBe(202); + }; + + const first = await submit(); + const firstRead = await readGranted(first.request.id); + await release(firstRead); + + const second = await submit(); + const secondRead = await readGranted(second.request.id); + + const namesWorkerA = expect.objectContaining({ + worker: { id: workerA.id, label: "worker-a" }, + workerId: workerA.id, + }); + expect({ + firstRequestRead: firstRead.request.lease, + secondRequestCreated: { lease: second.request.lease, state: second.request.state }, + secondRequestRead: secondRead.request.lease, + }).toEqual({ + firstRequestRead: namesWorkerA, + secondRequestCreated: { lease: namesWorkerA, state: "granted" }, + secondRequestRead: namesWorkerA, + }); + + await release(secondRead); + }); + it("queues a fleet-wide FIFO behind a full worker, refuses --no-wait, and serves the waiter on release", async () => { // One worker that can run exactly one device, so the fleet's whole capacity is one lease. // ADR §10: the gateway keeps a single fleet-wide queue and reports the same codes and From 0e22610ed31e8eda2f6f5e19cd76fb0f5a8d7191 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 19:08:09 +0200 Subject: [PATCH 3/6] fix(http,gateway): serve GET /v1/leases/{id} on a gateway, naming the lease's worker --- src/daemon/main.ts | 13 ++++++--- src/gateway/worker-link.ts | 12 +++++++- src/gateway/worker-registry.ts | 41 +++++++++++++++++++++++++-- src/http/app.ts | 52 +++++++++++++++++++++++++--------- src/http/tracker.ts | 13 ++++++++- 5 files changed, 110 insertions(+), 21 deletions(-) diff --git a/src/daemon/main.ts b/src/daemon/main.ts index cc670f999..2e9846b66 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -759,10 +759,15 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise; +/** A worker's device in the shape a grant carries it: what `GET /v1/leases/{id}` builds a lease + * payload from. Kept beside a view, never on it, because a view is what `status.get` and + * `worker.list` show every agent, and `driverDeviceId` is only the lease holder's to see. */ +export type WorkerGrantedDevice = z.infer; + +/** What one refresh over the uplink commits: the view's fields, and the same devices in the + * grant shape. Both come from one refresh and land in one call, so a lease the view reports is + * never visible before the device it names. */ +export type WorkerRefresh = Partial & { + readonly grantedDevices?: readonly WorkerGrantedDevice[]; +}; + export interface WorkerRegistryOptions { readonly clock: Clock; readonly eventBus: EventBus; @@ -70,6 +86,9 @@ export interface WorkerRegistryOptions { export class WorkerRegistry { readonly #workers = new Map(); + /** Each worker's devices in the grant shape (see `WorkerGrantedDevice`), written only by + * `refresh` and read only through `grantedDevices`, which skips a worker with no view. */ + readonly #grantedDevices = new Map(); /** * Drained worker ids, including ids with no view yet. Kept beside the views rather than only * on them because drain outlives a view: an operator drains a machine, the machine is turned @@ -102,6 +121,21 @@ export class WorkerRegistry { return this.#workers.get(workerId); } + /** + * Every worker's devices in the grant shape, each with the `workerId` it came from: what a + * gateway's `GET /v1/leases/{id}` builds the lease payload from. Only workers that still have + * a view are listed, so a device is never served for a worker the gateway has forgotten. The + * caller matches a device by worker and id together, never by id alone. + */ + grantedDevices(): readonly (WorkerGrantedDevice & { readonly workerId: string })[] { + return this.views().flatMap((view) => + (this.#grantedDevices.get(view.id) ?? []).map((device) => ({ + ...device, + workerId: view.id, + })), + ); + } + /** * `./fleet-ports.ts`'s `FleetViews#onViewsChanged` -- #118's seam for running dispatch * whenever the fleet's queue or any worker view changes (ADR 0005 §11), without reaching into @@ -252,15 +286,17 @@ export class WorkerRegistry { * previous value standing rather than blank it. A refresh for a worker whose view is gone * (removed while a status call was in flight) is dropped rather than resurrecting it. */ - refresh(workerId: string, snapshot: Partial): void { + refresh(workerId: string, refresh: WorkerRefresh): void { const existing = this.#workers.get(workerId); if (existing === undefined) return; + const { grantedDevices, ...snapshot } = refresh; const next: WorkerView = { ...existing, ...snapshot, lastSeenAt: this.options.clock.now(), }; this.#workers.set(workerId, next); + if (grantedDevices !== undefined) this.#grantedDevices.set(workerId, grantedDevices); this.#warnOnLowerMaxTtl(existing, next); this.#notifyViewsChanged(); } @@ -455,6 +491,7 @@ export class WorkerRegistry { { clearDrain }: { clearDrain: boolean }, ): Promise { this.#workers.delete(view.id); + this.#grantedDevices.delete(view.id); if (clearDrain && this.#drained.delete(view.id)) { await this.options.drainStore?.save([...this.#drained]); } diff --git a/src/http/app.ts b/src/http/app.ts index 7ec2b18b7..ff142485e 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -24,6 +24,7 @@ import { pipeSse } from "./sse.js"; import type { TokenIdentity } from "./token-store.js"; import { buildLeasePayload, + type HttpLeaseDevice, isTerminalStage, type LeaseRequestInput, type LeaseRequestReader, @@ -31,12 +32,25 @@ import { type TrackedRequestView, } from "./tracker.js"; +/** + * The device fields the lease routes read: what a lease payload is built from, plus two that + * only one kind of daemon has. A worker's own registry record carries `state`, which `DELETE + * /v1/leases/:id` reports; a gateway holds no device state of its own and leaves it out rather + * than inventing one. A gateway's device carries the `workerId` it lives on, because a device + * id is one worker's claim and is matched only together with the lease's own `workerId`. + */ +export interface HttpRegistryDevice extends HttpLeaseDevice { + readonly state?: DeviceRecord["state"]; + readonly workerId?: string; +} + /** Minimal structural read surface -- narrower than importing the `Registry` class itself. Kept * for the one thing dispatcher operations don't hand back: a device record for a specific - * lease's `GET /v1/leases/:id` decoration (there is no per-id device operation). */ + * lease's `GET /v1/leases/:id` decoration (there is no per-id device operation). A worker + * passes its registry; a gateway passes the devices its worker views hold in the grant shape. */ export interface HttpRegistryReader { readonly snapshot: { - readonly devices: readonly DeviceRecord[]; + readonly devices: readonly HttpRegistryDevice[]; }; } @@ -344,7 +358,7 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa const identity = c.get("identity"); const session = buildHttpSession(identity); const lease = await findOwnedLease(deps, session, c.req.param("id")); - const device = findDevice(deps, lease.deviceId); + const device = findDevice(deps, lease); if (device === undefined) throw unknownLease(lease.id); // ADR 0004: `ttlMs` comes off the lease record itself, so a payload served after a daemon // restart reports the lease's real width rather than a mode default standing in for a @@ -555,13 +569,17 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa // the handler answers `UNKNOWN_LEASE`/404 for a nonexistent one, matching the socket // transport exactly -- unlike the `lease.list`-filtered `findOwnedLease`, which always // answered 404 for both cases. - const deviceId = await findLeaseDeviceId(deps, session, id); + const lease = await findLeaseForDecoration(deps, session, id); await deps.dispatch("lease.release", { leaseId: id }, session); - const device = deviceId === undefined ? undefined : findDevice(deps, deviceId); + // A gateway holds no device state, so its answer is always the `reclaiming` default. + const device = lease === undefined ? undefined : findDevice(deps, lease); return c.json( - { device: { id: deviceId ?? id, state: device?.state ?? "reclaiming" }, released: true }, + { + device: { id: lease?.deviceId ?? id, state: device?.state ?? "reclaiming" }, + released: true, + }, 202, ); }); @@ -704,17 +722,17 @@ async function findOwnedLease( return lease; } -/** Best-effort `deviceId` lookup for a lease id, scoped to what the session's `lease.list` - * would show it (own leases; admin sees all) -- used only to decorate a response after an +/** Best-effort lease lookup for a lease id, scoped to what the session's `lease.list` would + * show it (own leases; admin sees all) -- used only to decorate a response after an * authoritative dispatch has already decided whether the request is allowed. Never used to * gate access itself (see the `DELETE /v1/leases/:id` route). */ -async function findLeaseDeviceId( +async function findLeaseForDecoration( deps: HttpGatewayDeps, session: ReturnType, id: string, -): Promise { +) { const { leases } = await deps.dispatch("lease.list", {}, session); - return leases.find((candidate) => candidate.id === id)?.deviceId; + return leases.find((candidate) => candidate.id === id); } function serializeRequest( @@ -742,8 +760,16 @@ function serializeRequest( } } -function findDevice(deps: HttpGatewayDeps, id: string): DeviceRecord | undefined { - return deps.registry.snapshot.devices.find((device) => device.id === id); +/** The device a lease names. On a gateway both carry the `workerId` they came from, and a + * device matches only on the lease's own worker: a device id is that worker's claim, so another + * worker reporting the same id never answers for it. On a worker neither carries one. */ +function findDevice( + deps: HttpGatewayDeps, + lease: { readonly deviceId: string; readonly workerId?: string | undefined }, +): HttpRegistryDevice | undefined { + return deps.registry.snapshot.devices.find( + (device) => device.id === lease.deviceId && device.workerId === lease.workerId, + ); } async function parseRenewBody(c: { diff --git a/src/http/tracker.ts b/src/http/tracker.ts index 2a1ceaeb0..a19011c19 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -43,6 +43,11 @@ export interface LeasePayload { readonly mode: "slim" | "full"; /** The image tag the device was created from, on a device whose request named one. */ readonly imageTag?: string; + /** The worker a gateway-issued lease lives on, as its lease record names it. Absent from a + * worker's own lease. */ + readonly worker?: { readonly id: string; readonly label?: string | undefined }; + /** `worker.id`, flat, for the aggregate lists: present exactly when `worker` is. */ + readonly workerId?: string; } /** @@ -76,6 +81,10 @@ export function buildLeasePayload( dataPlane: null, mode: device.mode, ...(device.spec.imageTag === undefined ? {} : { imageTag: device.spec.imageTag }), + // A gateway's lease record names its worker and a worker's own never does. `workerId` is + // derived from `worker` rather than read off the record: a grant's record has no + // `workerId` field (only `lease.list`'s does), and the two must never disagree. + ...(lease.worker === undefined ? {} : { worker: lease.worker, workerId: lease.worker.id }), }; } @@ -366,7 +375,7 @@ type HttpLeaseProgress = * contract-shaped data, which need not match core's own types field for field, and this module * never imports core domain types at all -- everything it needs from a grant is these few fields. */ -interface HttpLeaseDevice { +export interface HttpLeaseDevice { readonly id: string; readonly driverDeviceId: string; readonly spec: { @@ -383,6 +392,8 @@ interface HttpLeaseRecord { readonly grantedAt: number; readonly ttlMs: number; readonly ttlDeadline: number; + /** ADR 0005 §18: set on a lease a gateway issued, naming the worker it lives on. */ + readonly worker?: { readonly id: string; readonly label?: string | undefined } | undefined; } type StoredRequest = z.infer; From 6cc2c4b02853a84343134feaff32996e22f6d573 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 19:11:06 +0200 Subject: [PATCH 4/6] fix(gateway): leave out a worker device with no driverDeviceId rather than failing the view refresh; cover the gateway's device lookup --- src/gateway/service.test.ts | 30 +++++++++++++++++++++++ src/gateway/worker-link.ts | 15 +++++++++--- src/gateway/worker-registry.test.ts | 24 ++++++++++++++++++ src/http/app.test.ts | 38 ++++++++++++++++++++++++++++- 4 files changed, 102 insertions(+), 5 deletions(-) diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index a0a0e220b..643532d22 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -188,6 +188,36 @@ describe("GatewayService", () => { await harness.service.stop(); }); + it("keeps a worker's devices in the grant shape beside its view, with driverDeviceId, leaving out one that has none", async () => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + worker.devices = [ + { + ...deviceFixture("dev_1"), + createdAt: 1, + driverData: { secret: "a driver's private blob" }, + driverDeviceId: "UDID-1", + }, + { ...deviceFixture("dev_2"), createdAt: 1, driverData: {} }, + ]; + + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.devices).toHaveLength(2)); + + expect(harness.service.workers.grantedDevices()).toEqual([ + { + driverDeviceId: "UDID-1", + id: "dev_1", + mode: "full", + spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" }, + workerId: "wrk_1", + }, + ]); + + await harness.service.stop(); + }); + it("keeps each worker device's mode in the view", async () => { const harness = fleet(); await harness.service.start(); diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index 722e81af7..4330d8062 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -23,7 +23,7 @@ import type { SimlockAdminClient } from "../admin/index.js"; import { connectSimlockAdmin } from "../admin/index.js"; import type { AcceptedUplink, Clock, IpcConnection, Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; -import type { WorkerRegistry, WorkerViewSnapshot } from "./worker-registry.js"; +import type { WorkerGrantedDevice, WorkerRegistry, WorkerViewSnapshot } from "./worker-registry.js"; /** * How long the gateway waits for one round trip to a worker before giving up on it. @@ -111,8 +111,15 @@ const viewDevicesSchema = z.array(statusDeviceSchema); /** The same `list.get` answer narrowed to the grant shape instead, which keeps `driverDeviceId` * for the lease payload a gateway serves its holder (`GET /v1/leases/{id}`). Kept off the view, - * in the registry beside it: see `WorkerGrantedDevice`. */ -const grantedDevicesSchema = z.array(grantedDeviceSchema); + * in the registry beside it: see `WorkerGrantedDevice`. `list.get`'s contract also admits a + * device without `driverDeviceId`, so one that does not parse is left out on its own rather than + * failing the view's refresh; its lease then answers `UNKNOWN_LEASE` rather than a made-up udid. */ +function grantedDevices(devices: readonly unknown[]): WorkerGrantedDevice[] { + return devices.flatMap((device) => { + const parsed = grantedDeviceSchema.safeParse(device); + return parsed.success ? [parsed.data] : []; + }); +} export class WorkerLink { readonly workerId: string; @@ -376,7 +383,7 @@ export class WorkerLink { this.options.registry.refresh(this.workerId, { ...viewStatus(status), devices: viewDevicesSchema.parse(devices), - grantedDevices: grantedDevicesSchema.parse(devices), + grantedDevices: grantedDevices(devices), version: client.daemonVersion, ...(catalog === undefined ? {} : { catalog: catalog.platforms }), ...(config === undefined ? {} : viewConfig(config)), diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index d584ecfef..a1642f9b3 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -152,6 +152,30 @@ describe("WorkerRegistry", () => { expect(workers.view("wrk_1")).toBeUndefined(); }); + it("forgets a worker's granted devices with its view, so a worker re-added under that id lists none until it refreshes", async () => { + const { workers } = registry(); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { + grantedDevices: [ + { + driverDeviceId: "UDID-1", + id: "dev_1", + mode: "full", + spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" }, + }, + ], + }); + expect(workers.grantedDevices().map(({ id, workerId }) => ({ id, workerId }))).toEqual([ + { id: "dev_1", workerId: "wrk_1" }, + ]); + + workers.disconnected("wrk_1"); + await workers.remove("wrk_1"); + workers.connected("wrk_1", undefined, "0.3.0"); + + expect(workers.grantedDevices()).toEqual([]); + }); + describe("warning on a worker's lower lease.maxTtlMs (ADR 0005 §15)", () => { it("warns once a worker's own cap is refreshed in below the gateway's", () => { const logger = new RecordingLogger(); diff --git a/src/http/app.test.ts b/src/http/app.test.ts index db7a0587b..88621cdf0 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -33,6 +33,8 @@ function buildHarness( overrides: { readonly config?: HttpGatewayDeps["config"]; readonly leaseRequests?: HttpGatewayDeps["leaseRequests"]; + /** A gateway's device reader, in place of the fake worker registry. */ + readonly registry?: HttpGatewayDeps["registry"]; } = {}, ) { const clock = new FakeClock(1_000); @@ -67,7 +69,7 @@ function buildHarness( leaseRequests: overrides.leaseRequests ?? dispatcher.requests, logger, ownerRoutedFacts, - registry, + registry: overrides.registry ?? registry, tokens, }); @@ -970,6 +972,40 @@ describe("lease routes", () => { platform: "ios", udid: "ABCD-1234", }); + expect(body.lease).not.toHaveProperty("worker"); + expect(body.lease).not.toHaveProperty("workerId"); + }); + + it("GET /v1/leases/:id on a gateway builds the lease from its own worker's device, not another worker's with the same device id", async () => { + const device = (workerId: string, udid: string) => ({ + ...makeDevice({ driverDeviceId: udid, id: "dev_1" }), + workerId, + }); + const { app, dispatcher } = buildHarness({ + registry: { + snapshot: { devices: [device("wrk_a", "UDID-A"), device("wrk_b", "UDID-B")] }, + }, + }); + dispatcher.handlers["lease.list"] = () => ({ + leases: [ + { + ...makeLease({ deviceId: "dev_1", id: "wrk_b.lse_1", ownerId: "tok_agent" }), + worker: { id: "wrk_b", label: "mac-b" }, + workerId: "wrk_b", + }, + ], + }); + + const response = await app.request("/v1/leases/wrk_b.lse_1", { headers: agentAuth }); + + expect(response.status).toBe(200); + expect(((await response.json()) as { lease: unknown }).lease).toMatchObject({ + deviceId: "dev_1", + id: "wrk_b.lse_1", + udid: "UDID-B", + worker: { id: "wrk_b", label: "mac-b" }, + workerId: "wrk_b", + }); }); it("404s an unknown lease id", async () => { From 0773288f4bfa69a9a45c9414a9889d1836bc3e57 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 19:38:15 +0200 Subject: [PATCH 5/6] test: wait for the released device before the #253 inline grant; cover per-worker granted devices and the view's narrowing --- e2e/gateway-smoke.test.ts | 16 ++++++++++++++++ src/gateway/service.test.ts | 3 +++ src/gateway/worker-registry.test.ts | 24 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/e2e/gateway-smoke.test.ts b/e2e/gateway-smoke.test.ts index 48d964e06..8c06ed980 100644 --- a/e2e/gateway-smoke.test.ts +++ b/e2e/gateway-smoke.test.ts @@ -479,6 +479,22 @@ describe("gateway smoke", () => { const first = await submit(); const firstRead = await readGranted(first.request.id); await release(firstRead); + // The release answers before the worker has reclaimed the device. The second request is + // granted inside its own `201` only once the gateway's view shows that device ready again. + await waitFor( + async () => { + const status = (await (await fetch(`${baseUrl}/v1/status`, { headers: auth })).json()) as { + devices: { state: string }[]; + leases: unknown[]; + }; + return ( + status.leases.length === 0 && + status.devices.length > 0 && + status.devices.every((device) => device.state === "ready") + ); + }, + { label: "the released device ready again in the gateway's view", timeout: 30_000 }, + ); const second = await submit(); const secondRead = await readGranted(second.request.id); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 643532d22..4558f77d3 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -205,6 +205,9 @@ describe("GatewayService", () => { await harness.join("wrk_1", worker); await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.devices).toHaveLength(2)); + for (const device of harness.service.workers.view("wrk_1")?.devices ?? []) { + expect(device).not.toHaveProperty("driverDeviceId"); + } expect(harness.service.workers.grantedDevices()).toEqual([ { driverDeviceId: "UDID-1", diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index a1642f9b3..cb286333f 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -152,6 +152,30 @@ describe("WorkerRegistry", () => { expect(workers.view("wrk_1")).toBeUndefined(); }); + it("lists each worker's granted devices under that worker's id, and keeps them through a refresh that carries none", () => { + const { workers } = registry(); + const granted = (udid: string) => ({ + driverDeviceId: udid, + id: "dev_1", + mode: "full" as const, + spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" as const }, + }); + workers.connected("wrk_a", undefined, "0.3.0"); + workers.connected("wrk_b", undefined, "0.3.0"); + workers.refresh("wrk_a", { grantedDevices: [granted("UDID-A")] }); + workers.refresh("wrk_b", { grantedDevices: [granted("UDID-B")] }); + workers.refresh("wrk_b", { queueDepth: 1 }); + + expect( + workers + .grantedDevices() + .map(({ driverDeviceId, workerId }) => ({ driverDeviceId, workerId })), + ).toEqual([ + { driverDeviceId: "UDID-A", workerId: "wrk_a" }, + { driverDeviceId: "UDID-B", workerId: "wrk_b" }, + ]); + }); + it("forgets a worker's granted devices with its view, so a worker re-added under that id lists none until it refreshes", async () => { const { workers } = registry(); workers.connected("wrk_1", undefined, "0.3.0"); From 02ea32e34811c11e4fb60c7bcddf1a85df5f9edc Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 19:58:04 +0200 Subject: [PATCH 6/6] test: prove DELETE /v1/leases/{id} reads the device state; correct comments the review found false --- e2e/gateway-smoke.test.ts | 2 +- src/gateway/worker-registry.test.ts | 2 +- src/gateway/worker-registry.ts | 9 ++++----- src/http/app.test.ts | 6 ++++-- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/e2e/gateway-smoke.test.ts b/e2e/gateway-smoke.test.ts index 8c06ed980..c877286b6 100644 --- a/e2e/gateway-smoke.test.ts +++ b/e2e/gateway-smoke.test.ts @@ -410,7 +410,7 @@ describe("gateway smoke", () => { // `worker`, and the request resource embeds that object once `granted`. It is handed out in // two places: the `201` when the grant lands before any progress, and the stored request read // back. The first request provisions, so its `201` is not granted; it warms the device. The - // second finds that device free and is granted inside its own `201`. All three leases count. + // second finds that device free and is granted inside its own `201`. All three lease objects count. it("returns workerId and worker on a gateway-granted lease, in POST /v1/lease-requests' 201 and in GET /v1/lease-requests/{id} (#253)", async () => { const { baseUrl, gateway } = await startFleet( [{ label: "worker-a", models: ["Pixel 8"] }], diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index cb286333f..6c84ae862 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -176,7 +176,7 @@ describe("WorkerRegistry", () => { ]); }); - it("forgets a worker's granted devices with its view, so a worker re-added under that id lists none until it refreshes", async () => { + it("forgets a worker's granted devices with its view, so a worker re-added under that id lists none of them", async () => { const { workers } = registry(); workers.connected("wrk_1", undefined, "0.3.0"); workers.refresh("wrk_1", { diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index 504f44081..f95af493b 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -86,8 +86,8 @@ export interface WorkerRegistryOptions { export class WorkerRegistry { readonly #workers = new Map(); - /** Each worker's devices in the grant shape (see `WorkerGrantedDevice`), written only by - * `refresh` and read only through `grantedDevices`, which skips a worker with no view. */ + /** Each worker's devices in the grant shape (see `WorkerGrantedDevice`). Set by `refresh`, + * which writes nothing for a worker with no view, and deleted with the view by `#forget`. */ readonly #grantedDevices = new Map(); /** * Drained worker ids, including ids with no view yet. Kept beside the views rather than only @@ -123,9 +123,8 @@ export class WorkerRegistry { /** * Every worker's devices in the grant shape, each with the `workerId` it came from: what a - * gateway's `GET /v1/leases/{id}` builds the lease payload from. Only workers that still have - * a view are listed, so a device is never served for a worker the gateway has forgotten. The - * caller matches a device by worker and id together, never by id alone. + * gateway's `GET /v1/leases/{id}` builds the lease payload from. Ordered by worker id, as + * `views()` is. The caller matches a device by worker and id together, never by id alone. */ grantedDevices(): readonly (WorkerGrantedDevice & { readonly workerId: string })[] { return this.views().flatMap((view) => diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 88621cdf0..f18843c81 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -1417,8 +1417,10 @@ describe("lease routes", () => { dispatcher.handlers["lease.release"] = (input) => { const leaseId = (input as { leaseId: string }).leaseId; registry.leases = registry.leases.filter((lease) => lease.id !== leaseId); + // Not `reclaiming`: that is also the route's default for a device it cannot find, so only + // another state proves the answer is read from the registry. registry.devices = registry.devices.map((device) => - device.id === "dev_1" ? { ...device, state: "reclaiming" } : device, + device.id === "dev_1" ? { ...device, state: "quarantined" } : device, ); return { leaseId }; }; @@ -1429,7 +1431,7 @@ describe("lease routes", () => { }); expect(response.status).toBe(202); expect(await response.json()).toEqual({ - device: { id: "dev_1", state: "reclaiming" }, + device: { id: "dev_1", state: "quarantined" }, released: true, }); });