Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <slim|full>` — 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
Expand Down Expand Up @@ -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}
Expand All @@ -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
Expand Down
27 changes: 25 additions & 2 deletions docs/CLIENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions docs/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
30 changes: 23 additions & 7 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand All @@ -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.

Expand Down
11 changes: 9 additions & 2 deletions docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/internal/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
14 changes: 0 additions & 14 deletions docs/internal/IDEAS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 2 additions & 15 deletions docs/internal/KNOWN-PITFALLS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 <version>` 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
Expand Down
97 changes: 97 additions & 0 deletions e2e/component-install.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>[] {
return result.stderr
.split("\n")
.filter((line) => line.startsWith("{"))
.map((line) => JSON.parse(line) as Record<string, unknown>)
.filter((line) => line["push"] === "progress");
}

/** Every stderr line the CLI wrote, parsed. */
function stderrLines(result: CliResult): unknown[] {
return result.stderr
Expand Down Expand Up @@ -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" },
Expand Down Expand Up @@ -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",
Expand Down
31 changes: 31 additions & 0 deletions src/contract/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading