From 9bc26c6343854c3b352d9bbb5e931a674819ce14 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 15:35:50 +0200 Subject: [PATCH 1/3] feat(core,contract,http,mcp): a lease request reports the downloading stage while it waits on a download LeaseProgress gains { stage: "downloading", component, waiting, percent? }. The installer tells a call its install started before the driver reports, and replays its latest report to a call that joins. The lease path maps the installer's reports to the stage, skipping repeats. --- docs/CLI.md | 17 +- docs/CLIENT.md | 27 +- docs/EVENTS.md | 3 +- docs/HTTP-API.md | 30 ++- docs/internal/ARCHITECTURE.md | 11 +- docs/internal/EVENTS.md | 4 +- docs/internal/IDEAS.md | 14 -- docs/internal/KNOWN-PITFALLS.md | 17 +- e2e/component-install.test.ts | 97 +++++++ src/contract/operations.test.ts | 31 +++ src/contract/schemas.ts | 8 + src/core/component-installer.test.ts | 79 +++++- src/core/component-installer.ts | 25 +- .../lease-acquisition-coordinator.test.ts | 237 +++++++++++++++++- src/core/lease-acquisition-coordinator.ts | 51 +++- src/core/wait-queue.ts | 11 + src/daemon/dispatcher.test.ts | 36 ++- src/daemon/dispatcher.ts | 5 +- src/daemon/server.test.ts | 5 + src/gateway/fleet-coordinator.test.ts | 22 ++ src/gateway/test-support.ts | 6 + src/http/app.test.ts | 65 +++++ src/http/app.ts | 5 + src/http/tracker.ts | 24 ++ src/mcp/server.test.ts | 69 +++++ src/mcp/server.ts | 31 ++- 26 files changed, 860 insertions(+), 70 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index d215e4352..6930c3c51 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -218,8 +218,8 @@ granted. `component.install-started` and then `component.installed` or `component.install-failed` on the event bus once, however many leases share it (`simlock events --follow`); see [EVENTS.md](EVENTS.md#components). The - requester's own progress stream (below) does not yet reflect an in-flight - download. + request's own progress stream (below) reports the download as the + `downloading` stage. - `--mode ` — the device mode this lease asks for. Without it, the lease gets the default mode of the worker that serves it (`ios.defaultMode`, `full` unless configured). `full` is a guarantee: a `full` lease never gets a @@ -338,6 +338,7 @@ reclaiming work is reported separately: ```json {"push":"progress","stage":"queued","queuePosition":1} +{"push":"progress","stage":"downloading","component":"26.4","waiting":false,"percent":41} {"push":"progress","stage":"provisioning","etaMs":90000} {"push":"progress","stage":"booting","etaMs":60000} {"push":"progress","stage":"reclaiming","etaMs":34000} @@ -346,6 +347,18 @@ reclaiming work is reported separately: `push` is the one field the CLI adds to identify the line's kind; everything else is the contract's `LeaseProgress` push, serialized as-is. +`downloading` means the request waits on a download that `--allow-download` +started or joined, before any device work. `component` names what is being +downloaded, as the platform names it: an iOS version or an Android API +level, for example. `waiting` is +`true` while another download on the same platform runs ahead of this one, +since a platform downloads one component at a time, and `false` once this +download runs. `percent`, a whole number from 0 to 100, is there when the +platform's installer printed one; it is left out at the start of a download +and for an installer that prints no percentage. A request that joins a +download already running gets the download's latest line at once. A request +that needs no download never sees this stage. + `reclaiming` follows `queued` when the device the request is waiting on is being purged for its previous holder: the position alone would not say that the wait is an iOS erase rather than a moment. Every `eta_seconds` comes from diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 03dc03641..ecee64687 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -53,6 +53,28 @@ Spotlight, StoreKit sheets, universal links, system pickers — so check it before treating such a failure as a bug. Every device in `getStatus()` and in an admin's `list({ kind: "devices" })` carries the same `mode`. +`requestLease` takes an optional `onProgress` in its second argument, called +with the request's `LeaseProgress` as it moves along: + +```ts +type LeaseProgress = + | { stage: "queued"; queuePosition: number } + | { stage: "downloading"; component: string; waiting: boolean; percent?: number } + | { stage: "provisioning"; etaMs: number } + | { stage: "booting"; etaMs: number } + | { stage: "reclaiming"; etaMs: number }; +``` + +`downloading` is a request with `allowDownload: true` waiting on the download +of a missing runtime, before any device work. `component` names what is +being downloaded, as the platform names it: an iOS version or an Android API +level, for example. `waiting` is `true` while another download on the same +platform runs ahead of this one, and `false` once this download runs. +`percent`, a whole number from 0 to 100, is there when the platform's +installer printed one. A request that joins a download already running hears +that download's latest progress at once. A request that needs no download +never hears this stage. + **Keeping the lease alive is yours to do.** Every lease is TTL-bound: it expires at `grant.lease.ttlDeadline` unless a `renewLease` call lands first, and the daemon does nothing on its own to keep it. `requestLease` takes an optional @@ -458,8 +480,9 @@ Four cases, by when the signal fires: - **While the request is still queued** — sends `lease.cancel`, waits for the original request to actually reject, then surfaces `CANCELLED` regardless of what that rejection's own code/message was. -- **While device work is already in flight** (provisioning, booting, - reclaiming) — `lease.cancel` answers `not-cancellable` at this stage; the +- **While a download or device work is already in flight** (downloading, + provisioning, booting, reclaiming) — `lease.cancel` answers + `not-cancellable` at this stage; the client waits for the request's real outcome. If a grant still lands, it is released immediately (`releaseLease`, best-effort) so the caller never ends up holding a device it already told the client it didn't want, and diff --git a/docs/EVENTS.md b/docs/EVENTS.md index bae2bc9ea..b73ab5bdd 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -65,8 +65,7 @@ putting in front of every event-bus consumer. These fire once per install, however many requests joined it. A request that needs no install emits none: one whose component turned out to be installed already, one another install made unnecessary while it waited, or one refused -for lack of disk before anything started. The requester's own progress stream -does not yet reflect an in-flight download. +for lack of disk before anything started. ## System diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 6baa841c4..6d2ddd60b 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -362,11 +362,26 @@ once `wait` elapses. `wait` is capped at 60 seconds — a larger value is clamped, not rejected, and the poll simply returns (unchanged) sooner than asked; re-poll to keep waiting. -States: `queued | reclaiming | provisioning | booting | granted | failed | -cancelled`, carrying `queuePosition` (`queued`) or `etaSeconds` -(`reclaiming`/`provisioning`/`booting`) where the stage has one. Terminal -`granted` embeds the [lease object](#the-lease-object); terminal `failed` -embeds `{ code, message }`. +States: `queued | downloading | reclaiming | provisioning | booting | +granted | failed | cancelled`, carrying `queuePosition` (`queued`) or +`etaSeconds` (`reclaiming`/`provisioning`/`booting`) where the stage has one. +Terminal `granted` embeds the [lease object](#the-lease-object); terminal +`failed` embeds `{ code, message }`. + +`downloading` is a request with `allowDownload: true` waiting on the download +of a missing runtime, before any device work: + +```json +{ "request": { "id": "req_7d1a", "state": "downloading", "component": "26.4", "waiting": false, "percent": 41, "createdAt": "2026-09-01T09:12:00Z" } } +``` + +`component` names what is being downloaded, as the platform names it: an iOS +version or an Android API level, for example. `waiting` is `true` while +another download on the same platform runs ahead of this one, and `false` +once this download runs. `percent`, a whole number from 0 to 100, is there +when the platform's installer printed one. A request that joins a download +already running shows that download's latest state at once. A request that +needs no download never shows this state. The request is the one Simlock stored, so `GET` answers across a daemon restart and for a request your token sent over the socket too. A finished @@ -377,7 +392,8 @@ the current deadline from [`GET /v1/leases/{id}`](#get-v1leasesid). ### `GET /v1/lease-requests/{id}/events` Role: `agent` (ownership as above). Server-Sent Events stream of the same -progress objects, one event per state change, ending with `granted` or +progress objects, one event per state change, named after the state +(`queued`, `downloading`, `provisioning`, ...), ending with `granted` or `failed`. A `: keepalive` comment every ~15s keeps idle tunnels from closing the stream. @@ -386,7 +402,7 @@ the stream. Role: `agent` (ownership as above). Cancel a pending request. → `204` if it was still cancellable (no device work claimed for it yet). -`409 REQUEST_NOT_CANCELLABLE` once device work is in flight, or the request +`409 REQUEST_NOT_CANCELLABLE` once a download or device work is in flight, or the request already reached a terminal state — the body names the lease id if it was `granted` (release that instead). `404 UNKNOWN_LEASE_REQUEST` if unknown. diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 3ffc6534e..e534e151a 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -1433,7 +1433,10 @@ counted together, and one that does not fit is refused with `component.install-started` and calls the driver. On `installed` it stores a `ComponentRecord` (platform, version, time, receipt) in the registry inside the decision gate, then emits `component.installed`. Progress fans out to every -joined call; a call behind another install hears `waiting`. +joined call; a call behind another install hears `waiting`. When an install +starts running, its calls hear `downloading` with no percentage before the +driver reports anything, and a call that joins a running install hears that +install's latest report at once. Every call has one budget, `downloads.timeoutMs`, measured on the `Clock` from the moment it arrives; waiting spends it and nothing restarts it (architecture @@ -1447,7 +1450,11 @@ The lease path reaches the installer directly (architecture rule 5): `LeaseAcquisitionCoordinator` resolves the spec, and when the runtime is missing, downloadable, and the request may download, calls the installer with `stillNeeded` = "`resolveSpec` still throws `RuntimeMissingError`" and resolves -once more. Without `allowDownload` the first error stands. Warm-pool +once more. The installer's reports reach the requester as the `downloading` +lease-progress stage, sent through the wait queue like every other stage: +`waiting` becomes `waiting: true`, the install's own reports `waiting: false` +with the percentage rounded down, and a report equal to the last one sent is +skipped. Without `allowDownload` the first error stands. Warm-pool re-readiness and startup convergence never reach the installer (safety rule 4). The operator path is `component.install` (ADR 0010 §6), an admin operation diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 585201ba4..ea8f2bb5f 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -94,8 +94,8 @@ reservation (`InsufficientDiskSpaceError`) emits nothing. `component.installed` the component record is committed to the registry (events rule 3); with `alreadyPresent: true` nothing was recorded (ADR 0010 §5). `requesterId` is the requester whose call started the install. See "Device requests" in [ARCHITECTURE.md](ARCHITECTURE.md) for how a missing -component gets to this point, and `docs/internal/KNOWN-PITFALLS.md` for the requester-visible -progress gap this leaves. +component gets to this point. The requester hears the install through its own `downloading` +progress stage, a direct call chain from the installer, not these events (architecture rule 5). ## System diff --git a/docs/internal/IDEAS.md b/docs/internal/IDEAS.md index 6db9a32f9..202c63778 100644 --- a/docs/internal/IDEAS.md +++ b/docs/internal/IDEAS.md @@ -67,20 +67,6 @@ pursued in v1: parsing an undocumented, Apple-controlled catalog format is a maintenance burden disproportionate to the edge case it closes (see `docs/internal/KNOWN-PITFALLS.md`, "Component downloads"). -## Requester-visible download progress - -Neither driver's install (`xcodebuild -downloadPlatform`, `sdkmanager ---install`) currently reaches the requesting connection's progress stream — -see `docs/internal/KNOWN-PITFALLS.md` ("no progress push"). Closing this needs a -`downloading` stage on `LeaseProgress` (`src/core/wait-queue.ts`) and a -`Driver.resolveSpec` progress callback both drivers implement, threaded -through `LeaseAcquisitionCoordinator#resolveAndDrive` the same way -`provision`/`makeReady` already report `provisioning`/`booting`. Deferred -because it is protocol machinery (interface + CLI/MCP wire changes), not a -small addition, and the daemon-side `component.install-started` bus event -already gives an operator visibility via `simlock events --follow` even -though the waiting requester itself does not see it yet. - ## Gateway-side file upload for `device.exec` `device.exec` runs a `simctl`/`adb` command on the machine that owns the diff --git a/docs/internal/KNOWN-PITFALLS.md b/docs/internal/KNOWN-PITFALLS.md index 1e658f711..eeee9ee23 100644 --- a/docs/internal/KNOWN-PITFALLS.md +++ b/docs/internal/KNOWN-PITFALLS.md @@ -292,12 +292,12 @@ this has to be a TCP port and cannot live as a socket file inside `drivers.android.adbServerPort` exists and why two Simlock instances on one machine need distinct values for it. -## Component downloads: one at a time per platform, the bounded-default edge case, and no progress push +## Component downloads: one at a time per platform, and the bounded-default edge case A lease request that may download and whose runtime is missing calls `ComponentInstaller` (`src/core/component-installer.ts`, ADR 0010 §3), which runs `xcodebuild -downloadPlatform iOS` or `sdkmanager --install` through the -driver. Three things worth knowing about that path: +driver. Two things worth knowing about that path: **A platform runs one download at a time.** Installs queue per platform, first come first served. Requests for the *same* component join one install; @@ -325,19 +325,6 @@ If Xcode doesn't have a build matching that bare major version, the download fails and the request fails with it; passing `--os ` explicitly is the way out. -**No requester-visible progress during a download (#67 stage 4).** The -requester's lease-progress stream (`LeaseProgress` in `src/core/wait-queue.ts` -— `queued` / `provisioning` / `booting` / `reclaiming`, relayed as CLI stderr -JSON lines and MCP `notifications/progress`) has no `downloading` stage. The -installer already hands every call the driver's percentage and a `waiting` -report (`ComponentInstallRequest.onProgress`), but the lease path does not pass -one, so a CLI or MCP caller waiting on a multi-minute install sees nothing on -the wire between its request and either the eventual grant or a failure; the -only visibility is the daemon's own `component.install-started` bus event -(`simlock events --follow`, and the event file behind `simlock events ---since`). There is no `daemon.log` line for it. Wiring it through is #210: a -new `LeaseProgress` variant and CLI/MCP wire changes. - ## An iOS runtime download outlives the runtime, and only Xcode can reclaim it (#79) `xcrun simctl runtime delete` unregisters a runtime from CoreSimulator and diff --git a/e2e/component-install.test.ts b/e2e/component-install.test.ts index a78e24836..6d1e7fdb5 100644 --- a/e2e/component-install.test.ts +++ b/e2e/component-install.test.ts @@ -53,8 +53,101 @@ describe("lease-triggered component installs", () => { .map((entry) => entry.event); expect(componentEvents).toEqual(["component.install-started", "component.installed"]); }); + + it("prints downloading progress lines that name the component, with a rising percent, before provisioning", async () => { + const env = await withDaemon(); + await env.driverScript.set({ + ios: { availableOsVersions: ["18.4"], installProgress: [20, 60], knownModels: ["iPhone 16"] }, + }); + + const result = await env.cli([...MISSING, "--allow-download", "--detach"], { timeout: 30_000 }); + + expect(result.code, result.stderr).toBe(0); + const stages = progressLines(result); + expect(stages.filter((line) => line["stage"] === "downloading")).toEqual([ + { component: "19.0", push: "progress", stage: "downloading", waiting: false }, + { component: "19.0", percent: 20, push: "progress", stage: "downloading", waiting: false }, + { component: "19.0", percent: 60, push: "progress", stage: "downloading", waiting: false }, + ]); + const lastDownloading = stages.findLastIndex((line) => line["stage"] === "downloading"); + const provisioning = stages.findIndex((line) => line["stage"] === "provisioning"); + expect(provisioning).toBeGreaterThan(lastDownloading); + }); + + it("shows the downloading stage to a second request that joins a download already running", async () => { + const env = await withDaemon(); + await env.driverScript.set({ + ios: { + availableOsVersions: ["18.4"], + knownModels: ["iPhone 16"], + latencyMs: { installComponent: 3_000 }, + }, + }); + await env.driverLog.clear(); + + const first = env.cliBackground([ + ...MISSING, + "--allow-download", + "--agent-id", + "agent-a", + "--detach", + ]); + await waitFor(async () => (await installCalls(env)).length === 1, { + label: "the first lease's install started", + }); + const second = await env.cli( + [...MISSING, "--allow-download", "--agent-id", "agent-b", "--detach"], + { timeout: 30_000 }, + ); + await first.waitForExit(30_000); + + expect(second.code, second.stderr).toBe(0); + expect(progressLines(second)).toContainEqual({ + component: "19.0", + push: "progress", + stage: "downloading", + waiting: false, + }); + expect(await installCalls(env)).toEqual([["19.0"]]); + }); + + it("never shows the downloading stage to a request whose runtime is installed", async () => { + const env = await withDaemon(); + await env.driverScript.set({ + ios: { availableOsVersions: ["18.4"], installProgress: [50], knownModels: ["iPhone 16"] }, + }); + + const result = await env.cli( + [ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--allow-download", + "--detach", + ], + { timeout: 30_000 }, + ); + + expect(result.code, result.stderr).toBe(0); + const stages = progressLines(result).map((line) => line["stage"]); + expect(stages).toContain("provisioning"); + expect(stages).not.toContain("downloading"); + }); }); +/** The CLI's `progress` lines on stderr, parsed; other stderr lines are left out. */ +function progressLines(result: CliResult): Record[] { + return result.stderr + .split("\n") + .filter((line) => line.startsWith("{")) + .map((line) => JSON.parse(line) as Record) + .filter((line) => line["push"] === "progress"); +} + /** Every stderr line the CLI wrote, parsed. */ function stderrLines(result: CliResult): unknown[] { return result.stderr @@ -217,6 +310,8 @@ describe("POST /v1/components/install", () => { }); expect(response.status).toBe(200); expect(await readSse(response)).toEqual([ + // The install's start, before the driver's own percentage. + { data: { stage: "downloading" }, event: "progress" }, { data: { fraction: 0.41, stage: "downloading" }, event: "progress" }, { data: { component: "35", outcome: "installed", platform: "android", version: "35" }, @@ -247,6 +342,8 @@ describe("POST /v1/components/install", () => { const repeat = await install(operator, { platform: "android", version: "35" }); expect(await readSse(repeat)).toEqual([ + // Joining a running install, it hears that install's latest progress at once. + { data: { stage: "downloading" }, event: "progress" }, { data: { component: "35", outcome: "installed", platform: "android", version: "35" }, event: "result", diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index f2c15e86b..630982e85 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -706,6 +706,37 @@ describe("operation input/output round trips", () => { expect(() => PUSH_SCHEMAS.output.parse({ chunk: "hello", stream: "stdout" })).toThrow(); }); + it("the progress push carries the downloading stage with its component, whether it waits, and an optional whole percent", () => { + const pushes = [ + { component: "26.4", stage: "downloading", waiting: true }, + { component: "26.4", percent: 41, stage: "downloading", waiting: false }, + ]; + for (const progress of pushes) { + expect(PUSH_SCHEMAS.progress.parse({ progress, requestId: 7 })).toEqual({ + progress, + requestId: 7, + }); + } + }); + + // Each refused push beside the nearest one that is accepted, so the refusal is the bound's. + it.each([ + ["a percent above 100", { percent: 101 }, { percent: 100 }], + ["a percent below 0", { percent: -1 }, { percent: 0 }], + ["a percent that is not whole", { percent: 41.7 }, { percent: 41 }], + [ + "a component over 64 characters", + { component: "x".repeat(65) }, + { component: "x".repeat(64) }, + ], + ])("refuses a downloading progress push with %s", (_case, outside, inside) => { + const base = { component: "26.4", stage: "downloading", waiting: false }; + const parse = (fields: object) => + PUSH_SCHEMAS.progress.safeParse({ progress: { ...base, ...fields }, requestId: 7 }).success; + expect(parse(outside)).toBe(false); + expect(parse(inside)).toBe(true); + }); + it("config.get: round-trips a representative config", () => { const config = { mode: "worker", diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index d647b85a8..ea6d33931 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -257,6 +257,14 @@ export const passthroughCommandSchema = z.object({ export const leaseProgressSchema = z.discriminatedUnion("stage", [ z.object({ stage: z.literal("queued"), queuePosition: z.number() }), + // ADR 0010 §3: the request waits on a component download. Bounded here so a gateway checks a + // worker's push before relaying it (safety rule 10). + z.object({ + stage: z.literal("downloading"), + component: z.string().max(64), + waiting: z.boolean(), + percent: z.number().int().min(0).max(100).optional(), + }), z.object({ stage: z.literal("provisioning"), etaMs: z.number() }), z.object({ stage: z.literal("booting"), etaMs: z.number() }), z.object({ stage: z.literal("reclaiming"), etaMs: z.number() }), diff --git a/src/core/component-installer.test.ts b/src/core/component-installer.test.ts index 3585c27f5..31b79a8bd 100644 --- a/src/core/component-installer.test.ts +++ b/src/core/component-installer.test.ts @@ -279,11 +279,84 @@ describe("ComponentInstaller", () => { void harness.installer.install(ios("28.0", { onProgress: (report) => behind.push(report) })); await flush(); - expect(firstA).toEqual([{ percent: 40, stage: "downloading" }]); - expect(firstB).toEqual([{ percent: 40, stage: "downloading" }]); + // The first report is the install's start, before the driver's own percentage. + expect(firstA).toEqual([{ stage: "downloading" }, { percent: 40, stage: "downloading" }]); + expect(firstB).toEqual([{ stage: "downloading" }, { percent: 40, stage: "downloading" }]); expect(behind).toEqual([{ stage: "waiting" }]); }); + it("tells a call that its install started, with no percent, before the driver reports anything, and a call behind it hears the same when its own turn comes", async () => { + const harness = await createHarness({ + drivers: (clock) => [new FakeDriver({ availableOsVersions: [], clock, platform: "ios" })], + }); + harness.ios.holdInstalls(); + const first: ComponentInstallerProgress[] = []; + const behind: ComponentInstallerProgress[] = []; + + void harness.installer.install(ios("27.0", { onProgress: (report) => first.push(report) })); + void harness.installer.install(ios("28.0", { onProgress: (report) => behind.push(report) })); + await flush(); + + // The driver is holding and has reported nothing: the start report is the installer's own. + expect(installs(harness.ios)).toEqual(["27.0"]); + expect(first).toEqual([{ stage: "downloading" }]); + expect(behind).toEqual([{ stage: "waiting" }]); + + harness.ios.releaseInstalls(); + harness.ios.holdInstalls(); + await flush(); + expect(installs(harness.ios)).toEqual(["27.0", "28.0"]); + expect(behind).toEqual([{ stage: "waiting" }, { stage: "downloading" }]); + }); + + it("tells a call that joins a running install its latest report at once, and only that one", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ + availableOsVersions: [], + clock, + installProgress: [12, 41], + platform: "ios", + }), + ], + }); + harness.ios.holdInstalls(); + const early: ComponentInstallerProgress[] = []; + const joiner: ComponentInstallerProgress[] = []; + + void harness.installer.install(ios("27.0", { onProgress: (report) => early.push(report) })); + await flush(); + expect(early).toEqual([ + { stage: "downloading" }, + { percent: 12, stage: "downloading" }, + { percent: 41, stage: "downloading" }, + ]); + + void harness.installer.install(ios("27.0", { onProgress: (report) => joiner.push(report) })); + // Synchronously, before anything else runs: the latest report, and only that one. + expect(joiner).toEqual([{ percent: 41, stage: "downloading" }]); + expect(early).toHaveLength(3); + }); + + it("still lists a running install as downloading and one behind it as waiting after a call joined the running one", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ availableOsVersions: [], clock, installProgress: [41], platform: "ios" }), + ], + }); + harness.ios.holdInstalls(); + + void harness.installer.install(ios("27.0")); + void harness.installer.install(ios("28.0")); + await flush(); + void harness.installer.install(ios("27.0", { onProgress: () => undefined })); + + expect(harness.installer.inProgress()).toEqual([ + { component: "27.0", platform: "ios", since: 1_000, state: "downloading", waiters: 2 }, + { component: "28.0", platform: "ios", since: 1_000, state: "waiting", waiters: 1 }, + ]); + }); + it("runs an iOS install and an Android install at the same time", async () => { const harness = await createHarness({ drivers: (clock) => [ @@ -733,7 +806,7 @@ describe("ComponentInstaller", () => { expect(throwing).toMatchObject({ status: "fulfilled" }); expect(listening).toMatchObject({ status: "fulfilled" }); - expect(heard).toEqual([{ percent: 50, stage: "downloading" }]); + expect(heard).toEqual([{ stage: "downloading" }, { percent: 50, stage: "downloading" }]); }); it.each([ diff --git a/src/core/component-installer.ts b/src/core/component-installer.ts index 573317306..af5a5f501 100644 --- a/src/core/component-installer.ts +++ b/src/core/component-installer.ts @@ -21,8 +21,15 @@ import type { Registry } from "./registry.js"; import type { SerializedDecision } from "./serialized-decision.js"; import { stableError } from "./stable-error.js"; -/** What a caller hears while its call is open: the driver's own progress, or that it waits. */ -export type ComponentInstallerProgress = ComponentInstallProgress | { readonly stage: "waiting" }; +/** + * What a caller hears while its call is open: that it waits behind another install, that its + * install has started (`downloading` with no `percent`, before the driver reports anything), or + * the driver's own progress. + */ +export type ComponentInstallerProgress = + | ComponentInstallProgress + | { readonly stage: "downloading"; readonly percent?: undefined } + | { readonly stage: "waiting" }; export interface ComponentInstallRequest { readonly platform: Platform; @@ -133,6 +140,8 @@ interface Install { readonly since: number; state: InstallState; abort: AbortController | undefined; + /** The last report its calls heard since it started running, told at once to a call that joins. */ + latest: ComponentInstallerProgress | undefined; } interface InstallCall { @@ -198,6 +207,7 @@ export class ComponentInstaller { // An observer, like `onProgress`: a throw there must not reach the install. } if (queue[0] !== install) notify(call, { stage: "waiting" }); + else if (install.latest !== undefined) notify(call, install.latest); this.#pump(request.platform); }); } @@ -311,6 +321,7 @@ export class ComponentInstaller { const install: Install = { abort: undefined, calls: [], + latest: undefined, component: request.component, platform: request.platform, requesterId: request.requesterId, @@ -392,6 +403,8 @@ export class ComponentInstaller { const abort = new AbortController(); install.abort = abort; install.state = "running"; + // Every call hears that its install started, before the driver reports anything. + this.#report(install, { stage: "downloading" }); const startedAt = this.options.clock.now(); const attribution = install.requesterId === undefined ? {} : { requesterId: install.requesterId }; @@ -404,7 +417,7 @@ export class ComponentInstaller { try { result = await driver.installComponent(install.component, { onProgress: (progress) => { - for (const call of install.calls) notify(call, progress); + this.#report(install, progress); }, signal: abort.signal, }); @@ -449,6 +462,12 @@ export class ComponentInstaller { this.#settleAll(install, { outcome: { outcome: result.outcome, version: result.version } }); } + /** Tells every call on the install, and keeps the report for a call that joins later. */ + #report(install: Install, progress: ComponentInstallerProgress): void { + install.latest = progress; + for (const call of install.calls) notify(call, progress); + } + /** * A call's budget ran out. A waiting call, or one whose install is only writing its record, * leaves alone; the install carries on for the others, or ends when it was the last. A running install is ended at diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 095060dff..582553c4a 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -30,7 +30,12 @@ import { LeaseLifecycle } from "./lease-lifecycle.js"; import { ManagedDeviceLifecycle } from "./managed-device-lifecycle.js"; import { Registry } from "./registry.js"; import { SerializedDecision } from "./serialized-decision.js"; -import { QueueTimeoutError, RequesterAlreadyLeasedError, WaitQueue } from "./wait-queue.js"; +import { + type LeaseRequestOptions, + QueueTimeoutError, + RequesterAlreadyLeasedError, + WaitQueue, +} from "./wait-queue.js"; const gibibyte = 1024 ** 3; const statePath = "/home/agent/.simlock/state.json"; @@ -246,13 +251,13 @@ async function seedShutdown( }); } -describe("LeaseAcquisitionCoordinator: missing runtimes", () => { - function installs(driver: FakeDriver): readonly unknown[] { - return driver.calls - .filter((call) => call.operation === "installComponent") - .map((call) => call.arguments[0]); - } +function installs(driver: FakeDriver): readonly unknown[] { + return driver.calls + .filter((call) => call.operation === "installComponent") + .map((call) => call.arguments[0]); +} +describe("LeaseAcquisitionCoordinator: missing runtimes", () => { it("installs once for two lease requests for the same missing runtime, and grants both", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); @@ -400,6 +405,224 @@ describe("LeaseAcquisitionCoordinator: missing runtimes", () => { }); }); +describe("LeaseAcquisitionCoordinator: download progress", () => { + type Progress = Parameters>[0]; + + function downloading(progress: readonly Progress[]): readonly Progress[] { + return progress.filter((report) => report.stage === "downloading"); + } + + it("tells a request that starts a download downloading, naming the component and not waiting, before provisioning", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + const harness = await createHarness({ drivers: [driver] }); + const progress: Progress[] = []; + + await harness.coordinator.request(request, { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "a", + requesterId: "a", + }); + + expect(progress[0]).toEqual({ component: "26.5", stage: "downloading", waiting: false }); + const provisioning = progress.findIndex((report) => report.stage === "provisioning"); + expect(provisioning).toBeGreaterThan(0); + expect(progress.slice(provisioning).some((report) => report.stage === "downloading")).toBe( + false, + ); + }); + + it("tells a request behind another download on its platform that it is waiting, then not waiting when its own install starts", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + driver.holdInstalls(); + const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); + const progress: Progress[] = []; + + const first = harness.coordinator.request(request, { + allowDownload: true, + ownerId: "a", + requesterId: "a", + }); + const second = harness.coordinator.request( + { ...request, osVersion: "27.0" }, + { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "b", + requesterId: "b", + }, + ); + await flush(); + expect(progress).toEqual([{ component: "27.0", stage: "downloading", waiting: true }]); + + driver.releaseInstalls(); + await first; + await settle(); + expect(installs(driver)).toEqual(["26.5", "27.0"]); + expect(downloading(progress)).toEqual([ + { component: "27.0", stage: "downloading", waiting: true }, + { component: "27.0", stage: "downloading", waiting: false }, + ]); + + // Issue #226: nothing wakes a request queued behind a device that was granted meanwhile. + harness.coordinator.kick(); + await expect(second).resolves.toMatchObject({ device: { spec: { osVersion: "27.0" } } }); + }); + + it("tells a request that joins a download already running its latest percentage at once", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ + availableOsVersions: [], + clock, + installProgress: [12, 41], + platform: "ios", + }); + driver.holdInstalls(); + const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); + const joined: Progress[] = []; + + const first = harness.coordinator.request(request, { + allowDownload: true, + ownerId: "a", + requesterId: "a", + }); + await flush(); + expect(installs(driver)).toEqual(["26.5"]); + const second = harness.coordinator.request(request, { + allowDownload: true, + onProgress: (report) => joined.push(report), + ownerId: "b", + requesterId: "b", + }); + await flush(); + + // The driver is still holding: this is the replay, not a later report. + expect(joined).toEqual([ + { component: "26.5", percent: 41, stage: "downloading", waiting: false }, + ]); + driver.releaseInstalls(); + await Promise.all([first, second]); + expect(installs(driver)).toEqual(["26.5"]); + }); + + it("sends a percentage the driver reports twice to the requester once", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ + availableOsVersions: [], + clock, + installProgress: [30, 30, 60], + platform: "ios", + }); + const harness = await createHarness({ drivers: [driver] }); + const progress: Progress[] = []; + + await harness.coordinator.request(request, { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "a", + requesterId: "a", + }); + + expect(downloading(progress)).toEqual([ + { component: "26.5", stage: "downloading", waiting: false }, + { component: "26.5", percent: 30, stage: "downloading", waiting: false }, + { component: "26.5", percent: 60, stage: "downloading", waiting: false }, + ]); + }); + + it("sends a percentage of 41.7 as 41, and one that rounds down to the last sent not at all", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ + availableOsVersions: [], + clock, + installProgress: [41.2, 41.7], + platform: "ios", + }); + const harness = await createHarness({ drivers: [driver] }); + const progress: Progress[] = []; + + await harness.coordinator.request(request, { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "a", + requesterId: "a", + }); + + expect(downloading(progress)).toEqual([ + { component: "26.5", stage: "downloading", waiting: false }, + { component: "26.5", percent: 41, stage: "downloading", waiting: false }, + ]); + }); + + it("sends no downloading stage to a request whose runtime is installed", async () => { + const harness = await createHarness(); + const progress: Progress[] = []; + + await harness.coordinator.request(request, { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "a", + requesterId: "a", + }); + + expect(progress.map((report) => report.stage)).toContain("provisioning"); + expect(downloading(progress)).toEqual([]); + }); + + it("sends no downloading stage to a request without allowDownload for a missing runtime", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + const harness = await createHarness({ drivers: [driver] }); + const progress: Progress[] = []; + + await expect( + harness.coordinator.request(request, { + onProgress: (report) => progress.push(report), + ownerId: "a", + requesterId: "a", + }), + ).rejects.toMatchObject({ name: "RuntimeMissingError" }); + expect(progress).toEqual([]); + }); + + it("tells a request that waited and then needed no install that it was waiting, then provisioning, and never not waiting", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + driver.holdInstalls(); + const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); + const progress: Progress[] = []; + + const byVersion = harness.coordinator.request(request, { + allowDownload: true, + ownerId: "a", + requesterId: "a", + }); + // No version: the fake names its word for newest, a different component that waits its turn + // and finds, at the front, that the first install made its runtime available. + const newest = harness.coordinator.request( + { model: "iPhone 16", platform: "ios" }, + { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "b", + requesterId: "b", + }, + ); + await flush(); + driver.releaseInstalls(); + await Promise.all([byVersion, newest]); + + expect(installs(driver)).toEqual(["26.5"]); + expect(progress[0]).toMatchObject({ stage: "downloading", waiting: true }); + expect( + downloading(progress).every((report) => report.stage === "downloading" && report.waiting), + ).toBe(true); + expect(progress[1]).toMatchObject({ stage: "provisioning" }); + }); +}); + describe("LeaseAcquisitionCoordinator", () => { it("admits one requester and rejects an active or pending duplicate", async () => { const harness = await createHarness(); diff --git a/src/core/lease-acquisition-coordinator.ts b/src/core/lease-acquisition-coordinator.ts index 9905cecf0..64d93331b 100644 --- a/src/core/lease-acquisition-coordinator.ts +++ b/src/core/lease-acquisition-coordinator.ts @@ -16,7 +16,7 @@ import { type Platform, sameSpec, } from "./domain.js"; -import type { ComponentInstaller } from "./component-installer.js"; +import type { ComponentInstaller, ComponentInstallerProgress } from "./component-installer.js"; import { BootTimeoutError, type DeviceRequest, @@ -34,6 +34,7 @@ import { type SerializedDecision } from "./serialized-decision.js"; import { stableError } from "./stable-error.js"; import { type LeaseGrant, + type LeaseProgress, type LeaseRequestOptions, type LeaseTiming, RequestCancelledError, @@ -278,7 +279,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { try { // The one place a request with no mode gets the worker's default (ADR 0007 §2). const mode = request.mode ?? this.options.defaultModes[request.platform] ?? "full"; - const resolved = await this.#resolveOrInstall(driver, { ...request, mode }, options); + const resolved = await this.#resolveOrInstall(waiter, driver, { ...request, mode }, options); // Full is a guarantee (ADR 0007 §5): a slim spec is accepted only for a slim request, so a // driver that returns the wrong thing still cannot put a full request on a slim device. waiter.spec = mode === "slim" ? resolved : fullSpec(resolved); @@ -298,8 +299,13 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { * the install when, by the time this call reaches the front of its queue, `resolveSpec` no * longer fails with `RuntimeMissingError` -- another install made the runtime available. * Without `allowDownload` the first failure stands and the installer is never called. + * + * The installer's reports reach the requester as the `downloading` stage, through the queue + * like every other stage. A report equal to the last one sent is skipped, so a percentage is + * sent once per whole number. */ async #resolveOrInstall( + waiter: AcquisitionWaiter, driver: Driver, request: DeviceRequest, options: LeaseRequestOptions, @@ -315,8 +321,16 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { ) { throw error; } + const { component } = error; + let lastSent: DownloadingProgress | undefined; await this.options.components.install({ - component: error.component, + component, + onProgress: (progress) => { + const next = downloadingProgress(component, progress); + if (lastSent !== undefined && sameDownloadingProgress(lastSent, next)) return; + lastSent = next; + this.options.queue.notifyProgress(waiter, next); + }, platform: request.platform, requesterId: options.requesterId, stillNeeded: async () => { @@ -790,3 +804,34 @@ function fullSpec(spec: DeviceSpec): DeviceSpec { const { mode: _mode, ...full } = spec; return full; } + +type DownloadingProgress = Extract; + +/** + * The installer's report in the requester's words. `waiting` is a request still behind another + * install; `downloading` is its own install running, with the driver's percentage rounded down to + * a whole number from 0 to 100. A percentage that is not a finite number is left out. + */ +function downloadingProgress( + component: string, + progress: ComponentInstallerProgress, +): DownloadingProgress { + if (progress.stage === "waiting") return { component, stage: "downloading", waiting: true }; + const { percent } = progress; + return percent === undefined || !Number.isFinite(percent) + ? { component, stage: "downloading", waiting: false } + : { + component, + percent: Math.min(100, Math.max(0, Math.floor(percent))), + stage: "downloading", + waiting: false, + }; +} + +function sameDownloadingProgress(left: DownloadingProgress, right: DownloadingProgress): boolean { + return ( + left.component === right.component && + left.waiting === right.waiting && + left.percent === right.percent + ); +} diff --git a/src/core/wait-queue.ts b/src/core/wait-queue.ts index 88a842749..158afd464 100644 --- a/src/core/wait-queue.ts +++ b/src/core/wait-queue.ts @@ -32,6 +32,17 @@ export interface LeaseRequestOptions { /** Request-scoped progress for the lease action currently being performed. */ export type LeaseProgress = | { readonly stage: "queued"; readonly queuePosition: number } + /** + * The request waits on a component download (ADR 0010 §3). `component` is the string the + * driver named, carried unread. `waiting` is true while another install on the platform runs + * ahead of it. `percent`, a whole number from 0 to 100, is there when the installer printed one. + */ + | { + readonly stage: "downloading"; + readonly component: string; + readonly waiting: boolean; + readonly percent?: number | undefined; + } | { readonly stage: "provisioning"; readonly etaMs: number } | { readonly stage: "booting"; readonly etaMs: number } | { readonly stage: "reclaiming"; readonly etaMs: number }; diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 975286f48..e157dfb5a 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1358,6 +1358,9 @@ describe("Dispatcher: component.install", () => { ); expect(progress).toEqual([ + // The install's start, before the driver reports anything. + { stage: "downloading" }, + // The driver's NaN, with its fraction left out. { stage: "downloading" }, { fraction: 0, stage: "downloading" }, { fraction: 0.5, stage: "downloading" }, @@ -1389,7 +1392,38 @@ describe("Dispatcher: component.install", () => { await first; await expect(second).resolves.toMatchObject({ outcome: "installed", version: "28.0" }); - expect(progress).toEqual([{ stage: "waiting" }, { fraction: 0.41, stage: "downloading" }]); + expect(progress).toEqual([ + { stage: "waiting" }, + { stage: "downloading" }, + { fraction: 0.41, stage: "downloading" }, + ]); + }); + + it("tells a caller that joins an install already running its latest progress at once", async () => { + const { dispatcher, driver } = await buildDispatcher({ + driverOptions: { installProgress: [41] }, + }); + driver.holdInstalls(); + const first = dispatcher.dispatch( + "component.install", + { platform: "ios", version: "27.0" }, + admin(), + ); + await until(() => installCalls(driver).length === 1, "the first install started"); + + const progress: unknown[] = []; + const joined = dispatcher.dispatch( + "component.install", + { platform: "ios", version: "27.0" }, + admin({ onComponentProgress: (update) => progress.push(update) }), + ); + await until(() => progress.length === 1, "the joining call heard the latest progress"); + expect(progress).toEqual([{ fraction: 0.41, stage: "downloading" }]); + + driver.releaseInstalls(); + await first; + await expect(joined).resolves.toMatchObject({ outcome: "installed", version: "27.0" }); + expect(installCalls(driver)).toHaveLength(1); }); }); diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 6d3fcf499..9448c62a7 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -684,7 +684,10 @@ export class Dispatcher { */ function toWireProgress(progress: ComponentInstallerProgress): ComponentProgress { if (progress.stage === "waiting") return { stage: "waiting" }; - if (!Number.isFinite(progress.percent)) return { stage: "downloading" }; + // No percentage: the install has started and the driver has not reported one yet. + if (progress.percent === undefined || !Number.isFinite(progress.percent)) { + return { stage: "downloading" }; + } return { fraction: Math.min(1, Math.max(0, progress.percent / 100)), stage: "downloading" }; } diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 9d134e571..533462b0e 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -617,6 +617,11 @@ describe("DaemonServer", () => { payload: { component: "27.0", outcome: "installed", platform: "ios", version: "27.0" }, }); expect(client.frames().filter((frame) => frame.push === "component-progress")).toEqual([ + // The install's start, with no fraction: the schema accepts it as a push. + { + payload: { progress: { stage: "downloading" }, requestId: "install-frame" }, + push: "component-progress", + }, { payload: { progress: { fraction: 0.5, stage: "downloading" }, requestId: "install-frame" }, push: "component-progress", diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 6ff94d5bc..38eedfa3c 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -987,6 +987,28 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(grant.lease.worker?.id).toBe("wrk_a"); }); + it("relays a worker's downloading pushes to the requester unchanged", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + const pushed = [ + { component: "26.4", stage: "downloading", waiting: true }, + { component: "26.4", stage: "downloading", waiting: false }, + { component: "26.4", percent: 41, stage: "downloading", waiting: false }, + { etaMs: 5_000, stage: "provisioning" }, + ] as const; + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant", progress: pushed }); + const heard: unknown[] = []; + + await coordinator.request( + REQUEST, + requestOptions({ allowDownload: true, onProgress: (progress) => heard.push(progress) }), + ); + + expect(heard).toEqual(pushed); + }); + it("emits request.dispatched when a grant lands with no progress push at all -- the ADR §11 rule's other half", async () => { const { coordinator, directory, eventBus, workers } = harness(); const client = new ScriptedWorkerClient(); diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index f299fde99..b553c2dc9 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -174,6 +174,12 @@ export type RequestLeaseOutcome = type LeaseProgressLike = | { readonly stage: "queued"; readonly queuePosition: number } + | { + readonly stage: "downloading"; + readonly component: string; + readonly waiting: boolean; + readonly percent?: number | undefined; + } | { readonly stage: "provisioning"; readonly etaMs: number } | { readonly stage: "booting"; readonly etaMs: number } | { readonly stage: "reclaiming"; readonly etaMs: number }; diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 309e54227..a870ec32b 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -601,6 +601,71 @@ describe("full lease-request lifecycle via GET / long-poll / SSE", () => { const last = frames.at(-1)?.data as { lease: { id: string } }; expect(last.lease.id).toBe("lse_sse"); }); + + it("shows downloading with its component, whether it waits, and its percent on GET while the install runs", async () => { + const { app, dispatcher } = buildHarness(); + const { id, callIndex } = await createLeaseRequest(app, dispatcher, { + ...defaultBody, + allowDownload: true, + }); + const read = async () => + ( + (await (await app.request(`/v1/lease-requests/${id}`, { headers: agentAuth })).json()) as { + request: unknown; + } + ).request; + + const session = dispatcher.calls[callIndex]?.session; + session?.onProgress?.({ component: "26.4", stage: "downloading", waiting: true }); + expect(await read()).toEqual({ + component: "26.4", + createdAt: expect.any(String), + id, + state: "downloading", + waiting: true, + }); + + session?.onProgress?.({ component: "26.4", percent: 41, stage: "downloading", waiting: false }); + expect(await read()).toEqual({ + component: "26.4", + createdAt: expect.any(String), + id, + percent: 41, + state: "downloading", + waiting: false, + }); + }); + + it("sends a downloading event on the lease-request event stream", async () => { + const { app, dispatcher } = buildHarness(); + const { id, callIndex } = await createLeaseRequest(app, dispatcher, { + ...defaultBody, + allowDownload: true, + }); + + const streamResponse = await app.request(`/v1/lease-requests/${id}/events`, { + headers: agentAuth, + }); + const framesPromise = readSseFrames(streamResponse, 3); + dispatcher.calls[callIndex]?.session.onProgress?.({ + component: "26.4", + percent: 41, + stage: "downloading", + waiting: false, + }); + dispatcher.calls[callIndex]?.resolve(makeGrant({ lease: { id: "lse_download" } })); + const frames = await framesPromise; + + expect(frames.map((frame) => frame.event)).toEqual(["queued", "downloading", "granted"]); + expect(frames[1]?.data).toEqual({ + component: "26.4", + createdAt: expect.any(String), + id, + percent: 41, + state: "downloading", + waiting: false, + }); + }); }); describe("GET /v1/lease-requests/:id across a daemon restart", () => { diff --git a/src/http/app.ts b/src/http/app.ts index 9fc8ce3ec..eab136fc8 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -703,6 +703,11 @@ function serializeRequest( switch (view.state.stage) { case "queued": return { ...base, queuePosition: view.state.queuePosition }; + case "downloading": { + // `component`, `waiting` and `percent` when there is one, as the tracker built them. + const { stage: _stage, ...download } = view.state; + return { ...base, ...download }; + } case "provisioning": case "booting": case "reclaiming": diff --git a/src/http/tracker.ts b/src/http/tracker.ts index 52a18b97d..6eff50f62 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -77,6 +77,7 @@ export function buildLeasePayload( export type RequestSnapshot = | { readonly stage: "queued"; readonly queuePosition: number } + | DownloadingProgress | { readonly stage: "reclaiming"; readonly etaSeconds: number } | { readonly stage: "provisioning"; readonly etaSeconds: number } | { readonly stage: "booting"; readonly etaSeconds: number } @@ -325,11 +326,20 @@ export class LeaseRequestTracker { } } +/** A request waiting on a component download: the same fields on the wire and in the resource. */ +interface DownloadingProgress { + readonly stage: "downloading"; + readonly component: string; + readonly waiting: boolean; + readonly percent?: number | undefined; +} + /** Structural subset of `LeaseProgress` (`src/core/wait-queue.ts`) -- this module only ever * receives it through a dispatched `lease.request`'s session `onProgress` override, never * imports the core type directly. */ type HttpLeaseProgress = | { readonly stage: "queued"; readonly queuePosition: number } + | DownloadingProgress | { readonly stage: "provisioning"; readonly etaMs: number } | { readonly stage: "booting"; readonly etaMs: number } | { readonly stage: "reclaiming"; readonly etaMs: number }; @@ -388,8 +398,22 @@ function toSnapshot( } // Open with no progress reported yet: the request is admitted and about to queue. if (progress === undefined) return { queuePosition: 1, stage: "queued" }; + return openSnapshot(progress); +} + +/** An open request's state, from the progress its live wait last reported. */ +function openSnapshot(progress: HttpLeaseProgress): RequestSnapshot { if (progress.stage === "queued") return { queuePosition: progress.queuePosition, stage: "queued" }; + if (progress.stage === "downloading") { + const { component, percent, waiting } = progress; + return { + component, + stage: "downloading", + waiting, + ...(percent === undefined ? {} : { percent }), + }; + } return { etaSeconds: toSeconds(progress.etaMs), stage: progress.stage }; } diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 9f02ec32b..271f5eafb 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -274,6 +274,75 @@ describe("MCP server (smoke)", () => { } }); + it("relays the downloading stage as a notification naming the component, above queued and below provisioning, and never going down across queued, downloading, provisioning, booting", async () => { + const client = new FakeSimlockClient(); + let onProgress: ((progress: unknown) => void) | undefined; + let resolveGrant!: (grant: ReturnType) => void; + const grantPromise = new Promise>((resolve) => { + resolveGrant = resolve; + }); + client.requestLeaseImpl = (_input, options) => { + onProgress = options.onProgress as ((progress: unknown) => void) | undefined; + return grantPromise; + }; + const { mcpClient, close } = await connectedServer(client); + try { + const progressEvents: unknown[] = []; + const leaseCall = mcpClient.request( + { + method: "tools/call", + params: { + arguments: { allowDownload: true, model: "iPhone 17 Pro", platform: "ios" }, + name: "lease_simulator", + }, + }, + CallToolResultSchema, + { onprogress: (progress) => progressEvents.push(progress) }, + ); + await waitFor(() => onProgress !== undefined); + + onProgress!({ queuePosition: 2, stage: "queued" }); + onProgress!({ component: "26.4", stage: "downloading", waiting: true }); + onProgress!({ component: "26.4", stage: "downloading", waiting: false }); + onProgress!({ component: "26.4", percent: 41, stage: "downloading", waiting: false }); + onProgress!({ etaMs: 60_000, stage: "provisioning" }); + onProgress!({ etaMs: 4_000, stage: "booting" }); + await waitFor(() => progressEvents.length === 6); + + expect(progressEvents).toEqual([ + expect.objectContaining({ message: "Queued behind 2 other requests" }), + expect.objectContaining({ + message: "Waiting for another download before downloading 26.4", + }), + expect.objectContaining({ message: "Downloading 26.4" }), + expect.objectContaining({ message: "Downloading 26.4 (41%)" }), + expect.objectContaining({ message: expect.stringMatching(/^Provisioning device/) }), + expect.objectContaining({ message: expect.stringMatching(/^Booting device/) }), + ]); + const values = progressEvents.map((event) => (event as { progress: number }).progress); + const [queued, waiting, started, percent, provisioning] = values as [ + number, + number, + number, + number, + number, + ]; + // The reporter lifts a value that would go down to one above the last, so a gap wider than + // one is the stage's own placement, not that lift. + expect(waiting - queued).toBeGreaterThan(1); + expect(percent - started).toBeGreaterThan(1); + expect(provisioning - percent).toBeGreaterThan(1); + expect(values).toEqual([...values].sort((a, b) => a - b)); + expect(new Set(values).size).toBe(values.length); + + resolveGrant(sampleGrant()); + const lease = await leaseCall; + expect(lease.isError).not.toBe(true); + } finally { + await close(); + } + }); + it("emits nothing when the client supplied no progress token (MCP-only relay)", async () => { const client = new FakeSimlockClient(); let onProgress: ((progress: unknown) => void) | undefined; diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 1c95df1df..3db215b4d 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -21,16 +21,18 @@ import { const SERVER_INFO = { name: "simlock", version: "1.0.0" }; /** - * Progress is reported on a 3-stage scale (queued / provisioning-or-reclaiming / booting), each - * worth 1000 units, so a fresh stage's base always exceeds the previous stage's maximum. + * Progress is reported on a 4-stage scale (queued / downloading / provisioning-or-reclaiming / + * booting), each worth 1000 units, so a fresh stage's base always exceeds the previous stage's + * maximum. */ const STAGE_BASE_PROGRESS: Record = { - booting: 2_000, - provisioning: 1_000, + booting: 3_000, + downloading: 1_000, + provisioning: 2_000, queued: 0, - reclaiming: 1_000, + reclaiming: 2_000, }; -const TOTAL_PROGRESS = 3_000; +const TOTAL_PROGRESS = 4_000; /** Maps a lease progress push onto an MCP progress notification's `params`. */ function leaseProgressParams(progress: LeaseProgressNotice): { @@ -48,6 +50,23 @@ function leaseProgressParams(progress: LeaseProgressNotice): { progress: base + withinStageProgress(position), }; } + if (progress.stage === "downloading") { + // A request still behind another download sits at the stage's base; its own download climbs + // with the installer's percentage, reaching the next stage's base at 100. + if (progress.waiting) { + return { + message: `Waiting for another download before downloading ${progress.component}`, + progress: base, + }; + } + const { percent } = progress; + return percent === undefined + ? { message: `Downloading ${progress.component}`, progress: base } + : { + message: `Downloading ${progress.component} (${percent}%)`, + progress: base + Math.min(100, Math.max(0, percent)) * 10, + }; + } const etaSeconds = Math.max(0, Math.ceil(progress.etaMs / 1_000)); const verb = progress.stage === "provisioning" From ae05a70c0ce56932867b9ad8a093cbc6a5ac6905 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 15:48:06 +0200 Subject: [PATCH 2/3] fix(daemon,core,mcp): a progress push that does not fit its contract is dropped, not an unhandled rejection A downloading component past the push's 64-character bound made the push's schema check reject with nothing catching it. Also tests the percent clamp and the NaN guard, drops a clamp the contract already makes unreachable, and pins each MCP stage's base above the one before. --- .../lease-acquisition-coordinator.test.ts | 27 +++++++++++++++++++ src/core/lease-acquisition-coordinator.ts | 7 ++--- src/daemon/dispatcher.test.ts | 2 +- src/daemon/server.test.ts | 27 +++++++++++++++++++ src/daemon/server.ts | 7 ++++- src/mcp/server.test.ts | 14 ++++++---- src/mcp/server.ts | 3 ++- 7 files changed, 74 insertions(+), 13 deletions(-) diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 582553c4a..9f8f935a3 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -556,6 +556,33 @@ describe("LeaseAcquisitionCoordinator: download progress", () => { ]); }); + it("sends a driver's percentage outside 0 to 100 as the nearest bound, and one that is not a number as no percent", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ + availableOsVersions: [], + clock, + installProgress: [10, Number.NaN, -5, 150], + platform: "ios", + }); + const harness = await createHarness({ drivers: [driver] }); + const progress: Progress[] = []; + + await harness.coordinator.request(request, { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "a", + requesterId: "a", + }); + + expect(downloading(progress)).toEqual([ + { component: "26.5", stage: "downloading", waiting: false }, + { component: "26.5", percent: 10, stage: "downloading", waiting: false }, + { component: "26.5", stage: "downloading", waiting: false }, + { component: "26.5", percent: 0, stage: "downloading", waiting: false }, + { component: "26.5", percent: 100, stage: "downloading", waiting: false }, + ]); + }); + it("sends no downloading stage to a request whose runtime is installed", async () => { const harness = await createHarness(); const progress: Progress[] = []; diff --git a/src/core/lease-acquisition-coordinator.ts b/src/core/lease-acquisition-coordinator.ts index 64d93331b..440dee332 100644 --- a/src/core/lease-acquisition-coordinator.ts +++ b/src/core/lease-acquisition-coordinator.ts @@ -828,10 +828,7 @@ function downloadingProgress( }; } +/** Both reports are for the one component a `#resolveOrInstall` call downloads. */ function sameDownloadingProgress(left: DownloadingProgress, right: DownloadingProgress): boolean { - return ( - left.component === right.component && - left.waiting === right.waiting && - left.percent === right.percent - ); + return left.waiting === right.waiting && left.percent === right.percent; } diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index e157dfb5a..903beeece 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1399,7 +1399,7 @@ describe("Dispatcher: component.install", () => { ]); }); - it("tells a caller that joins an install already running its latest progress at once", async () => { + it("tells a caller that joins an install already running its latest progress while the install is still running", async () => { const { dispatcher, driver } = await buildDispatcher({ driverOptions: { installProgress: [41] }, }); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 533462b0e..8e4812725 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -2105,6 +2105,33 @@ describe("DaemonServer download policy", () => { await client.close(); }); + it("still answers a lease request whose download names a component past the progress push's bound, sending no downloading push for it", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + const harness = await createHarness({ clock, driver }); + const client = await createClient(harness.socketPath); + await hello(client); + // The fake names the requested version as the component: 65 characters, one past the bound. + const osVersion = "x".repeat(65); + + const grant = await client.request("lease.request", { + allowDownload: true, + requesterId: "agent-1", + model: "iPhone 16", + osVersion, + platform: "ios", + }); + + expect(grant.ok, JSON.stringify(grant.error)).toBe(true); + const stages = client + .frames() + .filter((frame) => frame.push === "progress") + .map((frame) => (frame.payload as { progress: { stage: string } }).progress.stage); + expect(stages).toContain("provisioning"); + expect(stages).not.toContain("downloading"); + await client.close(); + }); + it("withholds download permission under the never policy even when the request asks for it", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 0dcf0ca1b..f23006539 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -1221,7 +1221,12 @@ export class DaemonServer { ...this.#session(connection), onProgress: (progress) => { if (progressSocket !== undefined) { - void this.#pushProgress(progressSocket, requestId, progress); + // Progress is advisory: one that does not fit the push contract (a `downloading` + // component the driver named past the contract's bound) or a socket that went away + // is dropped, and the request carries on to its answer. + void this.#pushProgress(progressSocket, requestId, progress).catch(() => { + this.#logger.warn("A lease progress push was not sent", { stage: progress.stage }); + }); } }, }); diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 271f5eafb..908756ed5 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -304,9 +304,11 @@ describe("MCP server (smoke)", () => { onProgress!({ queuePosition: 2, stage: "queued" }); onProgress!({ component: "26.4", stage: "downloading", waiting: true }); onProgress!({ component: "26.4", stage: "downloading", waiting: false }); - onProgress!({ component: "26.4", percent: 41, stage: "downloading", waiting: false }); - onProgress!({ etaMs: 60_000, stage: "provisioning" }); - onProgress!({ etaMs: 4_000, stage: "booting" }); + // Each stage at its highest value, then the next at its lowest: a stage whose base did not + // sit above the one before would land at or under it, and be lifted by one. + onProgress!({ component: "26.4", percent: 100, stage: "downloading", waiting: false }); + onProgress!({ etaMs: 0, stage: "provisioning" }); + onProgress!({ etaMs: 600_000, stage: "booting" }); await waitFor(() => progressEvents.length === 6); expect(progressEvents).toEqual([ @@ -315,12 +317,13 @@ describe("MCP server (smoke)", () => { message: "Waiting for another download before downloading 26.4", }), expect.objectContaining({ message: "Downloading 26.4" }), - expect.objectContaining({ message: "Downloading 26.4 (41%)" }), + expect.objectContaining({ message: "Downloading 26.4 (100%)" }), expect.objectContaining({ message: expect.stringMatching(/^Provisioning device/) }), expect.objectContaining({ message: expect.stringMatching(/^Booting device/) }), ]); const values = progressEvents.map((event) => (event as { progress: number }).progress); - const [queued, waiting, started, percent, provisioning] = values as [ + const [queued, waiting, started, percent, provisioning, booting] = values as [ + number, number, number, number, @@ -332,6 +335,7 @@ describe("MCP server (smoke)", () => { expect(waiting - queued).toBeGreaterThan(1); expect(percent - started).toBeGreaterThan(1); expect(provisioning - percent).toBeGreaterThan(1); + expect(booting - provisioning).toBeGreaterThan(1); expect(values).toEqual([...values].sort((a, b) => a - b)); expect(new Set(values).size).toBe(values.length); diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 3db215b4d..343ad5f9d 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -64,7 +64,8 @@ function leaseProgressParams(progress: LeaseProgressNotice): { ? { message: `Downloading ${progress.component}`, progress: base } : { message: `Downloading ${progress.component} (${percent}%)`, - progress: base + Math.min(100, Math.max(0, percent)) * 10, + // The contract bounds `percent` to a whole number from 0 to 100. + progress: base + percent * 10, }; } const etaSeconds = Math.max(0, Math.ceil(progress.etaMs / 1_000)); From 30ae7a2fb2929fd9ed903aba68835e5ab9ac3845 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 15:59:38 +0200 Subject: [PATCH 3/3] refactor(core,daemon): the installer cleans a driver's percentage once for every caller The lease path and component.install each clamped and dropped non-finite percentages; the installer now does it before either hears it. Also makes the 41.7 test send 41.7 first, and has the dropped-push test assert the warning. --- src/core/component-installer.test.ts | 24 +++++++++++++++++++ src/core/component-installer.ts | 13 ++++++++-- .../lease-acquisition-coordinator.test.ts | 2 +- src/core/lease-acquisition-coordinator.ts | 13 ++++------ src/daemon/dispatcher.ts | 12 ++++------ src/daemon/server.test.ts | 16 +++++++++++-- 6 files changed, 59 insertions(+), 21 deletions(-) diff --git a/src/core/component-installer.test.ts b/src/core/component-installer.test.ts index 31b79a8bd..73d63c89a 100644 --- a/src/core/component-installer.test.ts +++ b/src/core/component-installer.test.ts @@ -338,6 +338,30 @@ describe("ComponentInstaller", () => { expect(early).toHaveLength(3); }); + it("tells its calls a driver's percentage clamped to 0..100, and one that is not a number as no percent", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ + availableOsVersions: [], + clock, + installProgress: [Number.NaN, -5, 150, 41.7], + platform: "ios", + }), + ], + }); + const heard: ComponentInstallerProgress[] = []; + + await harness.installer.install(ios("27.0", { onProgress: (report) => heard.push(report) })); + + expect(heard).toEqual([ + { stage: "downloading" }, + { stage: "downloading" }, + { percent: 0, stage: "downloading" }, + { percent: 100, stage: "downloading" }, + { percent: 41.7, stage: "downloading" }, + ]); + }); + it("still lists a running install as downloading and one behind it as waiting after a call joined the running one", async () => { const harness = await createHarness({ drivers: (clock) => [ diff --git a/src/core/component-installer.ts b/src/core/component-installer.ts index af5a5f501..f70712614 100644 --- a/src/core/component-installer.ts +++ b/src/core/component-installer.ts @@ -24,7 +24,7 @@ import { stableError } from "./stable-error.js"; /** * What a caller hears while its call is open: that it waits behind another install, that its * install has started (`downloading` with no `percent`, before the driver reports anything), or - * the driver's own progress. + * the driver's own progress, its `percent` within 0..100 or left out when it was not a number. */ export type ComponentInstallerProgress = | ComponentInstallProgress @@ -417,7 +417,7 @@ export class ComponentInstaller { try { result = await driver.installComponent(install.component, { onProgress: (progress) => { - this.#report(install, progress); + this.#report(install, cleanPercent(progress)); }, signal: abort.signal, }); @@ -519,6 +519,15 @@ export class ComponentInstaller { } } +/** + * The one place a driver's percentage is cleaned for every caller: clamped to 0..100, and left + * out when it is not a finite number rather than guessed. + */ +function cleanPercent(progress: ComponentInstallProgress): ComponentInstallerProgress { + if (!Number.isFinite(progress.percent)) return { stage: "downloading" }; + return { percent: Math.min(100, Math.max(0, progress.percent)), stage: "downloading" }; +} + /** A caller's progress callback is an observer: a throw there must not reach the install. */ function notify(call: InstallCall, progress: ComponentInstallerProgress): void { try { diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 9f8f935a3..bb11ed0e1 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -537,7 +537,7 @@ describe("LeaseAcquisitionCoordinator: download progress", () => { const driver = new FakeDriver({ availableOsVersions: [], clock, - installProgress: [41.2, 41.7], + installProgress: [41.7, 41.9], platform: "ios", }); const harness = await createHarness({ drivers: [driver] }); diff --git a/src/core/lease-acquisition-coordinator.ts b/src/core/lease-acquisition-coordinator.ts index 440dee332..7a43c971f 100644 --- a/src/core/lease-acquisition-coordinator.ts +++ b/src/core/lease-acquisition-coordinator.ts @@ -809,8 +809,8 @@ type DownloadingProgress = Extract { await client.close(); }); - it("still answers a lease request whose download names a component past the progress push's bound, sending no downloading push for it", async () => { + it("still answers a lease request whose download names a component past the progress push's bound, sending no downloading push for it and logging that", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - const harness = await createHarness({ clock, driver }); + const sink = new MemoryLogSink(); + const harness = await createHarness({ + clock, + driver, + logger: new JsonLinesLogger({ clock, level: "debug", sink }), + }); const client = await createClient(harness.socketPath); await hello(client); // The fake names the requested version as the component: 65 characters, one past the bound. @@ -2129,6 +2134,13 @@ describe("DaemonServer download policy", () => { .map((frame) => (frame.payload as { progress: { stage: string } }).progress.stage); expect(stages).toContain("provisioning"); expect(stages).not.toContain("downloading"); + expect(sink.records).toContainEqual( + expect.objectContaining({ + fields: { stage: "downloading" }, + level: "warn", + message: "A lease progress push was not sent", + }), + ); await client.close(); });