diff --git a/docs/CLI.md b/docs/CLI.md index 90b0ee0d9..89d8c7664 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -77,8 +77,8 @@ implement them: means for `USAGE` and `BAD_REQUEST`. Neither is retryable as written: the fix is a different command, or the same command against a different daemon. `UNSUPPORTED_IN_GATEWAY_MODE` in particular is permanent, not provisional: - `nuke`, `cleanup`, `doctor`, `driver.passthrough` and `component install` - stay per-worker operations rather than waiting on some later fleet-wide + `nuke`, `cleanup`, `doctor`, `driver.passthrough`, `component install` and + `component list` stay per-worker operations rather than waiting on some later fleet-wide version. - `UNKNOWN_WORKER` takes `12`, the number the table already gives to "the thing you named cannot be resolved" (`UNKNOWN_MODEL`, `NO_DRIVER`), because @@ -1169,6 +1169,70 @@ The command takes no `--json`: its output is already JSON, so the flag is a usage error (exit 2), as is a missing or extra argument or a platform other than `ios` or `android`. +## `simlock component list [--platform ]` + +Lists every iOS simulator runtime and Android system image installed on the +machine, whoever installed it. Read it before you remove anything. Any +session may run it, an agent session included. It changes nothing. + +```sh +simlock component list +simlock component list --platform android +``` + +The output is one JSON object on stdout: + +```json +{ + "components": [ + { + "platform": "android", + "version": "35", + "variant": "google_apis/arm64-v8a", + "sizeBytes": 4201234567, + "installedBySimlock": true, + "installedAt": 1790864071200, + "devices": 2, + "foreignDevices": 0 + }, + { + "platform": "ios", + "version": "26.4", + "variant": "23E244", + "sizeBytes": 9103456789, + "installedBySimlock": false, + "devices": 1, + "foreignDevices": 3 + } + ] +} +``` + +Entries are ordered by platform, then version, then variant. + +- `version` is the string `simlock catalog` lists under `runtimes`. +- `variant` tells two components of one version apart: the build of an iOS + runtime, or the tag and ABI of an Android image. +- `sizeBytes` is the disk the component takes. It is left out when it cannot + be read. +- `installedBySimlock` is `true` only for a component installed through + Simlock (`component install`, or a lease with `--allow-download`) that is + still the same one on disk. A component that was there before, or that was + deleted and installed again some other way, is `false`. `installedAt` is + when Simlock installed it. +- `devices` counts Simlock's own devices of this platform and version that + have not been deleted. Simlock does not track which variant a device uses, + so two variants of one version show the same count. +- `foreignDevices` counts the devices outside Simlock that use the + component: simulators in Xcode's default device set, or AVDs in your own + AVD home (`ANDROID_AVD_HOME`, or `~/.android/avd`). Simlock only reads + them. + +A platform whose tools cannot answer is left out, and the other platform is +still listed. A gateway answers `UNSUPPORTED_IN_GATEWAY_MODE`; run the +command against the worker. A platform other than `ios` or `android`, or a +positional argument, is a usage error (exit 2). + ## `simlock cleanup [--dry-run] [--rule ]` Run the cleanup reconciliation immediately. `--dry-run` prints the actions diff --git a/docs/CLIENT.md b/docs/CLIENT.md index e1a5a8cc8..8fd96ee83 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -259,6 +259,34 @@ const result = await admin.installComponent( component share one download, and each gets its result. A dropped connection does not stop the download; calling again joins it. +## What is installed: `listComponents` + +`listComponents({ platform? })`, on either client, lists every iOS +simulator runtime and Android system image installed on the daemon's +machine, whoever installed it — the call behind `simlock component list`: + +```ts +const { components } = await client.listComponents({ platform: "android" }); +// [{ platform: "android", version: "35", variant: "google_apis/arm64-v8a", +// sizeBytes: 4201234567, installedBySimlock: true, installedAt: 1790864071200, +// devices: 2, foreignDevices: 0 }] +``` + +- Entries are ordered by platform, then version, then variant. Without + `platform`, both platforms are listed; a platform whose tools cannot + answer is left out. +- `version` is the string `getCatalog` lists under `runtimes`. `variant` + tells two components of one version apart: an iOS runtime's build, an + Android image's tag and ABI. `sizeBytes` is absent when it cannot be read. +- `installedBySimlock` is `true` only for a component Simlock installed that + is still the same one on disk; `installedAt` is when it did. +- `devices` counts Simlock's own devices of this platform and version that + have not been deleted; two variants of one version show the same count. + `foreignDevices` counts the devices outside Simlock that use the + component: simulators in Xcode's default device set, AVDs in the user's + own AVD home. +- A gateway rejects it with `UNSUPPORTED_IN_GATEWAY_MODE`. + ## What machine answered: `getStatus().host` `getStatus()` carries a `host` block beside `daemon`: the machine the daemon diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 78ec00800..233fbe49a 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -62,7 +62,7 @@ Three roles: | Role | Can | |---|---| -| `agent` | catalog, status, its own lease requests and leases, `exec` on its own lease | +| `agent` | catalog, status, installed components, its own lease requests and leases, `exec` on its own lease | | `operator` | everything `agent` can, plus every other requester's leases/devices, the worker routes, event replay/stream, and releasing any lease | | `worker` | open an uplink at [`/v1/uplink`](#get-v1uplink-websocket-upgrade), and nothing else | @@ -116,8 +116,8 @@ Routes, status codes, and every other field are unchanged. Gateway/worker fleet mode is purely additive on top of that: the same routes answer identically whether the daemon behind them is a worker or a **gateway** fronting a fleet of workers (except -`POST /v1/components/install`, which only a worker serves; a gateway answers -`501 UNSUPPORTED_IN_GATEWAY_MODE`), and what it adds are new +`POST /v1/components/install` and `GET /v1/components`, which only a worker +serves; a gateway answers `501 UNSUPPORTED_IN_GATEWAY_MODE`), and what it adds are new routes (`/v1/uplink`, `/v1/workers*`, `POST /v1/leases/{id}/exec`), new fields (`mode` on status, `workers[]`, `workerId`, `worker` on the lease), and new error codes. Nothing existing changes shape, and a client that @@ -691,6 +691,45 @@ runs joins it and gets its result; repeating it after it finished answers `already-installed`. A lease request for the same component joins the same download too. +### `GET /v1/components?platform=ios|android` + +Role: `agent`. Lists every iOS simulator runtime and Android system image +installed on this machine, whoever installed it — the same answer as +`simlock component list`. It changes nothing. Without `platform`, both +platforms are listed. + +```json +{ + "components": [ + { + "platform": "android", + "version": "35", + "variant": "google_apis/arm64-v8a", + "sizeBytes": 4201234567, + "installedBySimlock": true, + "installedAt": 1790864071200, + "devices": 2, + "foreignDevices": 0 + } + ] +} +``` + +Entries are ordered by platform, then version, then variant. `version` is +the string `GET /v1/catalog` lists under `runtimes`; `variant` tells two +components of one version apart (an iOS runtime's build, an Android image's +tag and ABI). `sizeBytes` is left out when it cannot be read. +`installedBySimlock` is `true` only for a component Simlock installed that is +still the same one on disk, and `installedAt` is when it did. `devices` +counts Simlock's own devices of this platform and version that have not been +deleted; two variants of one version show the same count. `foreignDevices` +counts the devices outside Simlock that use the component: simulators in +Xcode's default device set, AVDs in the user's own AVD home. + +A platform whose tools cannot answer is left out. `400 BAD_REQUEST` for a +`platform` other than `ios` or `android`; `501 UNSUPPORTED_IN_GATEWAY_MODE` +from a gateway, which owns no components — ask the worker. + ### `DELETE /v1/leases/{id}` Role: `agent` (own lease); `operator` may release any lease. @@ -919,7 +958,7 @@ Every failure is the same shape the daemon protocol uses: | 404 | `UNKNOWN_WORKER` (`POST`/`DELETE /v1/workers/{id}/drain` naming a worker the gateway does not know), `UNKNOWN_LEASE_REQUEST` (unknown request id), `UNKNOWN_LEASE` (unknown lease id, expired/released, **or `GET /v1/leases/{id}`/`GET /v1/leases/{id}/events` naming another requester's lease** — see [`GET /v1/leases/{id}`](#get-v1leasesid)) | | 409 | `REQUESTER_ALREADY_LEASED` (body names the existing lease id; fleet-wide on a gateway), `IDEMPOTENCY_CONFLICT` (an `Idempotency-Key` repeated with a different device), `REQUEST_NOT_CANCELLABLE` (body names the lease id if the request had already been granted), `WORKER_CONNECTED` (`DELETE /v1/workers/{id}` while its uplink is open) | | 422 | `UNKNOWN_MODEL`, `RUNTIME_MISSING`, `NO_DRIVER`, `PASSTHROUGH_REFUSED` (a refused `exec` verb, a caller-supplied `--set`/`-P`, a bare `adb shell`), `UNKNOWN_PASSTHROUGH_TOOL` | -| 501 | `UNSUPPORTED_IN_GATEWAY_MODE` (an operation that acts on one machine, asked of a gateway: `POST /v1/components/install`) | +| 501 | `UNSUPPORTED_IN_GATEWAY_MODE` (an operation that acts on one machine, asked of a gateway: `POST /v1/components/install`, `GET /v1/components`) | | 503 | `NO_CAPACITY` (only with `noWait: true`; response carries `Retry-After`), `WORKER_UNREACHABLE` (a gateway could not reach the worker holding this lease or request) | | 504 | `EXEC_TIMEOUT` (a `device.exec` command outlived `exec.timeoutMs`), `DOWNLOAD_TIMEOUT` (a runtime download, waiting for another download included, outlived `downloads.timeoutMs`) | @@ -933,15 +972,16 @@ behind this is not reachable right now" is the same answer in all four cases, and a client with one retry rule for `transport` should not need a second one because the unreachable thing happened to be a worker. -`UNSUPPORTED_IN_GATEWAY_MODE` comes from one route in this version, -`POST /v1/components/install` asked of a gateway — `nuke`, `cleanup`, and +`UNSUPPORTED_IN_GATEWAY_MODE` comes from two routes in this version, +`POST /v1/components/install` and `GET /v1/components` asked of a gateway — +`nuke`, `cleanup`, and `doctor` are absent from the HTTP surface (see [Not implemented](#not-implemented)), and the status is fixed so adding `POST /v1/doctor` or `POST /v1/cleanup` later is additive rather than a fresh decision. `501` is the honest status for it: this is not a temporary condition to retry past, it is an operation this daemon will never perform, -and `nuke`/`cleanup`/`doctor`/`driver.passthrough`/component installs stay -per-worker permanently rather than pending some later fan-out. +and `nuke`/`cleanup`/`doctor`/`driver.passthrough`/component installs and +listings stay per-worker permanently rather than pending some later fan-out. `EXEC_TIMEOUT`'s `504` is documented for completeness rather than for the exec route: `POST /v1/leases/{id}/exec` has already answered `200` and begun diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 05198fb25..7350bb99d 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -177,7 +177,7 @@ agent / console ──token auth──> │ HTTP frontend + unix socket on HTTP — that is how agents reach it and what the uplink upgrades from — so `http.enabled: false` in gateway mode fails the start rather than being silently overridden. `nuke.run`, `cleanup.run`, `doctor.run`, - `driver.passthrough` and `component.install` answer + `driver.passthrough`, `component.install` and `component.list` answer `UNSUPPORTED_IN_GATEWAY_MODE` permanently: they act on one machine's devices or components, and stay per-worker. The lease lifecycle (`lease.request`/`renew`/`release`/`cancel`/`release-all`) and `device.exec` @@ -1443,6 +1443,35 @@ event. Neither transport stops the install when its client goes away; a repeat joins it. A gateway answers `UNSUPPORTED_IN_GATEWAY_MODE`; relaying to workers is a separate gateway operation. +The listing is `component.list` (ADR 0010 §8), an agent read with input +`{ platform? }`, behind `simlock component list`, `listComponents` on the +client and `GET /v1/components`. Each driver answers +`listComponents()`: one entry per installed component with its version, its +`variant` (the driver's own words, carried unread: the build on iOS, tag and +ABI on Android), its size when readable, its receipt from the same function +`findComponent` and `installComponent` use, and `foreignDevices`. It is +read-only, never downloads, and every process it starts is bounded, like +`listCatalog`. iOS reads `simctl runtime list -j` (iOS images only) and +counts devices per runtime in the default device set with an unscoped +`simctl list -j devices`, the one unscoped call besides the pre-root path's. +Android reads the installed images, sizes each directory with +`Filesystem.directorySize`, and counts AVDs in the user's own AVD home whose +`config.ini` names the image's directory. On both platforms a foreign-device +read that fails rejects the listing rather than undercount. Counting foreign devices is the +only place a driver looks at devices outside its root; it reads them and +never writes there (safety rule 1). + +`ComponentInstaller.list(platform?)` merges each driver's listing with the +registry: `installedBySimlock` is true when a `ComponentRecord` of that +platform has a receipt equal (`sameReceipt`) to the entry's, and +`installedAt` is that record's time — the record is the only proof (ADR 0010 +§5, safety rule 8). `devices` counts registry devices of that platform and +version in any state but `deleted`; the core cannot tell variants apart, so +two variants of one version show the same count. A driver whose listing +rejects is left out and logged, and the other platform is still listed. +Entries are ordered by platform, then version, then variant. A gateway +answers `UNSUPPORTED_IN_GATEWAY_MODE`. + ## External APIs behind interfaces (ports) Every external API the app touches gets its own type/interface (a *port*), diff --git a/e2e/component-list.test.ts b/e2e/component-list.test.ts new file mode 100644 index 000000000..b49fd15b8 --- /dev/null +++ b/e2e/component-list.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; + +import { withDaemon } from "./helpers/index.js"; + +describe("simlock component list", () => { + it("lists a component installed with simlock component install as Simlock's, and one scripted as already present as not", async () => { + const env = await withDaemon(); + await env.driverScript.set({ + ios: { + availableOsVersions: ["18.4"], + componentSizes: { "18.4": 8_000_000_000, "19.0": 9_000_000_000 }, + foreignDevices: { "18.4": 1 }, + }, + }); + + const install = await env.cli(["component", "install", "ios", "19.0"]); + expect(install.code, install.stderr).toBe(0); + const listed = await env.cli(["component", "list", "--platform", "ios"]); + + expect(listed.code, listed.stderr).toBe(0); + expect(listed.json).toEqual({ + components: [ + { + devices: 0, + foreignDevices: 1, + installedBySimlock: false, + platform: "ios", + sizeBytes: 8_000_000_000, + version: "18.4", + }, + { + devices: 0, + foreignDevices: 0, + installedAt: expect.any(Number), + installedBySimlock: true, + platform: "ios", + sizeBytes: 9_000_000_000, + version: "19.0", + }, + ], + }); + }); + + it("answers an agent session", async () => { + const env = await withDaemon(); + await env.driverScript.set({ ios: { availableOsVersions: ["18.4"] } }); + + // A credential the daemon rejects falls back to an agent session (with a notice). + const listed = await env.cli([ + "--token", + "not-an-admin-credential", + "component", + "list", + "--platform", + "ios", + ]); + + expect(listed.code, listed.stderr).toBe(0); + expect(listed.stderr).toContain("connecting as agent"); + expect(listed.json).toMatchObject({ components: [{ platform: "ios", version: "18.4" }] }); + }); +}); diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index 48c86473b..5f35bb82b 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -13,6 +13,7 @@ import { type DeviceRequest, type Driver, type DriverCatalogEntry, + type DriverComponent, type DriverDevice, type DriverEstimate, type DriverReality, @@ -290,6 +291,26 @@ export class OutOfProcessFakeDriver implements Driver { return { outcome: "installed", receipt, version: component }; } + /** + * One entry per available version, with the receipt `findComponent` reports for it; sizes and + * foreign devices come from `componentSizes` and `foreignDevices`. + */ + async listComponents(): Promise { + const script = await this.#beforeCall("listComponents", []); + return this.#available(script).flatMap((version): DriverComponent[] => { + const found = this.#find(version, script); + if (found === undefined) return []; + const sizeBytes = script.componentSizes?.[version]; + return [ + { + ...found, + foreignDevices: script.foreignDevices?.[version] ?? 0, + ...(sizeBytes === undefined ? {} : { sizeBytes }), + }, + ]; + }); + } + #find(component: string, script: FakeDriverPlatformScript): InstalledComponent | undefined { if (!this.#available(script).includes(component)) return undefined; return { diff --git a/e2e/fake-driver/types.ts b/e2e/fake-driver/types.ts index 0d683a44f..2745255e0 100644 --- a/e2e/fake-driver/types.ts +++ b/e2e/fake-driver/types.ts @@ -18,6 +18,7 @@ export type FakeDriverOperation = | "destroy" | "listManaged" | "listCatalog" + | "listComponents" /** The root re-proof `doctor --purge-orphans` takes before its first destroy. */ | "revalidateRoot"; @@ -95,6 +96,10 @@ export interface FakeDriverPlatformScript { * `failures.installComponent` makes it fail. */ readonly installProgress?: readonly number[]; + /** What `listComponents` reports as each version's size in bytes; absent for one left out. */ + readonly componentSizes?: Readonly>; + /** What `listComponents` reports as each version's foreign devices; 0 for one left out. */ + readonly foreignDevices?: Readonly>; readonly latencyMs?: Partial>; readonly estimateMs?: Partial>; readonly reclaimResult?: "ready" | "shutdown"; diff --git a/src/admin/index.ts b/src/admin/index.ts index a8e27c8af..d4dede6ac 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -15,6 +15,8 @@ export type { AnySimlockError, CatalogGetInput, CatalogGetOutput, + ComponentListInput, + ComponentListOutput, CleanupRunInput, CleanupRunOutput, ComponentInstallInput, diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 866f8a7bb..9c07a0665 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1897,7 +1897,10 @@ describe("CLI: component install (ADR 0010 §6)", () => { }), ), ).resolves.toBe(0); - expect(output.stdout).toBe("Usage: simlock component install \n"); + expect(output.stdout).toBe( + "Usage: simlock component install \n" + + " simlock component list [--platform ]\n", + ); expect(connected).toBe(false); }, ); @@ -1909,6 +1912,91 @@ describe("CLI: component install (ADR 0010 §6)", () => { }); }); +describe("CLI: component list (ADR 0010 §8)", () => { + const listing = { + components: [ + { + devices: 2, + foreignDevices: 1, + installedAt: 1_790_864_071_200, + installedBySimlock: true, + platform: "android" as const, + sizeBytes: 4_200_000_000, + variant: "google_apis/arm64-v8a", + version: "35", + }, + ], + }; + + it("prints the daemon's component.list answer as one JSON object on stdout, and exits 0", async () => { + const output = outputCapture(); + const asked: unknown[] = []; + const client = fakeClient({ + listComponents: async (input) => { + asked.push(input); + return listing; + }, + }); + + await expect( + runCli(["component", "list"], output.environmentWith({ connectAdmin: async () => client })), + ).resolves.toBe(0); + + expect(asked).toEqual([{}]); + expect(output.stdout.trim().split("\n")).toHaveLength(1); + expect(JSON.parse(output.stdout)).toEqual(listing); + }); + + it("asks for one platform with --platform", async () => { + const output = outputCapture(); + const asked: unknown[] = []; + const client = fakeClient({ + listComponents: async (input) => { + asked.push(input); + return { components: [] }; + }, + }); + + await expect( + runCli( + ["component", "list", "--platform", "ios"], + output.environmentWith({ connectAdmin: async () => client }), + ), + ).resolves.toBe(0); + + expect(asked).toEqual([{ platform: "ios" }]); + }); + + it.each([ + ["an unknown platform", ["component", "list", "--platform", "tvos"]], + ["a positional argument", ["component", "list", "ios"]], + ["an unknown flag", ["component", "list", "--json"]], + ])("exits 2 with USAGE for %s, without asking the daemon", async (_label, argv) => { + const output = outputCapture(); + let listed = 0; + const client = fakeClient({ + listComponents: () => { + listed += 1; + return Promise.resolve({ components: [] }); + }, + }); + + await expect( + runCli(argv, output.environmentWith({ connectAdmin: async () => client })), + ).resolves.toBe(2); + expect(listed).toBe(0); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toMatchObject({ + error: { code: "USAGE" }, + }); + }); + + it("lists the command in the usage banner", async () => { + const output = outputCapture(); + await runCli(["--help"], output.environmentWith({})); + expect(output.stdout).toContain("component list [--platform ]"); + }); +}); + describe("CLI: worker commands (ADR 0005 §8/§23)", () => { const connectedWorker = { capacity: { @@ -3941,6 +4029,7 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl daemonVersion: "test", getCatalog: () => Promise.resolve(emptyCatalog), getStatus: () => Promise.resolve(EMPTY_STATUS), + listComponents: () => Promise.resolve({ components: [] }), requestLease: (_input, _options) => Promise.resolve(grant), resolvePassthrough: () => Promise.resolve({ args: [], command: "adb", env: {} }), exec: () => Promise.resolve({ exitCode: 0 }), diff --git a/src/cli/index.ts b/src/cli/index.ts index 3278a44d9..dd1cc4b92 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -59,6 +59,8 @@ Commands: Inspect and manage the workers of a gateway component install Install a simulator runtime or system image + component list [--platform ] + List installed runtimes and system images simctl Run xcrun simctl against Simlock's iOS device set adb Run adb against Simlock's adb server mcp Start the stdio MCP server @@ -1838,7 +1840,9 @@ async function runWorkerAction( return 0; } -const COMPONENT_USAGE = "Usage: simlock component install \n"; +const COMPONENT_USAGE = + "Usage: simlock component install \n" + + " simlock component list [--platform ]\n"; /** * ADR 0010 §6: installs one component through the daemon's `component.install`. Argument @@ -1856,6 +1860,7 @@ async function runComponent( environment.stdout.write(COMPONENT_USAGE); return 0; } + if (command === "list") return runComponentList(argv.slice(1), environment, token); if (command !== "install") { throw new UsageError(withHelpHint(`Unknown component command: ${command}`)); } @@ -1878,6 +1883,41 @@ async function runComponent( } } +/** + * ADR 0010 §8: `component list` renders the daemon's `component.list` as one JSON object on + * stdout. Which components are Simlock's, and how many devices use each, is the daemon's answer. + */ +async function runComponentList( + argv: readonly string[], + environment: CliEnvironment, + token: string | undefined, +): Promise { + const values = commandArgs(argv, { + help: { type: "boolean", short: "h" }, + platform: { type: "string" }, + }); + if (values.help) { + environment.stdout.write(COMPONENT_USAGE); + return 0; + } + if (values.positionals.length > 0) { + throw new UsageError(withHelpHint("component list takes no positional arguments")); + } + if (values.platform !== undefined && values.platform !== "ios" && values.platform !== "android") + throw new UsageError("component list --platform must be ios or android"); + const platform = values.platform as "ios" | "android" | undefined; + const client = await connectDaemonClient(environment, token); + try { + writeResult( + environment, + await client.listComponents(platform === undefined ? {} : { platform }), + ); + return 0; + } finally { + await client.close(); + } +} + /** `component install`'s arguments: exactly a platform and a version, or `--help`. */ function parseComponentInstallArgs( argv: readonly string[], diff --git a/src/client/index.ts b/src/client/index.ts index 9d153f039..c7cb470da 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -19,6 +19,8 @@ export type { AnySimlockError, CatalogGetInput, CatalogGetOutput, + ComponentListInput, + ComponentListOutput, DeviceRecoveredPush, DeviceUnhealthyPush, ExecInput, diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 3a4a4ccb4..366a0581a 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -66,6 +66,7 @@ const ROLE_MATRIX: ReadonlyArray<{ { name: "worker.remove", input: { workerId: "wrk_1" }, role: "admin" }, // ADR 0010 §6: an operator's consent to a download. { name: "component.install", input: { platform: "ios", version: "26.4" }, role: "admin" }, + { name: "component.list", input: {}, role: "agent" }, ]; describe("operation role matrix", () => { @@ -130,6 +131,7 @@ const EFFECT_MATRIX: ReadonlyArray<{ { name: "worker.undrain", input: { workerId: "wrk_1" }, effect: "write" }, { name: "worker.remove", input: { workerId: "wrk_1" }, effect: "write" }, { name: "component.install", input: { platform: "ios", version: "26.4" }, effect: "write" }, + { name: "component.list", input: {}, effect: "read" }, ]; function resolvedEffect(name: OperationName, input: unknown): unknown { diff --git a/src/contract/operations.ts b/src/contract/operations.ts index d17bc44c6..408c0f302 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -711,6 +711,39 @@ export const componentInstall = defineOperation({ }), }); +// ---- component.list (ADR 0010 §8) ----------------------------------------------------------- + +/** + * Every installed iOS simulator runtime and Android system image on this machine, ordered by + * platform, then version, then variant. A read for any session. `installedBySimlock` is true only + * when Simlock's record of an install names this exact component; `installedAt` is that + * record's time. `devices` counts Simlock's own devices of this platform and version in any + * state but deleted, so two variants of one version show the same count; `foreignDevices` + * counts the devices outside Simlock that use it. `variant` tells two components of one + * version apart, in the platform's own words; `sizeBytes` is absent when it could not be read. + */ +// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. +export const componentList = defineOperation({ + name: "component.list", + role: "agent", + effect: "read", + input: z.object({ platform: platformSchema.optional() }), + output: z.object({ + components: z.array( + z.object({ + platform: platformSchema, + version: z.string(), + variant: z.string().optional(), + sizeBytes: z.number().int().nonnegative().optional(), + installedBySimlock: z.boolean(), + installedAt: z.number().int().optional(), + devices: z.number().int().nonnegative(), + foreignDevices: z.number().int().nonnegative(), + }), + ), + }), +}); + // ---- the full registry ---------------------------------------------------------------------- export const OPERATIONS = { @@ -741,6 +774,7 @@ export const OPERATIONS = { "worker.undrain": workerUndrain, "worker.remove": workerRemove, "component.install": componentInstall, + "component.list": componentList, } as const; /** diff --git a/src/core/component-installer.test.ts b/src/core/component-installer.test.ts index 5398c1a8b..3585c27f5 100644 --- a/src/core/component-installer.test.ts +++ b/src/core/component-installer.test.ts @@ -1,7 +1,13 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, type Filesystem, MemoryFilesystem, type TimerHandle } from "../ports/index.js"; +import { + FakeClock, + type Filesystem, + type Logger, + MemoryFilesystem, + type TimerHandle, +} from "../ports/index.js"; import { ComponentInstaller, ComponentInstallerClosedError, @@ -11,6 +17,7 @@ import { import { ComponentInstallTimeoutError, DiskSpaceGuard, + type DriverComponent, DriverCrashError, InsufficientDiskSpaceError, } from "./driver.js"; @@ -52,6 +59,7 @@ async function createHarness( readonly decisions?: Pick; readonly filesystem?: (clock: FakeClock) => Pick; readonly freeDiskBytes?: number; + readonly logger?: Logger; } = {}, ) { const clock = options.clock ?? new FakeClock(1_000); @@ -66,11 +74,12 @@ async function createHarness( new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }), ]; const stateFilesystem = new MemoryFilesystem(); + let nextId = 0; const registry = await Registry.load({ clock, eventBus: bus, filesystem: stateFilesystem, - idGenerator: { generate: () => "id" }, + idGenerator: { generate: () => `id${String((nextId += 1))}` }, statePath, }); // Every reservation the installer takes, and whether it gave it back. @@ -93,6 +102,7 @@ async function createHarness( drivers: new DriverCatalog(drivers), eventBus: bus, filesystem: options.filesystem?.(clock) ?? new MemoryFilesystem(options.freeDiskBytes), + ...(options.logger === undefined ? {} : { logger: options.logger }), registry, timeoutMs, }); @@ -920,3 +930,260 @@ describe("ComponentInstaller.inProgress", () => { ); }); }); + +/** A fake whose `listComponents` answers with exactly what a test lists. */ +class ListingDriver extends FakeDriver { + constructor( + clock: FakeClock, + platform: "ios" | "android", + private readonly listing: readonly DriverComponent[], + ) { + super({ availableOsVersions: [], clock, platform }); + } + + override listComponents(): Promise { + return Promise.resolve(this.listing); + } +} + +async function addDevice( + registry: Registry, + platform: "ios" | "android", + osVersion: string, +): Promise { + const device = await registry.registerDevice({ + driverData: {}, + driverDeviceId: `${platform}-${osVersion}-${String(registry.snapshot.devices.length)}`, + provisionDuration: 0, + spec: { model: "Phone", osVersion, platform }, + }); + return device.id; +} + +describe("ComponentInstaller.list", () => { + it("lists a component Simlock installed with installedBySimlock true and the time its record was written", async () => { + const harness = await createHarness({ + drivers: (clock) => [new FakeDriver({ availableOsVersions: [], clock, platform: "ios" })], + }); + harness.clock.advance(4_000); + + await harness.installer.install(ios("27.0")); + + expect(await harness.installer.list()).toEqual([ + { + devices: 0, + foreignDevices: 0, + installedAt: 5_000, + installedBySimlock: true, + platform: "ios", + version: "27.0", + }, + ]); + }); + + it("lists a component that was on the machine before with installedBySimlock false and no installedAt", async () => { + const harness = await createHarness(); + + expect(await harness.installer.list()).toEqual([ + { + devices: 0, + foreignDevices: 0, + installedBySimlock: false, + platform: "ios", + version: "26.5", + }, + ]); + }); + + it("marks nothing as Simlock's for a record of that platform and version whose receipt no longer equals the installed one", async () => { + const harness = await createHarness(); + await harness.registry.recordComponent({ + installedAt: 1_000, + platform: "ios", + receipt: { install: "1", version: "26.5" }, + version: "26.5", + }); + + const [listed] = await harness.installer.list(); + + expect(listed).toMatchObject({ installedBySimlock: false, version: "26.5" }); + expect(listed).not.toHaveProperty("installedAt"); + }); + + it("does not take a record of another platform with an equal receipt as proof", async () => { + const harness = await createHarness(); + await harness.registry.recordComponent({ + installedAt: 1_000, + platform: "android", + receipt: { preinstalled: "26.5" }, + version: "26.5", + }); + + const [listed] = await harness.installer.list(); + + expect(listed).toMatchObject({ installedBySimlock: false, platform: "ios" }); + }); + + it("counts registry devices of that platform and version, and not deleted ones", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ availableOsVersions: ["26.5", "27.0"], clock, platform: "ios" }), + ], + }); + await addDevice(harness.registry, "ios", "26.5"); + await addDevice(harness.registry, "ios", "26.5"); + const deleted = await addDevice(harness.registry, "ios", "26.5"); + await harness.registry.markDeviceMissing(deleted, "test"); + await addDevice(harness.registry, "ios", "27.0"); + // Same version string on the other platform: not a device of this component. + await addDevice(harness.registry, "android", "26.5"); + + const listed = await harness.installer.list(); + + expect(listed.map(({ devices, version }) => ({ devices, version }))).toEqual([ + { devices: 2, version: "26.5" }, + { devices: 1, version: "27.0" }, + ]); + }); + + it("shows the devices of a version on both of its variants", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new ListingDriver(clock, "android", [ + { + foreignDevices: 0, + receipt: { image: "a" }, + variant: "google_apis/arm64-v8a", + version: "35", + }, + { + foreignDevices: 0, + receipt: { image: "b" }, + variant: "default/arm64-v8a", + version: "35", + }, + ]), + ], + }); + await addDevice(harness.registry, "android", "35"); + await addDevice(harness.registry, "android", "35"); + + const listed = await harness.installer.list(); + + expect(listed.map(({ devices, variant }) => ({ devices, variant }))).toEqual([ + { devices: 2, variant: "default/arm64-v8a" }, + { devices: 2, variant: "google_apis/arm64-v8a" }, + ]); + }); + + it("carries the driver's size, variant and foreign devices through unread", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new ListingDriver(clock, "ios", [ + { + foreignDevices: 3, + receipt: { image: "x" }, + sizeBytes: 9 * gibibyte, + variant: "23A343", + version: "26.0", + }, + ]), + ], + }); + + expect(await harness.installer.list()).toEqual([ + { + devices: 0, + foreignDevices: 3, + installedBySimlock: false, + platform: "ios", + sizeBytes: 9 * gibibyte, + variant: "23A343", + version: "26.0", + }, + ]); + }); + + it("orders by platform, then version as numbers, then variant", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new ListingDriver(clock, "ios", [ + { foreignDevices: 0, receipt: { r: "1" }, version: "26.4" }, + { foreignDevices: 0, receipt: { r: "2" }, version: "9.3" }, + ]), + new ListingDriver(clock, "android", [ + { foreignDevices: 0, receipt: { r: "3" }, variant: "z", version: "35" }, + { foreignDevices: 0, receipt: { r: "4" }, variant: "a", version: "35" }, + { foreignDevices: 0, receipt: { r: "5" }, variant: "a", version: "9" }, + ]), + ], + }); + + const listed = await harness.installer.list(); + + expect(listed.map(({ platform, variant, version }) => [platform, version, variant])).toEqual([ + ["android", "9", "a"], + ["android", "35", "a"], + ["android", "35", "z"], + ["ios", "9.3", undefined], + ["ios", "26.4", undefined], + ]); + }); + + it("asks only the named platform's driver when given a platform", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }), + new FakeDriver({ availableOsVersions: ["35"], clock, platform: "android" }), + ], + }); + + const listed = await harness.installer.list("android"); + + expect(listed.map((component) => component.platform)).toEqual(["android"]); + expect(harness.ios.calls.some((call) => call.operation === "listComponents")).toBe(false); + }); + + it("leaves out a driver whose listing rejects, logs why, and still lists the other platform", async () => { + const warnings: { readonly message: string; readonly fields: unknown }[] = []; + const logger: Logger = { + child: () => logger, + debug: () => {}, + error: () => {}, + info: () => {}, + warn: (message, fields) => { + warnings.push({ fields, message }); + }, + }; + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }), + new FakeDriver({ availableOsVersions: ["35"], clock, platform: "android" }), + ], + logger, + }); + harness.ios.failOn("listComponents", 1, new DriverCrashError("simctl runtime list failed")); + + const listed = await harness.installer.list(); + + expect(listed.map((component) => [component.platform, component.version])).toEqual([ + ["android", "35"], + ]); + expect(warnings).toEqual([ + { + fields: { error: "DriverCrashError: simctl runtime list failed", platform: "ios" }, + message: "A driver could not list its installed components", + }, + ]); + }); + + it("starts no install, takes no reservation and emits no event", async () => { + const harness = await createHarness(); + + await harness.installer.list(); + + expect(installs(harness.ios)).toEqual([]); + expect(harness.reservations).toEqual([]); + expect(harness.events).toEqual([]); + }); +}); diff --git a/src/core/component-installer.ts b/src/core/component-installer.ts index 80c8e39df..573317306 100644 --- a/src/core/component-installer.ts +++ b/src/core/component-installer.ts @@ -1,5 +1,11 @@ import type { EventBus } from "../bus/index.js"; -import type { Clock, Filesystem, TimerHandle } from "../ports/index.js"; +import { + type Clock, + type Filesystem, + type Logger, + NoopLogger, + type TimerHandle, +} from "../ports/index.js"; import type { Platform } from "./domain.js"; import { type ComponentInstallProgress, @@ -7,6 +13,8 @@ import { ComponentInstallTimeoutError, type DiskSpaceGuard, type Driver, + type DriverComponent, + sameReceipt, } from "./driver.js"; import type { DriverCatalog } from "./driver-catalog.js"; import type { Registry } from "./registry.js"; @@ -50,10 +58,12 @@ export interface ComponentInstallerOptions { */ readonly decisions: Pick; readonly diskSpace: Pick; - readonly drivers: Pick; + readonly drivers: Pick; readonly eventBus: Pick; readonly filesystem: Pick; - readonly registry: Pick; + /** Hears a driver whose `listComponents` rejects; `list` leaves that driver out. */ + readonly logger?: Logger; + readonly registry: Pick; /** `downloads.timeoutMs`: one budget per call, from the moment `install` is called. */ readonly timeoutMs: number; } @@ -74,6 +84,24 @@ export interface ComponentInstallInProgress { readonly waiters: number; } +/** + * One installed component as `list` reports it (ADR 0010 §8). `installedBySimlock` is true only + * when a component record's receipt equals this component's: the record is the only proof (§5). + * `devices` counts Simlock's own devices of this platform and version in any state but + * `deleted`; the core cannot tell variants apart, so two variants of one version show the same + * count. `variant` and `foreignDevices` are the driver's, carried unread. + */ +export interface InstalledComponentListing { + readonly platform: Platform; + readonly version: string; + readonly variant?: string; + readonly sizeBytes?: number; + readonly installedBySimlock: boolean; + readonly installedAt?: number; + readonly devices: number; + readonly foreignDevices: number; +} + /** `inProgress()` lists at most this many installs, the oldest first. */ const MAX_LISTED_INSTALLS = 16; @@ -133,7 +161,11 @@ export class ComponentInstaller { readonly #runs = new Set>(); #closed = false; - constructor(private readonly options: ComponentInstallerOptions) {} + readonly #logger: Logger; + + constructor(private readonly options: ComponentInstallerOptions) { + this.#logger = options.logger ?? new NoopLogger(); + } install(request: ComponentInstallRequest): Promise { if (this.#closed) return Promise.reject(new ComponentInstallerClosedError()); @@ -197,6 +229,55 @@ export class ComponentInstaller { return listed.sort((a, b) => a.since - b.since).slice(0, MAX_LISTED_INSTALLS); } + /** + * Every installed component on this platform's driver, or on every driver, ordered by + * platform, then version, then variant. Read-only: it asks each driver's `listComponents` and + * reads the registry, and writes nothing. A driver whose listing rejects is left out and + * logged, and the other platforms are still listed. + */ + // fallow-ignore-next-line unused-class-member -- reached through the Dispatcher's `components` option, typed as a Pick of this class. + async list(platform?: Platform): Promise { + const listed = await Promise.all( + this.options.drivers.select(platform).map(async (driver) => { + try { + return { components: await driver.listComponents(), platform: driver.platform }; + } catch (error: unknown) { + this.#logger.warn("A driver could not list its installed components", { + error: stableError(error), + platform: driver.platform, + }); + return { components: [], platform: driver.platform }; + } + }), + ); + const { components: records, devices } = this.options.registry.snapshot; + return listed + .flatMap(({ components, platform: listedPlatform }) => + components.map((component): InstalledComponentListing => { + const record = records.find( + (candidate) => + candidate.platform === listedPlatform && + sameReceipt(candidate.receipt, component.receipt), + ); + return { + devices: devices.filter( + (device) => + device.state !== "deleted" && + device.spec.platform === listedPlatform && + device.spec.osVersion === component.version, + ).length, + foreignDevices: component.foreignDevices, + installedBySimlock: record !== undefined, + platform: listedPlatform, + version: component.version, + ...(record === undefined ? {} : { installedAt: record.installedAt }), + ...optionalFields(component), + }; + }), + ) + .sort(compareListings); + } + /** * Ends the running installs through their `AbortSignal`, rejects every open call, and resolves * once each driver run has returned. Nothing is resumed after a restart. @@ -427,3 +508,26 @@ function notify(call: InstallCall, progress: ComponentInstallerProgress): void { // Isolated like an event handler (events rule 5). } } + +function optionalFields( + component: DriverComponent, +): Pick { + return { + ...(component.variant === undefined ? {} : { variant: component.variant }), + ...(component.sizeBytes === undefined ? {} : { sizeBytes: component.sizeBytes }), + }; +} + +const ORDER = new Intl.Collator("en", { numeric: true }); + +/** By platform, then version (numerically, so `9` precedes `35`), then variant. */ +function compareListings( + left: InstalledComponentListing, + right: InstalledComponentListing, +): number { + return ( + ORDER.compare(left.platform, right.platform) || + ORDER.compare(left.version, right.version) || + ORDER.compare(left.variant ?? "", right.variant ?? "") + ); +} diff --git a/src/core/driver-catalog.ts b/src/core/driver-catalog.ts index f898db109..b40def341 100644 --- a/src/core/driver-catalog.ts +++ b/src/core/driver-catalog.ts @@ -77,17 +77,20 @@ export class DriverCatalog { * omitted rather than raising `NoDriverError` — mirrors `discoverDrivers`. */ async listCatalog(platform?: Platform): Promise { - const drivers = - platform === undefined ? [...this.#drivers.values()] : this.#driverIfKnown(platform); return Promise.all( - drivers.map(async (driver) => ({ + this.select(platform).map(async (driver) => ({ platform: driver.platform, ...(await driver.listCatalog()), })), ); } - #driverIfKnown(platform: Platform): readonly Driver[] { + /** + * Every registered driver, or only the given platform's. A platform with no registered driver + * gives none rather than raising `NoDriverError`: a read across platforms leaves it out. + */ + select(platform?: Platform): readonly Driver[] { + if (platform === undefined) return [...this.#drivers.values()]; const driver = this.#drivers.get(platform); return driver === undefined ? [] : [driver]; } diff --git a/src/core/driver.ts b/src/core/driver.ts index 1070c3b2b..befbb3c66 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -229,6 +229,13 @@ export interface Driver { * installer reports a size before it downloads, so this is what `ComponentInstaller` reserves. */ readonly componentFootprint: { readonly path: string; readonly bytes: number }; + /** + * Every component installed on the machine now, one entry each (ADR 0010 §8). Read-only, never + * downloads, and every process it starts is bounded: the same contract as `listCatalog`. + * Counting `foreignDevices` is the only place a driver looks at devices outside its own root; + * it reads them and never writes there (safety rule 1). + */ + listComponents(): Promise; provision(spec: DeviceSpec): Promise; /** * Boots the device and returns it with a freshly read `address`. Never trust the address a @@ -463,6 +470,19 @@ export interface InstalledComponent { readonly receipt: ComponentReceipt; } +/** + * One component `listComponents` found installed. `receipt` is built by the same function + * `findComponent` and `installComponent` use, so a listed component and the record of its install + * compare equal with `sameReceipt`. `variant` is the driver's own words for what tells two + * components of one version apart, carried unread. `sizeBytes` is absent when the driver could + * not read it. `foreignDevices` counts the devices outside Simlock's root that use it. + */ +export interface DriverComponent extends InstalledComponent { + readonly variant?: string; + readonly sizeBytes?: number; + readonly foreignDevices: number; +} + /** * What one `installComponent` run ended with. `installed` when the receipt was not there before * the run; `already-installed` when it was, so Simlock never records a component it did not put diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index a8a8400f2..5fdb1bd8a 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -8,6 +8,7 @@ import { type Driver, type DriverCatalogEntry, type DriverCatalogImage, + type DriverComponent, type DriverDevice, type DriverEstimate, type DriverReality, @@ -32,6 +33,7 @@ export type FakeDriverOperation = | "destroy" | "listManaged" | "listCatalog" + | "listComponents" /** Recorded like every other call, so a test can pin that it precedes the first destroy. */ | "revalidateRoot" | "findLegacy" @@ -51,6 +53,10 @@ export interface FakeDriverOptions { readonly componentFootprint?: { readonly path: string; readonly bytes: number }; /** The percentages every `installComponent` reports through `onProgress`, in order. */ readonly installProgress?: readonly number[]; + /** What `listComponents` reports as each version's size; absent for a version left out. */ + readonly componentSizes?: Readonly>; + /** What `listComponents` reports as each version's foreign devices; 0 for one left out. */ + readonly foreignDevices?: Readonly>; /** Stands in for a real driver's owned root; nothing here validates or creates it. */ readonly deviceRoot?: string; readonly estimateMs?: Partial>; @@ -124,7 +130,10 @@ export class FakeDriver implements Driver { /** One receipt per installed version; an install replaces it with a new one. */ readonly #receipts: Map; #installCount = 0; - readonly #install: Pick; + readonly #install: Pick< + FakeDriverOptions, + "componentFootprint" | "componentSizes" | "foreignDevices" | "installProgress" + >; #holdInstalls = false; readonly #pendingInstalls: (() => void)[] = []; readonly #callCounts = new Map(); @@ -270,6 +279,26 @@ export class FakeDriver implements Driver { return { outcome: "installed", receipt, version }; } + /** + * One entry per available version, with the receipt `findComponent` and `installComponent` + * report for it, and the scripted size and foreign devices. + */ + async listComponents(): Promise { + await this.#beforeCall("listComponents"); + return [...this.#availableOsVersions].flatMap((version): DriverComponent[] => { + const installed = this.#installed(version); + if (installed === undefined) return []; + const sizeBytes = this.#install.componentSizes?.[version]; + return [ + { + ...installed, + foreignDevices: this.#install.foreignDevices?.[version] ?? 0, + ...(sizeBytes === undefined ? {} : { sizeBytes }), + }, + ]; + }); + } + holdInstalls(): void { this.#holdInstalls = true; } diff --git a/src/core/index.ts b/src/core/index.ts index 7af9625a9..5b39531f6 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -32,6 +32,7 @@ export { type Driver, type DriverAdvisory, type DriverCatalogEntry, + type DriverComponent, DriverCrashError, type DriverDevice, type DriverEstimate, diff --git a/src/core/test-wiring.ts b/src/core/test-wiring.ts index d9ed5c5bc..bae7d0294 100644 --- a/src/core/test-wiring.ts +++ b/src/core/test-wiring.ts @@ -18,7 +18,7 @@ export function testComponentWiring< readonly clock: Clock; readonly drivers: readonly Driver[]; readonly eventBus: Pick; - readonly registry: Pick; + readonly registry: Pick; /** Stands in for the installer, when a test needs to see whether it was reached at all. */ readonly components?: Components | undefined; }): { diff --git a/src/daemon/admin-secret.test.ts b/src/daemon/admin-secret.test.ts index c041f4c8f..3b788bc5b 100644 --- a/src/daemon/admin-secret.test.ts +++ b/src/daemon/admin-secret.test.ts @@ -53,6 +53,7 @@ describe("AdminSecretManager", () => { readdir: () => Promise.reject(new Error("unused by this test")), exists: () => Promise.reject(new Error("unused by this test")), diskFree: () => Promise.reject(new Error("unused by this test")), + directorySize: () => Promise.reject(new Error("unused by this test")), writeFileExclusive: () => Promise.reject(new Error("unused by this test")), rename: () => Promise.reject(new Error("unused by this test")), lstat: () => Promise.reject(new Error("unused by this test")), @@ -135,6 +136,9 @@ describe("AdminSecretManager", () => { diskFree: () => { throw new Error("verify() must not touch the filesystem"); }, + directorySize: () => { + throw new Error("verify() must not touch the filesystem"); + }, writeFileExclusive: () => { throw new Error("verify() must not touch the filesystem"); }, @@ -208,6 +212,9 @@ describe("AdminSecretManager", () => { diskFree: () => { throw new Error("must not touch the filesystem"); }, + directorySize: () => { + throw new Error("must not touch the filesystem"); + }, writeFileExclusive: () => { throw new Error("must not touch the filesystem"); }, diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 68f9db556..0f0401881 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -149,7 +149,7 @@ async function buildDispatcher( readonly capacity?: Config["capacity"]; /** Stands in for the component installer: a test that needs to see whether it was reached, * or one that reads `status.get`'s installs from an installer of its own. */ - readonly components?: Pick; + readonly components?: Pick; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -1011,7 +1011,10 @@ describe("Dispatcher: status.get installs in progress", () => { drivers: new DriverCatalog([driver]), eventBus: new EventBus(clock), filesystem: new MemoryFilesystem(), - registry: { recordComponent: () => Promise.resolve() }, + registry: { + recordComponent: () => Promise.resolve(), + snapshot: { components: [], devices: [], leases: [] }, + }, timeoutMs: installTimeoutMs, }); const { dispatcher } = await buildDispatcher({ clock, components: installer }); @@ -1106,7 +1109,7 @@ describe("Dispatcher: component.install", () => { const install = vi.fn(() => Promise.resolve({ outcome: "installed" as const, version: "unreachable" }), ); - return { inProgress: () => [], install }; + return { inProgress: () => [], install, list: () => Promise.resolve([]) }; } function installCalls(driver: FakeDriver): unknown[] { @@ -1365,6 +1368,47 @@ describe("Dispatcher: component.install", () => { }); }); +describe("Dispatcher: component.list", () => { + it("lets an agent session list the installed components, the one Simlock installed marked as its", async () => { + const { clock, dispatcher } = await buildDispatcher(); + await dispatcher.dispatch( + "component.install", + { platform: "ios", version: "27.0" }, + session({ principal: "tok_operator", role: "admin" }), + ); + + const result = await dispatcher.dispatch("component.list", {}, session()); + + expect(result).toEqual({ + components: [ + { + devices: 0, + foreignDevices: 0, + installedBySimlock: false, + platform: "ios", + version: "26.5", + }, + { + devices: 0, + foreignDevices: 0, + installedAt: clock.now(), + installedBySimlock: true, + platform: "ios", + version: "27.0", + }, + ], + }); + }); + + it("lists only the platform asked for", async () => { + const { dispatcher } = await buildDispatcher(); + + await expect( + dispatcher.dispatch("component.list", { platform: "android" }, session()), + ).resolves.toEqual({ components: [] }); + }); +}); + describe("Dispatcher: status.get host facts", () => { it("reports operating system, version, architecture, and every driver's tool versions", async () => { const hostFacts = new HostFactsReader({ diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 92df403e5..7a8655d72 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -86,9 +86,10 @@ export interface DispatcherOptions { readonly clock: Clock; /** * The one installer (ADR 0010 §3), shared with the lease path so `component.install` and a - * lease request's download join one install, and read for `status.get`'s installs in progress. + * lease request's download join one install, and read for `status.get`'s installs in progress + * and for `component.list`. */ - readonly components: Pick; + readonly components: Pick; readonly config: Config; readonly doctor?: Doctor; /** Answers `events.replay`: the ring, or the event file for a `sinceTs`. */ @@ -220,6 +221,7 @@ export class Dispatcher { "token.list": this.#tokenList, "token.revoke": this.#tokenRevoke, "component.install": this.#componentInstall, + "component.list": this.#componentList, // "daemon.stop" deliberately absent -- see the class comment; `DaemonServer` never calls // `dispatch()` for a frame type this map has no entry for. }; @@ -636,6 +638,11 @@ export class Dispatcher { }; }; + /** ADR 0010 §8: a read for any session; the installer merges the drivers and the registry. */ + #componentList: Handler<"component.list"> = async (input) => ({ + components: await this.options.components.list(input.platform), + }); + /** * ADR §11: the daemon is the only owner of `tokens.json` -- `TokenStore.create` never * persists the plaintext `secret`, only its hash, exactly as it did when the CLI called it diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 661122d4a..3131edda5 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -321,6 +321,29 @@ describe("startDaemon", () => { expect(reads).toBe(1); }); + it("logs a driver whose component listing fails under daemon.components, and still answers component.list", async () => { + const clock = new FakeClock(1_000); + const ios = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); + ios.failOn("listComponents", 1, new Error("simctl runtime list failed")); + const { daemon, sink } = await start({ drivers: [ios] }); + + const listed = await daemon.dispatch( + "component.list", + {}, + { manageEventSubscription: () => undefined, principal: "agent", role: "agent" }, + ); + + expect(listed).toEqual({ components: [] }); + expect(sink.records).toContainEqual( + expect.objectContaining({ + fields: { error: "Error: simctl runtime list failed", platform: "ios" }, + level: "warn", + message: "A driver could not list its installed components", + module: "daemon.components", + }), + ); + }); + it("scopes child loggers under daemon. so records are attributable", async () => { const { sink } = await start(); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 96992efbb..298bc6488 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -234,6 +234,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise; + readonly components: Pick; readonly doctor?: Doctor; /** What `events.replay` answers from; see `EventHistory`. */ readonly eventHistory: Pick; @@ -1134,6 +1134,12 @@ export class DaemonServer { return this.#dispatcher.dispatch("worker.remove", frame.payload, this.#session(connection)); case "component.install": return this.#installComponent(connection, frame.id, frame.payload); + case "component.list": + return this.#dispatcher.dispatch( + "component.list", + frame.payload ?? {}, + this.#session(connection), + ); // "daemon.stop" is deliberately absent from this switch: `#dispatchLine` intercepts it // itself, ahead of the protocol-mismatch and `#stopping` gates (ADR §6's frozen exception, // scoped to protocol version only -- still gated on a completed handshake and the `admin` diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 7da2fedb6..a78799364 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -2545,6 +2545,182 @@ describe("AndroidDriver pre-root devices", () => { }); }); +describe("AndroidDriver listComponents()", () => { + const userAvdHome = `${home}/.android/avd`; + const googleApis = `${sdk}/system-images/android-35/google_apis/arm64-v8a`; + const plain = `${sdk}/system-images/android-35/default/arm64-v8a`; + + /** An AVD the user made with avdmanager: `.ini` pointing at `.avd`. */ + async function userAvd( + filesystem: MemoryFilesystem, + name: string, + sysdir: string, + options: { readonly avdHome?: string; readonly avdPath?: string } = {}, + ): Promise { + const avdHome = options.avdHome ?? userAvdHome; + const avdPath = options.avdPath ?? `${avdHome}/${name}.avd`; + await filesystem.mkdirp(avdPath); + await filesystem.writeFileAtomic( + `${avdHome}/${name}.ini`, + `avd.ini.encoding=UTF-8\npath=${avdPath}\n`, + ); + await filesystem.writeFileAtomic( + `${avdPath}/config.ini`, + `hw.ramSize=2048\nimage.sysdir.1=${sysdir}\ntag.id=google_apis\n`, + ); + } + + it("lists two images of one API level as two entries with different variants, each with its directory's size", async () => { + const filesystem = await androidFilesystem({ + images: [ + ["35", "google_apis", "arm64-v8a"], + ["35", "default", "arm64-v8a"], + ], + }); + await filesystem.writeFileAtomic(`${googleApis}/source.properties`, "Pkg.Revision=7\n"); + await filesystem.mkdirp(`${googleApis}/data`); + await filesystem.writeFileAtomic(`${googleApis}/data/userdata.img`, "0123456789"); + await filesystem.writeFileAtomic(`${plain}/system.img`, "abc"); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + const listed = await driver.listComponents(); + + expect(listed).toEqual([ + { + foreignDevices: 0, + receipt: { + package: "system-images;android-35;default;arm64-v8a", + revision: "unknown", + stamp: "", + }, + sizeBytes: 3, + variant: "default/arm64-v8a", + version: "35", + }, + { + foreignDevices: 0, + receipt: { + package: "system-images;android-35;google_apis;arm64-v8a", + revision: "7", + stamp: expect.stringMatching(/^.+@\d+$/), + }, + sizeBytes: "Pkg.Revision=7\n".length + 10, + variant: "google_apis/arm64-v8a", + version: "35", + }, + ]); + }); + + it("counts an AVD in the user's AVD home that names the image as foreign, wherever its directory is, and not an AVD in Simlock's root", async () => { + const filesystem = await androidFilesystem({ + images: [ + ["35", "google_apis", "arm64-v8a"], + ["35", "default", "arm64-v8a"], + ], + }); + await userAvd(filesystem, "Pixel_8", "system-images/android-35/google_apis/arm64-v8a/"); + // avdmanager's `-p`: the AVD directory lives elsewhere, and the `.ini` points at it. + await userAvd(filesystem, "Elsewhere", `${googleApis}/`, { avdPath: "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/work/Elsewhere.avd" }); + await userAvd(filesystem, "Other", "system-images/android-34/google_apis/arm64-v8a/"); + // Simlock's own AVD of the same image: one of its devices, counted from the registry. + await userAvd(filesystem, "simlock_one", "system-images/android-35/google_apis/arm64-v8a/", { + avdHome: avdDirectory, + }); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + const listed = await driver.listComponents(); + + expect(listed.map(({ foreignDevices, variant }) => ({ foreignDevices, variant }))).toEqual([ + { foreignDevices: 0, variant: "default/arm64-v8a" }, + { foreignDevices: 2, variant: "google_apis/arm64-v8a" }, + ]); + }); + + it("finds an AVD beside a pointer file with an empty path, counts nothing for an AVD whose directory is gone, and still lists the image", async () => { + const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); + const sysdir = "system-images/android-35/google_apis/arm64-v8a/"; + await userAvd(filesystem, "Beside", sysdir); + await filesystem.writeFileAtomic( + `${userAvdHome}/Beside.ini`, + "avd.ini.encoding=UTF-8\npath=\n", + ); + await filesystem.writeFileAtomic(`${userAvdHome}/Gone.ini`, "path=/nowhere/Gone.avd\n"); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + const listed = await driver.listComponents(); + + expect(listed.map(({ foreignDevices, version }) => ({ foreignDevices, version }))).toEqual([ + { foreignDevices: 1, version: "35" }, + ]); + }); + + it("counts no foreign AVD when the user's AVD home is Simlock's own root, as in a daemon started from a lease's environment", async () => { + const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); + await userAvd(filesystem, "simlock_one", "system-images/android-35/google_apis/arm64-v8a/", { + avdHome: avdDirectory, + }); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([]), { + avdHome: avdDirectory, + }); + + const listed = await driver.listComponents(); + + expect(listed.map(({ foreignDevices }) => foreignDevices)).toEqual([0]); + }); + + it.each([ + ["the user's AVD home", () => userAvdHome], + ["an AVD's pointer file", () => `${userAvdHome}/Locked.ini`], + ["an AVD's config.ini", () => `${userAvdHome}/Locked.avd/config.ini`], + ])( + "rejects when %s cannot be read, rather than count the AVDs there as using nothing", + async (_label, unreadable) => { + const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); + await userAvd(filesystem, "Locked", "system-images/android-35/google_apis/arm64-v8a/"); + filesystem.defineFailure(unreadable(), "EACCES"); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + await expect(driver.listComponents()).rejects.toMatchObject({ code: "EACCES" }); + }, + ); + + it("leaves sizeBytes out when the image directory cannot be read, and still lists the image", async () => { + const filesystem = await androidFilesystem({ images: [["35", "google_apis", "arm64-v8a"]] }); + await filesystem.writeFileAtomic(`${googleApis}/system.img`, "abc"); + filesystem.defineFailure(`${googleApis}/system.img`, "EACCES"); + const driver = await createDriver(filesystem, new ScriptedProcessRunner([])); + + const listed = await driver.listComponents(); + + expect(listed).toHaveLength(1); + expect(listed[0]).toMatchObject({ variant: "google_apis/arm64-v8a", version: "35" }); + expect(listed[0]).not.toHaveProperty("sizeBytes"); + }); + + it("lists an image with the receipt installComponent returned for it, and starts no process to list", async () => { + const filesystem = await androidFilesystem(); + const runner = new InstallReflectingProcessRunner( + [ + processResult(binaries.sdkmanager, [ + "--install", + "system-images;android-35;google_apis;arm64-v8a", + ]), + ], + filesystem, + ); + const driver = await createDriver(filesystem, runner); + const installed = await installFor(driver, "35"); + const callsBeforeListing = runner.calls.length; + + const listed = await driver.listComponents(); + + expect(listed.find((component) => component.version === "35")?.receipt).toEqual( + installed.receipt, + ); + expect(runner.calls).toHaveLength(callsBeforeListing); + }); +}); + function bootProbes(runner: ScriptedProcessRunner): number { return runner.calls.filter((call) => call.args.includes("sys.boot_completed")).length; } @@ -2758,6 +2934,8 @@ async function createDriver( processRunner: ScriptedProcessRunner, options: { readonly acceptAndroidLicenses?: boolean; + /** `ANDROID_AVD_HOME` in the environment the daemon started with; unset by default. */ + readonly avdHome?: string; readonly clock?: FakeClock; readonly driverConfig?: Readonly>; readonly emulator?: AndroidEmulatorLaunchOptions; @@ -2778,7 +2956,10 @@ async function createDriver( ...onlyProvided(options), clock: options.clock ?? new FakeClock(), driverConfig, - env: { ANDROID_HOME: sdk }, + env: { + ANDROID_HOME: sdk, + ...(options.avdHome === undefined ? {} : { ANDROID_AVD_HOME: options.avdHome }), + }, filesystem, homeDirectory: home, hostAbi: "arm64-v8a", diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index ee65e09f5..5fd45d7ff 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -10,6 +10,7 @@ import { type Driver, type DriverCatalogEntry, type DriverCatalogImage, + type DriverComponent, type DriverDevice, DriverCrashError, type DriverEstimate, @@ -473,9 +474,10 @@ export class AndroidDriver implements Driver { // System images land under the SDK root, so that is the volume an install is reserved on. this.componentFootprint = { bytes: ANDROID_SYSTEM_IMAGE_MIN_FREE_BYTES, path: sdk.root }; // Where an AVD Simlock made before it owned a root still sits: the AVD home the user - // had configured then, or the SDK's own default. Read only by `findLegacy` / + // had configured then, or the SDK's own default. Used only by `findLegacy` / // `destroyLegacy` -- the fallback CP3 deleted from the driver proper, kept exactly here - // because a stranded device cannot be found anywhere else (ADR 0001, Migration). + // because a stranded device cannot be found anywhere else (ADR 0001, Migration) -- and + // read by `listComponents`, which counts the user's own AVDs there (ADR 0010 §8). this.#legacyAvdHome = options.env.ANDROID_AVD_HOME ?? join(options.homeDirectory, ".android", "avd"); this.#portAllocator = portAllocatorFor(options.processRunner, sdk.adb); @@ -1207,6 +1209,75 @@ export class AndroidDriver implements Driver { return { ...installed, outcome: wasThere ? "already-installed" : "installed" }; } + /** + * One entry per installed system image: its API level, its tag and ABI as the variant, the + * receipt `findComponent` and `installComponent` build for it, and the size of its directory, + * left out when that cannot be read. `foreignDevices` counts the AVDs in the user's own AVD + * home whose `config.ini` names the image's directory; that home is only read. + */ + async listComponents(): Promise { + const [images, foreignAvds] = await Promise.all([ + this.#installedImages(), + this.#foreignAvdImageDirectories(), + ]); + return Promise.all( + images.map(async (image): Promise => { + const sizeBytes = await this.#filesystem.directorySize(image.path).catch(() => undefined); + const directories = [image.path, relativeImageDirectory(image)]; + return { + ...(await this.#installedComponent(image)), + foreignDevices: foreignAvds.filter((named) => + named.some((directory) => directories.includes(directory)), + ).length, + variant: `${image.tag}/${image.abi}`, + ...(sizeBytes === undefined ? {} : { sizeBytes }), + }; + }), + ); + } + + /** + * For every AVD in the user's own AVD home, the image directories its `config.ini` names + * (`image.sysdir.N`), without trailing slashes. Read-only (safety rule 1). A home or a + * `config.ini` that does not exist names no image. Any other read failure rejects: a count that + * silently left an AVD out would read as "nothing of the user's uses this image". A home that is + * this driver's own root -- the daemon started from a lease's environment -- holds Simlock's + * AVDs, which the registry counts, and none of the user's. + */ + async #foreignAvdImageDirectories(): Promise { + const home = this.#legacyAvdHome; + if (home === this.#deviceRoot) return []; + let entries: string[]; + try { + entries = await this.#filesystem.readdir(home); + } catch (error: unknown) { + if (isMissingPathError(error)) return []; + throw error; + } + const avds = entries + .filter((entry) => entry.endsWith(".ini")) + .map(async (entry) => { + const pointer = await this.#filesystem.readFile(join(home, entry)); + // `path=` names the AVD's directory; avdmanager puts it beside the pointer by default. + const avdPath = + iniValues(pointer, /^path$/)[0] ?? join(home, `${entry.slice(0, -".ini".length)}.avd`); + const config = await this.#readIfPresent(join(avdPath, "config.ini")); + if (config === undefined) return []; + return iniValues(config, /^image\.sysdir\.\d+$/).map((value) => value.replace(/\/+$/, "")); + }); + return Promise.all(avds); + } + + /** A file's contents, or `undefined` when it does not exist; any other failure rejects. */ + async #readIfPresent(path: string): Promise { + try { + return await this.#filesystem.readFile(path); + } catch (error: unknown) { + if (isMissingPathError(error)) return undefined; + throw error; + } + } + async #installedComponent(image: SystemImage): Promise { return { receipt: await this.#imageReceipt(image), version: image.apiLevel }; } @@ -2017,6 +2088,21 @@ async function packageRevision( } } +/** The values of every `key=value` line in an ini file whose key matches, trimmed. */ +function iniValues(contents: string, key: RegExp): string[] { + return contents.split(/\r?\n/).flatMap((line) => { + const separator = line.indexOf("="); + if (separator === -1 || !key.test(line.slice(0, separator).trim())) return []; + const value = line.slice(separator + 1).trim(); + return value === "" ? [] : [value]; + }); +} + +/** An image's directory relative to the SDK root, as an AVD's `image.sysdir.N` names it. */ +function relativeImageDirectory(image: SystemImage): string { + return `system-images/android-${image.apiLevel}/${image.tag}/${image.abi}`; +} + function serialFor(port: number): string { return `emulator-${port}`; } diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index f1b1a094f..66db80d3a 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -139,8 +139,9 @@ const legacyUdid = "00000000-0000-0000-0000-0000000000ff"; /** * The complete argv of every call the pre-root path is allowed to make without `--set`, * spelled out rather than pattern-matched: `findLegacy` / `destroyLegacy` deliberately - * address the machine's default set (ADR 0001, Migration), and every *other* call must - * still fail the invariant below if its scoping ever goes missing. + * address the machine's default set (ADR 0001, Migration), and `listComponents` reads it with + * the same `list` to count foreign devices (ADR 0010 §8). Every *other* call must still fail + * the invariant below if its scoping ever goes missing. */ const UNSCOPED_LEGACY_CALLS = new Set( [ @@ -3118,6 +3119,264 @@ describe("IosSimctlDriver", () => { }); }); +describe("IosSimctlDriver listComponents()", () => { + const runtimeListInvocation = simctl("runtime", "list", "-j"); + /** The unscoped read of the machine's default device set: no `--set`. */ + const defaultSetInvocation = { args: ["simctl", "list", "-j", "devices"], command: "xcrun" }; + + interface Image { + readonly id: string; + readonly runtime: string; + readonly build: string; + readonly version: string; + readonly sizeBytes?: number; + readonly platform?: string; + } + + function image(version: string, build: string, extra: Partial = {}): Image { + return { + build, + id: `IMG-${version}-${build}`, + runtime: `com.apple.CoreSimulator.SimRuntime.iOS-${version.replace(".", "-")}`, + version, + ...extra, + }; + } + + function imagesListed(images: readonly Image[]) { + const stdout = JSON.stringify( + Object.fromEntries( + images.map((entry) => [ + entry.id, + { + build: entry.build, + identifier: entry.id, + platformIdentifier: entry.platform ?? "com.apple.platform.iphonesimulator", + runtimeIdentifier: entry.runtime, + sizeBytes: entry.sizeBytes ?? 1_000, + state: "Ready", + version: entry.version, + }, + ]), + ), + ); + return { match: runtimeListInvocation, result: { code: 0, stderr: "", stdout } }; + } + + function defaultSetListed(devices: Readonly>) { + const stdout = JSON.stringify({ + devices: Object.fromEntries( + Object.entries(devices).map(([runtime, count]) => [ + runtime, + Array.from({ length: count }, (_, index) => ({ + name: `user-${String(index)}`, + state: "Shutdown", + udid: `USER-${runtime}-${String(index)}`, + })), + ]), + ), + }); + return { match: defaultSetInvocation, result: { code: 0, stderr: "", stdout } }; + } + + it("lists one entry per iOS runtime image with its version, size and build, and no entry for another platform's runtime", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([ + image("18.4", "22E238", { sizeBytes: 8_963_458_461 }), + image("26.0", "23A343", { sizeBytes: 9_100_000_000 }), + image("11.4", "22T250", { + platform: "com.apple.platform.watchsimulator", + runtime: "com.apple.CoreSimulator.SimRuntime.watchOS-11-4", + }), + ]), + defaultSetListed({}), + ]); + const driver = await createDriver(runner); + + await expect(driver.listComponents()).resolves.toEqual([ + { + foreignDevices: 0, + receipt: { build: "22E238", image: "IMG-18.4-22E238" }, + sizeBytes: 8_963_458_461, + variant: "22E238", + version: "18.4", + }, + { + foreignDevices: 0, + receipt: { build: "23A343", image: "IMG-26.0-23A343" }, + sizeBytes: 9_100_000_000, + variant: "23A343", + version: "26.0", + }, + ]); + }); + + it("counts a device in the default device set that uses an image's runtime as foreign, and reads no device in Simlock's own set for it", async () => { + const used = image("18.4", "22E238"); + const unused = image("26.0", "23A343"); + // The scripted runner refuses any call it was not given, so a `simctl --set list` + // would fail this test: only the default set is read. + const runner = new ScriptedProcessRunner([ + imagesListed([used, unused]), + defaultSetListed({ [used.runtime]: 2, "com.apple.CoreSimulator.SimRuntime.iOS-17-5": 1 }), + ]); + const driver = await createDriver(runner); + + const listed = await driver.listComponents(); + + expect(listed.map(({ foreignDevices, version }) => ({ foreignDevices, version }))).toEqual([ + { foreignDevices: 2, version: "18.4" }, + { foreignDevices: 0, version: "26.0" }, + ]); + expect(runner.calls.map((call) => call.args)).toEqual([ + runtimeListInvocation.args, + defaultSetInvocation.args, + ]); + }); + + it("lists a runtime with the receipt installComponent returned for it, and runs no installer to list", async () => { + const before = [ + { build: "22E238", id: "IMG-184", runtime: "com.apple.CoreSimulator.SimRuntime.iOS-18-4" }, + ]; + const after = [ + ...before, + { build: "22G86", id: "IMG-186", runtime: "com.apple.CoreSimulator.SimRuntime.iOS-18-6" }, + ]; + const asImages = (entries: typeof after): Image[] => + entries.map((entry) => ({ + ...entry, + version: entry.runtime.endsWith("18-6") ? "18.6" : "18.4", + })); + const listed = (stdout: string) => ({ + match: listInvocation, + result: { code: 0, stderr: "", stdout }, + }); + const runner = new ScriptedProcessRunner([ + listed(listFixture), + imagesListed(asImages(before)), + { + match: { + args: ["-downloadPlatform", "iOS", "-buildVersion", "18.6"], + command: "xcodebuild", + }, + }, + listed(listFixtureAfterDownload), + imagesListed(asImages(after)), + imagesListed(asImages(after)), + defaultSetListed({}), + ]); + const driver = await createDriver(runner); + const installed = await driver.installComponent("18.6", { + onProgress: () => undefined, + signal: new AbortController().signal, + }); + const callsBeforeListing = runner.calls.length; + + const components = await driver.listComponents(); + + expect(components.find((component) => component.version === "18.6")?.receipt).toEqual( + installed.receipt, + ); + expect(runner.calls.slice(callsBeforeListing).map((call) => call.command)).toEqual([ + "xcrun", + "xcrun", + ]); + }); + + it("leaves out an image with no version or no platform, leaves out a size that is not a byte count, and counts no device under a runtime that lists none", async () => { + const ios = "com.apple.platform.iphonesimulator"; + const runtimeList = { + "IMG-A": { + build: "22E238", + identifier: "IMG-A", + platformIdentifier: ios, + runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-18-4", + sizeBytes: -1, + version: "18.4", + }, + "IMG-B": { + build: "23A343", + identifier: "IMG-B", + platformIdentifier: ios, + runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-0", + sizeBytes: 1.5, + }, + "IMG-C": { + build: "23A344", + identifier: "IMG-C", + runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-1", + sizeBytes: 10, + version: "26.1", + }, + }; + const runner = new ScriptedProcessRunner([ + { + match: runtimeListInvocation, + result: { code: 0, stderr: "", stdout: JSON.stringify(runtimeList) }, + }, + { + match: defaultSetInvocation, + result: { + code: 0, + stderr: "", + stdout: JSON.stringify({ + devices: { "com.apple.CoreSimulator.SimRuntime.iOS-18-4": "not a list" }, + }), + }, + }, + ]); + const driver = await createDriver(runner); + + await expect(driver.listComponents()).resolves.toEqual([ + { + foreignDevices: 0, + receipt: { build: "22E238", image: "IMG-A" }, + variant: "22E238", + version: "18.4", + }, + ]); + }); + + it("rejects with DriverCrashError when the default device set answers with something that is not JSON", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([image("18.4", "22E238")]), + { match: defaultSetInvocation, result: { code: 0, stderr: "", stdout: "not json" } }, + ]); + const driver = await createDriver(runner); + + const error = await driver.listComponents().catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(DriverCrashError); + expect((error as Error).message).toContain("Could not parse simctl device list"); + }); + + it("rejects with DriverCrashError when the default device set answers JSON with no devices map", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([image("18.4", "22E238")]), + { match: defaultSetInvocation, result: { code: 0, stderr: "", stdout: "{}" } }, + ]); + const driver = await createDriver(runner); + + const error = await driver.listComponents().catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(DriverCrashError); + expect((error as Error).message).toBe("Invalid simctl device list JSON"); + }); + + it("rejects when the default device set cannot be read, rather than report no foreign devices", async () => { + const runner = new ScriptedProcessRunner([ + imagesListed([image("18.4", "22E238")]), + { + match: defaultSetInvocation, + result: { code: 1, stderr: "CoreSimulator is down", stdout: "" }, + }, + ]); + const driver = await createDriver(runner); + + await expect(driver.listComponents()).rejects.toBeInstanceOf(DriverCrashError); + }); +}); + describe("IosSimctlDriver toolVersions()", () => { it("reports the Xcode version and build that xcodebuild -version prints", async () => { const runner = new ScriptedProcessRunner([ diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index e9ecbce46..220ae7143 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -10,6 +10,7 @@ import { type DriverAdvisory, type DriverToolVersion, type DriverCatalogEntry, + type DriverComponent, type DriverDevice, DriverCrashError, type DriverEstimate, @@ -523,6 +524,40 @@ export class IosSimctlDriver implements Driver { return { ...installed, outcome: wasThere ? "already-installed" : "installed" }; } + /** + * One entry per iOS runtime image `simctl runtime list -j` reports: its version, its size, its + * build as the variant, and the receipt `findComponent` and `installComponent` build for the + * runtime it provides. `foreignDevices` counts the devices in the machine's default device set + * whose runtime is the image's; that read is an unscoped `simctl list`, which mutates nothing. + * An image that reports no version names no component and is left out. + */ + async listComponents(): Promise { + const [images, defaultSet] = await Promise.all([ + this.#loadRuntimeImages(), + this.#legacySimctl(["list", "-j", "devices"], COMMAND_TIMEOUT_MS), + ]); + let foreign: ReadonlyMap; + try { + foreign = devicesPerRuntime(JSON.parse(defaultSet.stdout) as unknown); + } catch (error: unknown) { + if (error instanceof DriverCrashError) throw error; + throw new DriverCrashError(`Could not parse simctl device list: ${errorMessage(error)}`); + } + return images.filter(isIosImage).flatMap((image): DriverComponent[] => + image.version === undefined + ? [] + : [ + { + foreignDevices: foreign.get(image.runtimeIdentifier) ?? 0, + receipt: imageReceipt(image), + version: image.version, + ...(image.build === undefined ? {} : { variant: image.build }), + ...(image.sizeBytes === undefined ? {} : { sizeBytes: image.sizeBytes }), + }, + ], + ); + } + /** The receipt of every runtime installed right now, before an installer run. */ async #installedReceipts(): Promise { const [catalog, images] = await Promise.all([this.#loadCatalog(), this.#loadRuntimeImages()]); @@ -1530,7 +1565,8 @@ export class IosSimctlDriver implements Driver { * `findLegacy` / `destroyLegacy` deal with are in the machine's default set, which is * where a `--set` would stop reaching them. Only those two may call it, and only for a * UDID a registry record names -- registry-only destruction (safety rule 1) is satisfied - * by that record, not by the root. + * by that record, not by the root. The one other caller is `listComponents`, and only for + * `simctl list`, which reads the default set and mutates nothing (ADR 0010 §8). */ async #invokeLegacySimctl(args: readonly string[], timeoutMs: number): Promise { return this.#invokeXcrun(["simctl", ...args], timeoutMs); @@ -1869,8 +1905,15 @@ interface RuntimeImage { /** The `SimRuntime` identifier the image provides, as `simctl list runtimes` names it. */ readonly runtimeIdentifier: string; readonly build?: string; + /** The platform the image is for: `com.apple.platform.iphonesimulator` for iOS. */ + readonly platformIdentifier?: string; + readonly version?: string; + readonly sizeBytes?: number; } +/** The `platformIdentifier` `simctl runtime list -j` gives an iOS simulator runtime image. */ +const IOS_SIMULATOR_PLATFORM = "com.apple.platform.iphonesimulator"; + /** `simctl runtime list -j` is an object keyed by image identifier; unreadable entries are skipped. */ function parseRuntimeImages(value: unknown): readonly RuntimeImage[] { if (!isRecord(value)) { @@ -1884,18 +1927,33 @@ function parseRuntimeImages(value: unknown): readonly RuntimeImage[] { { identifier: entry.identifier, runtimeIdentifier: entry.runtimeIdentifier, - ...(typeof entry.build === "string" ? { build: entry.build } : {}), + ...optionalString("build", entry.build), + ...optionalString("platformIdentifier", entry.platformIdentifier), + ...optionalString("version", entry.version), + ...(isByteCount(entry.sizeBytes) ? { sizeBytes: entry.sizeBytes } : {}), }, ] : [], ); } +/** `{ [key]: value }` when `value` is a string, and nothing otherwise. */ +function optionalString( + key: Key, + value: unknown, +): Partial> { + return typeof value === "string" ? ({ [key]: value } as Record) : {}; +} + +function isByteCount(value: unknown): value is number { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} + /** - * The one function that builds this driver's receipt (ADR 0010 §5): the runtime image the - * runtime is mounted from, and its build. A runtime with no image of its own -- one bundled - * inside Xcode rather than downloaded -- is named by its runtime identifier instead; Simlock - * never installs one of those, so no record of Simlock's can match it. + * The receipt of the installed component a runtime is (ADR 0010 §5): the receipt of the image it + * is mounted from. A runtime with no image of its own -- one bundled inside Xcode rather than + * downloaded -- is named by its runtime identifier instead; Simlock never installs one of those, + * so no record of Simlock's can match it. */ function runtimeReceipt(runtime: Runtime, images: readonly RuntimeImage[]): ComponentReceipt { const image = images.find( @@ -1903,10 +1961,41 @@ function runtimeReceipt(runtime: Runtime, images: readonly RuntimeImage[]): Comp candidate.runtimeIdentifier === runtime.identifier && (runtime.build === undefined || candidate.build === runtime.build), ); - const build = runtime.build ?? image?.build ?? ""; return image === undefined - ? { build, runtime: runtime.identifier } - : { build, image: image.identifier }; + ? { build: runtime.build ?? "", runtime: runtime.identifier } + : imageReceipt(image); +} + +/** + * The one function that builds an image's receipt, for an install, a find and a listing alike + * (ADR 0010 §5): the image identifier and its build. `runtimeReceipt` only picks the image. + */ +function imageReceipt(image: RuntimeImage): ComponentReceipt { + return { build: image.build ?? "", image: image.identifier }; +} + +/** + * Whether an image is an iOS simulator runtime, not a watchOS, tvOS or visionOS one. An image + * that does not say which platform it is for is not listed: nothing else proves it is iOS. + */ +function isIosImage(image: RuntimeImage): boolean { + return image.platformIdentifier === IOS_SIMULATOR_PLATFORM; +} + +/** + * How many devices a `simctl list -j devices` answer holds under each runtime: the answer is + * keyed by runtime identifier, with one array of devices under each. + */ +function devicesPerRuntime(value: unknown): ReadonlyMap { + if (!isRecord(value) || !isRecord(value.devices)) { + throw new DriverCrashError("Invalid simctl device list JSON"); + } + return new Map( + Object.entries(value.devices).map(([runtime, devices]) => [ + runtime, + Array.isArray(devices) ? devices.length : 0, + ]), + ); } function installedComponent(runtime: Runtime, images: readonly RuntimeImage[]): InstalledComponent { diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 94a345639..d87b1ff59 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -594,6 +594,18 @@ describe("GatewayDispatcher", () => { message: "component.install installs on one machine; run it against a worker", }); }); + + it("component.list answers UNSUPPORTED_IN_GATEWAY_MODE to an agent session, saying it lists one machine's components (ADR 0010 §8)", async () => { + const { dispatcher } = harness(); + + await expect( + dispatcher.dispatch("component.list", {}, session({ role: "agent" })), + ).rejects.toMatchObject({ + code: "UNSUPPORTED_IN_GATEWAY_MODE", + details: { operation: "component.list" }, + message: "component.list lists one machine's components; run it against a worker", + }); + }); }); describe("lease lifecycle and device.exec (#118)", () => { diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 628df35e9..7e0350887 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -169,6 +169,10 @@ export class GatewayDispatcher { "component.install", "component.install installs on one machine; run it against a worker", ), + "component.list": unsupportedByDesign( + "component.list", + "component.list lists one machine's components; run it against a worker", + ), "lease.request": this.#leaseRequest, "lease.renew": this.#leaseRenew, diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 26d592aa5..02729b3e2 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -263,6 +263,60 @@ describe("GET /v1/status, /v1/catalog", () => { }); }); +describe("GET /v1/components", () => { + const listing = { + components: [ + { + devices: 1, + foreignDevices: 0, + installedAt: 1_790_864_071_200, + installedBySimlock: true, + platform: "android", + sizeBytes: 4_200_000_000, + variant: "google_apis/arm64-v8a", + version: "35", + }, + ], + }; + + it("answers an agent token with component.list, passing the platform query through", async () => { + const { app, dispatcher } = buildHarness(); + dispatcher.handlers["component.list"] = (input) => { + expect(input).toEqual({ platform: "android" }); + return listing; + }; + + const response = await app.request("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/v1/components?platform=android", { headers: agentAuth }); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual(listing); + }); + + it("lists every platform when no platform is asked for", async () => { + const { app, dispatcher } = buildHarness(); + dispatcher.handlers["component.list"] = (input) => { + expect(input).toEqual({}); + return listing; + }; + + const response = await app.request("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/v1/components", { headers: agentAuth }); + + expect(response.status).toBe(200); + }); + + it("400s an invalid platform query, before ever dispatching", async () => { + const { app, dispatcher } = buildHarness(); + dispatcher.handlers["component.list"] = () => { + throw new Error("should not be called"); + }; + + const response = await app.request("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/v1/components?platform=windows", { headers: agentAuth }); + + expect(response.status).toBe(400); + expect(((await response.json()) as { error: { code: string } }).error.code).toBe("BAD_REQUEST"); + }); +}); + describe("POST /v1/lease-requests", () => { it("creates a request resource, 201 with a Location header", async () => { const { app, dispatcher } = buildHarness(); diff --git a/src/http/app.ts b/src/http/app.ts index 3feb9357f..1a178942f 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -219,6 +219,19 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa return c.json(result); }); + app.get("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/v1/components", agentAuth, async (c) => { + const platform = c.req.query("platform"); + if (platform !== undefined && platform !== "ios" && platform !== "android") { + throw badRequest("platform must be ios or android"); + } + const result = await deps.dispatch( + "component.list", + platform === undefined ? {} : { platform }, + buildHttpSession(c.get("identity")), + ); + return c.json(result); + }); + app.post("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/v1/lease-requests", agentAuth, jsonBody(leaseRequestBodySchema), async (c) => { const identity = c.get("identity"); const body = c.req.valid("json"); diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index e052922b7..5cc332c28 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -8,6 +8,8 @@ import { type AnySimlockError, type CatalogGetInput, type CatalogGetOutput, + type ComponentListInput, + type ComponentListOutput, type DeviceRecoveredPush, type DeviceUnhealthyPush, type DoctorReport, @@ -58,6 +60,8 @@ export class FakeSimlockClient implements SimlockClient { getCatalogImpl: (input: CatalogGetInput) => Promise = notStubbed("getCatalog"); getStatusImpl: () => Promise = notStubbed("getStatus"); + listComponentsImpl: (input: ComponentListInput) => Promise = + notStubbed("listComponents"); requestLeaseImpl: ( input: LeaseRequestInput, options: RequestLeaseOptions, @@ -94,6 +98,12 @@ export class FakeSimlockClient implements SimlockClient { return this.#dead ? this.#deadConnection() : this.getStatusImpl(); } + // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP exposes no component tool of its own. + listComponents(input: ComponentListInput = {}): Promise { + this.calls.push({ input, method: "listComponents" }); + return this.#dead ? this.#deadConnection() : this.listComponentsImpl(input); + } + requestLease(input: LeaseRequestInput, options: RequestLeaseOptions = {}): Promise { this.calls.push({ input, method: "requestLease" }); return this.#dead ? this.#deadConnection() : this.requestLeaseImpl(input, options); diff --git a/src/ports/filesystem.test.ts b/src/ports/filesystem.test.ts index a082d2b25..2f9732681 100644 --- a/src/ports/filesystem.test.ts +++ b/src/ports/filesystem.test.ts @@ -158,6 +158,27 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) code: "ENOTDIR", }); }); + + it("sizes a directory as the bytes of the files under it, subdirectories included, without following a symlink", async () => { + const filesystem = create(); + const root = `${temporaryDirectory}/image`; + await filesystem.mkdirp(`${root}/data`); + await filesystem.mkdirp(`${temporaryDirectory}/outside`); + await filesystem.writeFileAtomic(`${root}/system.img`, "abcd"); + await filesystem.writeFileAtomic(`${root}/data/userdata.img`, "0123456789"); + await filesystem.writeFileAtomic(`${temporaryDirectory}/outside/big.img`, "x".repeat(100)); + await link(filesystem, `${root}/linked`, `${temporaryDirectory}/outside`); + + await expect(filesystem.directorySize(root)).resolves.toBe(14); + }); + + it("refuses to size a directory that is not there", async () => { + const filesystem = create(); + + await expect(filesystem.directorySize(`${temporaryDirectory}/missing`)).rejects.toMatchObject({ + code: "ENOENT", + }); + }); }); describe.each(implementations)("Filesystem ownership contract: $name", ({ create }) => { @@ -252,6 +273,15 @@ describe("MemoryFilesystem", () => { }); }); + it("refuses to size a directory when a path under it was declared broken", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("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/image/data"); + await filesystem.writeFileAtomic("/image/data/userdata.img", "0123456789"); + filesystem.defineFailure("/image/data/userdata.img", "EACCES"); + + await expect(filesystem.directorySize("/image")).rejects.toMatchObject({ code: "EACCES" }); + }); + it("fails at a path a test declared broken, with the errno it declared", async () => { // The only way to reach the branches that turn a filesystem failure into a typed // rejection: an EACCES on a device root cannot be produced by writing to the double. diff --git a/src/ports/filesystem.ts b/src/ports/filesystem.ts index 6ad65767c..1dae4c487 100644 --- a/src/ports/filesystem.ts +++ b/src/ports/filesystem.ts @@ -82,6 +82,12 @@ export interface Filesystem { readdir(path: string): Promise; exists(path: string): Promise; diskFree(path: string): Promise; + /** + * The bytes the files under a directory hold, its subdirectories included. Symlinks are not + * followed, so nothing outside the directory is counted. Rejects when the directory, or + * anything under it, cannot be read. + */ + directorySize(path: string): Promise; } export class NodeFilesystem implements Filesystem { @@ -200,6 +206,16 @@ export class NodeFilesystem implements Filesystem { const details = await statfs(path); return details.bavail * details.bsize; } + + async directorySize(path: string): Promise { + let total = 0; + for (const entry of await readdir(path, { withFileTypes: true })) { + const child = join(path, entry.name); + if (entry.isDirectory()) total += await this.directorySize(child); + else if (entry.isFile()) total += (await lstat(child)).size; + } + return total; + } } /** Attributes every in-memory entry carries, so callers can read them without a `kind` check. */ @@ -453,6 +469,18 @@ export class MemoryFilesystem implements Filesystem { return this.freeDiskBytes; } + async directorySize(path: string): Promise { + let total = 0; + for (const name of await this.readdir(path)) { + const child = joinMemoryPath(path, name); + this.#failIfDefined(child); + const entry = this.#rawEntryAt(child); + if (entry.kind === "directory") total += await this.directorySize(child); + else if (entry.kind === "file") total += Buffer.byteLength(entry.contents); + } + return total; + } + /** * Test-only: makes every operation on `path` fail with `code`, which is the only way to * reach the branches that turn an unexpected filesystem failure into a typed rejection. diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index 28a8b47e4..a2f53180b 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -166,6 +166,35 @@ describe("connectSimlock: handshake", () => { expect(connection.sent).toHaveLength(before); }); + it("lists components from an agent client with component.list, sending the platform and returning the daemon's answer", async () => { + const connection = new ScriptedConnection(); + const connectPromise = connectSimlock({ connection }); + await flushMicrotasks(); + completeHello(connection); + const client = await connectPromise; + const answer = { + components: [ + { + devices: 0, + foreignDevices: 2, + installedBySimlock: false, + platform: "ios", + sizeBytes: 9_100_000_000, + variant: "23A343", + version: "26.0", + }, + ], + }; + + const callPromise = client.listComponents({ platform: "ios" }); + await flushMicrotasks(); + const call = connection.lastSentOf("component.list")!; + expect(call.payload).toEqual({ platform: "ios" }); + connection.reply(call.id, answer); + + await expect(callPromise).resolves.toEqual(answer); + }); + it("wraps a malformed daemon response instead of throwing a raw parse failure", async () => { const connection = new ScriptedConnection(); const connectPromise = connectSimlock({ connection }); diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index fec78b5ff..0320d2f68 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -33,6 +33,8 @@ import type { CleanupRunOutput, ComponentInstallInput, ComponentInstallOutput, + ComponentListInput, + ComponentListOutput, DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, @@ -85,6 +87,8 @@ export type { ComponentInstallInput, ComponentInstallOutput, ComponentInstallProgress, + ComponentListInput, + ComponentListOutput, DaemonStopOutput, DeviceRecoveredPush, DeviceUnhealthyPush, @@ -167,6 +171,11 @@ export interface SimlockClient { getCatalog(input?: CatalogGetInput): Promise; getStatus(): Promise; + /** + * ADR 0010 §8: every installed iOS simulator runtime and Android system image on the daemon's + * machine, with its size, whether Simlock installed it, and how many devices use it. + */ + listComponents(input?: ComponentListInput): Promise; requestLease(input: LeaseRequestInput, options?: RequestLeaseOptions): Promise; cancelLease(input?: LeaseCancelInput): Promise; renewLease(input: LeaseRenewInput): Promise; @@ -313,6 +322,7 @@ function buildDegradedClient( getCatalog: () => rejected(), getStatus: () => rejected(), + listComponents: () => rejected(), requestLease: () => rejected(), cancelLease: () => rejected(), renewLease: () => rejected(), @@ -422,6 +432,10 @@ class SimlockClientImpl { return this.#call("status.get", {}); } + listComponents(input: ComponentListInput = {}): Promise { + return this.#call("component.list", input); + } + async requestLease( input: LeaseRequestInput, options: RequestLeaseOptions = {}, diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index 666557e66..123e87536 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -82,6 +82,8 @@ export type WorkerRemoveOutput = OpOutput<"worker.remove">; export type ComponentInstallInput = OpInput<"component.install">; export type ComponentInstallOutput = OpOutput<"component.install">; +export type ComponentListInput = OpInput<"component.list">; +export type ComponentListOutput = OpOutput<"component.list">; // ---- pushes ---------------------------------------------------------------------------------