diff --git a/docs/CLI.md b/docs/CLI.md index f4283ddb6..f8bb823d5 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -913,7 +913,8 @@ why its Android catalog looks thin, trimmed to one worker: "defaultRuntime": "26.0", "modelRuntimes": {"iPhone 16": ["18.4"]}, "modelAliases": {}, - "modelClasses": {"iPhone 16": "phone"} + "modelClasses": {"iPhone 16": "phone"}, + "classDefaults": {"phone": "iPhone 16"} }, { "platform": "android", @@ -923,6 +924,7 @@ why its Android catalog looks thin, trimmed to one worker: "modelRuntimes": {}, "modelAliases": {}, "modelClasses": {}, + "classDefaults": {}, "images": [{"runtime": "18.0", "tag": "google_apis", "abi": "arm64-v8a"}] } ], @@ -1254,6 +1256,16 @@ is `desktop`, and a profile with no tag, or a custom profile from `devices.xml`, is `phone`. A model whose tooling reports nothing usable has no entry, and is still listed and leasable by name. +`classDefaults` says, for a class, which model Simlock would create for it on +this machine: the first name on the class's preference list that the catalog +lists, that is a model of the class, and that pairs with an installed runtime +(or the first of those that are listed and of the class, when none pairs). +The list is the names in `ios.defaultModels.` or +`android.defaultModels.`, then Simlock's own list for the platform; +see [`docs/CONFIGURATION.md`](CONFIGURATION.md#default-models-per-class). A class +in which no listed name counts has no entry. The human-oriented output shows +it beside the class, as `none` when there is none. + `customModels` lists the models that exist because of something on that machine rather than the platform's tools. The field is absent when there are none, and iOS never has it. See [Where Android models come @@ -1269,14 +1281,14 @@ downloads a runtime or system image, and lists only what is installed, whatever `downloads.policy` says. Human-oriented by default, models grouped under a line for their class (in -the order above, then `(no class)`), one line per model with the runtimes it +the order above, then `(no class)`) that shows the class's default model, one line per model with the runtimes it pairs with, its other names on the line below it, and then each image: ```text Platform: android Runtimes: 34, 35 (default: 35) Models: - phone: + phone (default: Pixel 8): My Tablet (custom): 34, 35 Pixel 8: 34, 35 Other names: pixel_8 @@ -1292,6 +1304,7 @@ Platform: android "modelRuntimes":{"My Tablet":["34","35"],"Pixel 8":["34","35"]}, "modelAliases":{"Pixel 8":["pixel_8"]}, "modelClasses":{"My Tablet":"phone","Pixel 8":"phone"}, + "classDefaults":{"phone":"Pixel 8"}, "customModels":["My Tablet"], "images":[{"runtime":"34","tag":"default","abi":"x86_64"},{"runtime":"35","tag":"google_apis","abi":"arm64-v8a"}]}]} ``` @@ -1299,7 +1312,9 @@ Platform: android Against a gateway, `modelAliases` is the union of each worker's other names for a model, `modelClasses` the union of their classes (when two workers class a model differently, the worker with the smallest id wins), and `images` -the union of their images. A model is in +the union of their images. A class's entry in `classDefaults` is kept only +when every connected worker reports the same model for it; a worker with none +for that class counts as disagreeing. A model is in `customModels` when any worker that lists it marks it custom; `simlock worker list --json` shows which worker that is. A gateway accepts any name a worker lists for a model, in any letter case, and sends that worker its diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 04f5619ad..383fdff38 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -243,7 +243,8 @@ const { platforms } = await client.getCatalog({ platform: "ios" }); // defaultRuntime: "26.0", // modelRuntimes: { "iPhone 16": ["18.4", "26.0"], "iPhone XS": ["18.4"] }, // modelAliases: {}, -// modelClasses: { "iPhone 16": "phone", "iPhone XS": "phone" } }] +// modelClasses: { "iPhone 16": "phone", "iPhone XS": "phone" }, +// classDefaults: { phone: "iPhone 16" } }] ``` - `models` and `runtimes` are what is installed. A model and a runtime that @@ -259,6 +260,11 @@ const { platforms } = await client.getCatalog({ platform: "ios" }); - `modelClasses` maps a model to its class, one of `"phone"`, `"tablet"`, `"watch"`, `"tv"`, `"vision"`, `"auto"` or `"desktop"`, when its tooling reports one. A model with no entry is still listed and leasable by name. +- `classDefaults` maps a class to the model Simlock would create for it on + this machine: the first name on the class's preference list that is listed, + is of the class and pairs with an installed runtime. The list is the names + in `ios.defaultModels.` or `android.defaultModels.`, then + Simlock's own. A class in which no listed name counts has no entry. - `images` is on Android entries only: every installed system image as `{ runtime, tag, abi }`, where `runtime` is a value from `runtimes`. An image whose ABI the host cannot run natively is listed too. @@ -280,7 +286,8 @@ model is paired with a runtime when at least one worker pairs them, and runtime. The gateway sends a request only to a worker that pairs the model with the runtime. `modelAliases` and `images` are the unions of each worker's own, and so is `modelClasses`: when two workers class a model -differently, the worker with the smallest id wins. A model is in `customModels` when any worker that lists it +differently, the worker with the smallest id wins. A class has a `classDefaults` +entry only when every connected worker reports the same model for it. A model is in `customModels` when any worker that lists it marks it custom; each worker's own list is in its catalog on `listWorkers()` from the admin client. A model may be asked for by any name a worker lists for it, in any letter case, and the gateway sends that worker its own name for it. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 40ea1b619..6c4bc5c76 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -66,6 +66,8 @@ edit yourself keeps the mode you give it until the next `config set`; run | `ios.defaultMode` | The device mode an iOS lease request gets when it names none: `slim` or `full`. Every worker makes both kinds whatever this says. See [Device mode: slim and full](#device-mode-slim-and-full). | `full` | | `ios.slim.categories` | Which daemon categories a slim iOS device has disabled. Omitted means every category the driver knows. | every known category | | `ios.slim.bootTimeoutMs` | Boot deadline for a slim iOS device, in place of the normal boot timeout. | `10 minutes` | +| `ios.defaultModels.` | The iOS models to prefer for a device class (`phone`, `tablet`, `watch`, `tv`, `vision`, `auto` or `desktop`): one model name or a list of them, most preferred first. Tried before Simlock's own list. See [Default models per class](#default-models-per-class). | unset (Simlock's own list only) | +| `android.defaultModels.` | The same for Android models. | unset (Simlock's own list only) | | `android.emulator.headless` | Launch emulators without a window (`-no-window`). Needed on a host with no display, such as a Linux CI runner. See [Android emulator launch options](#android-emulator-launch-options). | `false` | | `android.emulator.gpu` | The emulator's GPU mode, passed as `-gpu ` (for example `host`, `swiftshader_indirect`, `guest`). `auto` passes nothing and leaves the emulator's own choice. | `auto` | | `android.emulator.audio` | `false` launches emulators without audio (`-no-audio`). | `true` | @@ -457,6 +459,48 @@ request. Empty it before upgrading: simlock nuke --delete-devices ``` +## Default models per class + +For each device class (`phone`, `tablet`, `watch`, `tv`, `vision`, `auto`, +`desktop`) Simlock keeps a preference list of model names, and the default +model for the class on this machine is the first name on it that qualifies. +`simlock catalog` shows the result beside each class, as `classDefaults` in +its JSON. A name qualifies when this machine's catalog lists it (by its name +or another name it answers to, in any letter case), when the catalog says it +is a model of that class, and when it pairs with at least one installed +runtime. When no listed name of the class pairs with a runtime, the first +listed one is shown anyway. A class in which no name qualifies has no default, +and the catalog shows `none`. + +The list is the names you set, then Simlock's own list for the platform: + +| Class | iOS, newest first | Android, newest first | +| --------- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | +| `phone` | iPhone 17, iPhone 16, iPhone 15, iPhone 14, iPhone 13 | Pixel 9, Pixel 8, Pixel 7, Pixel 6, Medium Phone | +| `tablet` | iPad Pro 11-inch (M5), iPad Pro 11-inch (M4), iPad Air 11-inch (M3), iPad (A16), iPad (10th generation) | none | +| `watch` | Apple Watch Series 11 (46mm), Apple Watch Series 10 (46mm), Apple Watch Series 9 (45mm) | Wear OS Large Round, Wear OS Small Round | +| `tv` | Apple TV 4K (3rd generation), Apple TV | Television (1080p), Television (4K) | +| `vision` | Apple Vision Pro | none | +| `auto` | none | Automotive (1080p landscape), Automotive (1024p landscape) | +| `desktop` | none | Medium Desktop, Large Desktop | + +Set `ios.defaultModels.` or `android.defaultModels.` to one +model name, or to a non-empty list of them: + +```json +{ + "ios": { "defaultModels": { "phone": "iPhone 15", "tablet": ["iPad (A16)", "iPad (10th generation)"] } }, + "android": { "defaultModels": { "phone": "Pixel 7" } } +} +``` + +An empty string, an empty list, a list with an empty string, and a key that is +not a class are refused when the config loads. A name that is not a model of +that class on this machine is skipped, not an error: with `ios.defaultModels.phone` +set to an iPad, the `phone` default is the first of Simlock's own names that +qualifies. Which class a model belongs to is what the platform's tools report; +see `modelClasses` in [`simlock catalog`](CLI.md#simlock-catalog---platform-iosandroid---json). + ## Android emulator launch options `android.emulator` sets how this machine's Android emulators are launched. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 4351f4056..96dca1454 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -285,6 +285,16 @@ entry, and is still listed and leasable by name. On a gateway it is the union over the connected workers; when two workers class a model differently, the worker with the smallest id wins. +Each entry also carries `classDefaults`: for a class, the model Simlock would +create for it on that machine. It is the first name on the class's preference +list (the names in `ios.defaultModels.` or `android.defaultModels.`, +then Simlock's own list for the platform) that `models` lists, that is a model +of the class, and that pairs with an installed runtime; when none pairs, the +first of those that are listed and of the class. A class in which no listed +name counts has no entry. On a gateway a class's entry is kept only when every +connected worker reports the same model for it, and a worker with none for that +class counts as disagreeing. + An entry may also carry `customModels`: the names from `models` that exist because of something on that machine rather than the platform's tools. On Android that is a profile made with Android Studio's device manager, read @@ -302,7 +312,8 @@ that lists it marks it custom; each worker's own list is in its catalog in "defaultRuntime": "26.0", "modelRuntimes": { "iPhone 16": ["18.4", "26.0"], "iPhone XS": ["18.4"] }, "modelAliases": {}, - "modelClasses": { "iPhone 16": "phone", "iPhone XS": "phone" } + "modelClasses": { "iPhone 16": "phone", "iPhone XS": "phone" }, + "classDefaults": { "phone": "iPhone 16" } }, { "platform": "android", "models": ["My Tablet", "Pixel 8"], @@ -311,6 +322,7 @@ that lists it marks it custom; each worker's own list is in its catalog in "modelRuntimes": { "My Tablet": ["34", "35"], "Pixel 8": ["34", "35"] }, "modelAliases": { "Pixel 8": ["pixel_8"] }, "modelClasses": { "My Tablet": "phone", "Pixel 8": "phone" }, + "classDefaults": { "phone": "Pixel 8" }, "customModels": ["My Tablet"], "images": [ { "runtime": "34", "tag": "default", "abi": "x86_64" }, { "runtime": "35", "tag": "google_apis", "abi": "arm64-v8a" } ] @@ -1063,7 +1075,8 @@ simulated (hence the thin Android catalog), trimmed to one worker: "defaultRuntime": "26.0", "modelRuntimes": {"iPhone 16": ["18.4"]}, "modelAliases": {}, - "modelClasses": {"iPhone 16": "phone"} + "modelClasses": {"iPhone 16": "phone"}, + "classDefaults": {"phone": "iPhone 16"} }, { "platform": "android", @@ -1073,6 +1086,7 @@ simulated (hence the thin Android catalog), trimmed to one worker: "modelRuntimes": {}, "modelAliases": {}, "modelClasses": {}, + "classDefaults": {}, "images": [{"runtime": "18.0", "tag": "google_apis", "abi": "arm64-v8a"}] } ], diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 51dc8fb08..9e782c30d 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -268,8 +268,9 @@ relays that operation to workers, so a worker without it must be `incompatible` rather than fail in the middle of a relay. ADR 0014 gives every event envelope an `id`, taking it to 10, and ADR 0009 makes `atRamBudget` a required capacity field, taking it to 11, and ADR 0015 §3 makes -`modelClasses` a required catalog field, taking it to 12. So the range both -sides advertise is `{min: 12, max: 12}`, an older client and a current daemon simply +`modelClasses` a required catalog field, taking it to 12, and ADR 0015 §4 makes +`classDefaults` one too, taking it to 13. So the range both +sides advertise is `{min: 13, max: 13}`, an older client and a current daemon simply do not overlap, and `hello` fails with `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges. The same negotiation runs over a worker's uplink, which is why a worker older than this shows up in a gateway's views as `incompatible` @@ -832,7 +833,9 @@ of fleet models and fleet runtimes: one worker with the model and another with the runtime is not a leasable pair. `modelAliases` is the union per model, deduplicated ignoring case, `modelClasses` the union over workers (ADR 0015 §3: when two class a model differently, the first worker in id -order wins), and `images` the union by runtime, tag, and ABI, absent when no +order wins), `classDefaults` a class's model only when every connected worker +reports the same one for it (a worker with none counts as disagreeing, ADR 0015 §4), +and `images` the union by runtime, tag, and ABI, absent when no worker reports the field. `customModels` lists a model when any worker that lists it marks it custom; a name a worker marks but does not list is dropped. Each worker's lists are @@ -907,7 +910,8 @@ emits its own facts — `worker.connected`, `worker.disconnected`, `{min: 9, max: 9}`, because the gateway is to relay `component.install` to workers, and ADR 0014 to `{min: 10, max: 10}`, because every event envelope has an `id`, and ADR 0009 to `{min: 11, max: 11}`, because `atRamBudget` is required, and - ADR 0015 to `{min: 12, max: 12}`, because the catalog's `modelClasses` is required; a + ADR 0015 to `{min: 12, max: 12}`, because the catalog's `modelClasses` is required, then + to `{min: 13, max: 13}`, because its `classDefaults` is; a worker on an older version is `incompatible` the same way. That is the ordinary upgrade path, not a failure mode: upgrade the worker. An incompatible worker is marked `incompatible` in its view with both ranges shown and is never dispatched to, and it is not diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index 7527e8ec5..02e842ec9 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -1,3 +1,4 @@ +import { readFileSync } from "node:fs"; import { appendFile, mkdir, readFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname } from "node:path"; @@ -27,7 +28,7 @@ import { PassthroughRefusedError, removeListedComponent, } from "../../dist/core/driver.js"; -import type { DeviceSpec, Platform } from "../../dist/core/domain.js"; +import type { DeviceClass, DeviceSpec, Platform } from "../../dist/core/domain.js"; import type { FakeDriverErrorSpec, FakeDriverOperation, @@ -217,6 +218,21 @@ export class OutOfProcessFakeDriver implements Driver { this.#scriptPath = options.scriptPath; } + /** + * The script's `defaultModels`, `{}` when unset. Read from the file on each access, as every + * operation re-reads it, but synchronously: the port reads this as a property, once at start. + */ + get defaultModels(): Readonly>> { + if (this.#scriptPath === undefined) return {}; + try { + const parsed = JSON.parse(readFileSync(this.#scriptPath, "utf8")) as FakeDriverScript; + return parsed[this.platform]?.defaultModels ?? {}; + } catch { + // The same fallback as `readPlatformScript`: a missing or half-written file reads as unset. + return {}; + } + } + /** * Logged like every other call, so a flow can assert the purge re-proved the root before * it destroyed anything -- and refusable through `failures.revalidateRoot`, which is how diff --git a/e2e/fake-driver/types.ts b/e2e/fake-driver/types.ts index 4815d3922..4483b98db 100644 --- a/e2e/fake-driver/types.ts +++ b/e2e/fake-driver/types.ts @@ -80,6 +80,8 @@ export interface FakeDriverPlatformScript { readonly modelRuntimes?: Readonly>; /** What `listCatalog` reports as other names per model; none unless set. */ readonly modelAliases?: Readonly>; + /** The built-in preference lists the driver carries, per class; none unless set. */ + readonly defaultModels?: Readonly>>; /** What `listCatalog` reports as each model's class; empty unless set. */ readonly modelClasses?: Readonly>; /** What `listCatalog` reports as custom models; the field is absent unless set. */ diff --git a/e2e/lease-lifecycle.test.ts b/e2e/lease-lifecycle.test.ts index a61665b10..4ad167a8c 100644 --- a/e2e/lease-lifecycle.test.ts +++ b/e2e/lease-lifecycle.test.ts @@ -64,4 +64,30 @@ describe("lease lifecycle across both frontends", () => { await env.expectEvents(["lease.requested", "lease.granted", "lease.released"]); }); + + it("catalog shows each class's default model: the configured name before the driver's list, skipped when the catalog does not list it", async () => { + const script = { + ios: { + availableOsVersions: ["26.0"], + defaultModels: { phone: ["iPhone 17", "iPhone 16"], tablet: ["iPad Pro"] }, + knownModels: ["iPhone 15", "iPhone 16", "iPad Pro"], + modelClasses: { "iPad Pro": "tablet", "iPhone 15": "phone", "iPhone 16": "phone" }, + }, + } as const; + const defaultsWith = async (phone: string | undefined) => { + const env = await withDaemon({ + configOverrides: phone === undefined ? {} : { ios: { defaultModels: { phone } } }, + driverScript: script, + }); + const catalog = await env.cli(["catalog", "--json", "--platform", "ios"]); + expect(catalog.code, catalog.stderr).toBe(0); + return (catalog.json as { platforms: { classDefaults: unknown }[] }).platforms[0] + ?.classDefaults; + }; + + // The driver's list alone: iPhone 17 is not listed, so iPhone 16 is the first that counts. + expect(await defaultsWith(undefined)).toEqual({ phone: "iPhone 16", tablet: "iPad Pro" }); + expect(await defaultsWith("iPhone 15")).toEqual({ phone: "iPhone 15", tablet: "iPad Pro" }); + expect(await defaultsWith("iPhone 99")).toEqual({ phone: "iPhone 16", tablet: "iPad Pro" }); + }); }); diff --git a/e2e/slow-ios-smoke.test.ts b/e2e/slow-ios-smoke.test.ts index 2990a2ce5..250afa7ec 100644 --- a/e2e/slow-ios-smoke.test.ts +++ b/e2e/slow-ios-smoke.test.ts @@ -30,6 +30,45 @@ async function simctlRuntimes(): Promise { return parsed.runtimes.filter((runtime) => runtime.isAvailable).map((runtime) => runtime.version); } +/** Every runtime the catalog lists is one real simctl reports as installed. */ +function expectRuntimesAgree(reported: readonly string[] | undefined, available: string[]): void { + for (const runtime of reported ?? []) { + expect(available, "simlock catalog's runtimes must agree with real simctl").toContain(runtime); + } +} + +/** The catalog's default phone model, read through the CLI as the daemon currently reports it. */ +async function iosPhoneDefault(env: TestEnv): Promise { + const reported = await env.cli(["catalog", "--json", "--platform", "ios"]); + expect(reported.code, `catalog failed: ${reported.stderr}`).toBe(0); + const platforms = ( + reported.json as { platforms: { platform: string; classDefaults: Record }[] } + ).platforms; + return platforms.find((platform) => platform.platform === "ios")?.classDefaults["phone"]; +} + +/** + * `ios.defaultModels` against a real catalog: a configured name the catalog lists is the shown + * default, and one it does not list falls through to the built-in list. + */ +async function expectConfiguredPhoneDefaults( + env: TestEnv, + models: readonly string[] | undefined, +): Promise { + expect(models ?? [], "this lane needs the host's simctl to list iPhone 15").toContain( + "iPhone 15", + ); + await env.withConfig({ ios: { defaultModels: { phone: ["iPhone 15"] } } }, async () => { + expect(await iosPhoneDefault(env)).toBe("iPhone 15"); + }); + await env.withConfig( + { ios: { defaultModels: { phone: ["Simlock Unlisted Phone"] } } }, + async () => { + expect(await iosPhoneDefault(env)).toBe("iPhone 17"); + }, + ); +} + // This lane needs the real simctl toolchain, hence darwin-only and gated on an // installed runtime -- it never installs one itself (no --allow-download). /** @@ -72,6 +111,7 @@ describe.skipIf(process.platform !== "darwin")( models: string[]; runtimes: string[]; modelClasses: Record; + classDefaults: Record; }[]; } ).platforms; @@ -84,12 +124,10 @@ describe.skipIf(process.platform !== "darwin")( // The class comes from the device type's product family, read off this host's simctl. expect(iosCatalog?.modelClasses["iPhone 17"]).toBe("phone"); expect(iosCatalog?.modelClasses["Apple Watch Series 11 (46mm)"]).toBe("watch"); - for (const runtime of iosCatalog?.runtimes ?? []) { - expect( - availableRuntimes, - "simlock catalog's runtimes must agree with real simctl", - ).toContain(runtime); - } + // With no `ios.defaultModels`, the built-in list's first listed phone is the default. + expect(iosCatalog?.classDefaults["phone"]).toBe("iPhone 17"); + await expectConfiguredPhoneDefaults(env, iosCatalog?.models); + expectRuntimesAgree(iosCatalog?.runtimes, availableRuntimes); const model = iosCatalog?.models[0] as string; const lease = await env.cli( diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 9c1cc9fca..8310dc692 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1889,6 +1889,7 @@ describe("CLI: catalog", () => { platforms: [ { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: {}, models: ["constructor"], @@ -1915,6 +1916,7 @@ describe("CLI: catalog", () => { platforms: [ { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: {}, models: [], @@ -1944,6 +1946,7 @@ describe("CLI: catalog", () => { { defaultRuntime: "26.0", modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 16": ["18.4", "26.0"], @@ -1978,6 +1981,7 @@ describe("CLI: catalog", () => { it("prints each model under its class in the order of the enum, and an unclassed model under (no class)", async () => { const catalog = { defaultRuntime: "26.0", + classDefaults: { phone: "iPhone 17", tablet: "iPad Pro" }, modelAliases: { "iPhone 17": ["iphone-17", "i17"] }, modelClasses: { "Apple TV 4K": "tv" as const, @@ -2019,15 +2023,15 @@ describe("CLI: catalog", () => { "Platform: ios", " Runtimes: 26.0 (default: 26.0)", " Models:", - " phone:", + " phone (default: iPhone 17):", " iPhone 17: 26.0", " Other names: iphone-17, i17", " iPhone 16 (custom): 26.0", - " tablet:", + " tablet (default: iPad Pro):", " iPad Pro: 26.0", - " watch:", + " watch (default: none):", " Apple Watch Series 11 (46mm): 26.0", - " tv:", + " tv (default: none):", " Apple TV 4K: 26.0", " (no class):", " Mystery: (no paired runtime)", @@ -2036,9 +2040,31 @@ describe("CLI: catalog", () => { ); }); + it("carries classDefaults in --json as received", async () => { + const catalog = { + classDefaults: { phone: "Pixel 9", tv: "Not Even Listed" }, + modelAliases: {}, + modelClasses: {}, + modelRuntimes: {}, + models: [], + platform: "android" as const, + runtimes: [], + }; + const output = outputCapture(); + const environment = output.environmentWith({ + connectAdmin: async () => + fakeClient({ getCatalog: () => Promise.resolve({ platforms: [catalog] }) }), + }); + + await expect(runCli(["catalog", "--json"], environment)).resolves.toBe(0); + + expect(JSON.parse(output.stdout)).toEqual({ platforms: [catalog] }); + }); + it("carries modelClasses in --json as received", async () => { const catalog = { modelAliases: {}, + classDefaults: {}, modelClasses: { "Pixel 8": "phone" as const, "Odd One": "tv" as const }, modelRuntimes: {}, models: ["Pixel 8"], @@ -2067,6 +2093,7 @@ describe("CLI: catalog", () => { { images: [], modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: {}, models: [], @@ -2106,6 +2133,7 @@ describe("CLI: catalog", () => { { abi: "arm64-v8a", runtime: "35", tag: "google_apis" }, ], modelAliases: { "Pixel 8": ["pixel_8"] }, + classDefaults: {}, modelClasses: { "Pixel 8": "phone" }, modelRuntimes: { "My Tablet": ["34", "35"], "Pixel 8": ["34", "35"] }, models: ["My Tablet", "Pixel 8"], @@ -2124,7 +2152,7 @@ describe("CLI: catalog", () => { "Platform: android", " Runtimes: 34, 35 (default: 35)", " Models:", - " phone:", + " phone (default: none):", " Pixel 8: 34, 35", " Other names: pixel_8", " (no class):", @@ -2149,6 +2177,7 @@ describe("CLI: catalog", () => { customModels: ["My Tablet"], defaultRuntime: "35", modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "My Tablet": ["35"], "Pixel 8": ["35"] }, models: ["My Tablet", "Pixel 8"], @@ -5034,8 +5063,11 @@ function testConfig(): Config { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, lease: { defaultTtlMs: 60_000, diff --git a/src/cli/index.ts b/src/cli/index.ts index abce526ce..9b7217768 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -2388,11 +2388,17 @@ function formatCatalog(response: CatalogGetOutput): string { // Models sit under a line for their class, in the order of the enum, then `(no class)`. const classOf = (model: string): string | undefined => Object.hasOwn(entry.modelClasses, model) ? entry.modelClasses[model] : undefined; + // A class line says which model Simlock would create for it on this host, or `none`. + const classLine = (deviceClass: string | undefined): string => { + if (deviceClass === undefined) return " (no class):"; + const model = Object.hasOwn(entry.classDefaults, deviceClass) + ? entry.classDefaults[deviceClass as keyof typeof entry.classDefaults] + : undefined; + return ` ${deviceClass} (default: ${model ?? "none"}):`; + }; const models = [...DEVICE_CLASS_ORDER, undefined].flatMap((deviceClass) => { const members = entry.models.filter((model) => classOf(model) === deviceClass); - return members.length === 0 - ? [] - : [` ${deviceClass ?? "(no class)"}:`, ...members.flatMap(modelLine)]; + return members.length === 0 ? [] : [classLine(deviceClass), ...members.flatMap(modelLine)]; }); const images = (entry.images ?? []).map( (image) => ` ${image.runtime} ${image.tag} ${image.abi}`, diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 70ea0f971..3485612b1 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -481,6 +481,7 @@ describe("operation input/output round trips", () => { models: ["iPhone 17"], runtimes: ["26.0"], modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, }, @@ -512,6 +513,7 @@ describe("operation input/output round trips", () => { models: ["iPhone 17"], runtimes: ["26.0"], modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, modelWorkers: { "iPhone 17": ["wrk_1", "wrk_2"] }, @@ -528,6 +530,7 @@ describe("operation input/output round trips", () => { models: ["iPhone 17"], runtimes: ["26.0"], modelAliases: {}, + classDefaults: {}, modelClasses: {}, }; expect(() => OPERATIONS["catalog.get"].output.parse({ platforms: [entry] })).toThrow( @@ -545,6 +548,7 @@ describe("operation input/output round trips", () => { platform: "ios", models: ["iPhone 17"], runtimes: ["26.0"], + classDefaults: {}, modelAliases: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, }; @@ -566,6 +570,7 @@ describe("operation input/output round trips", () => { platform: "android", models: ["Pixel 8"], runtimes: ["35"], + classDefaults: {}, modelClasses: {}, modelRuntimes: { "Pixel 8": ["35"] }, }; @@ -593,6 +598,7 @@ describe("operation input/output round trips", () => { runtimes: ["35"], modelRuntimes: { "Pixel 8": ["35"] }, modelAliases: {}, + classDefaults: {}, modelClasses: {}, }; const image = { runtime: "35", tag: "google_apis", abi: "arm64-v8a" }; @@ -795,8 +801,11 @@ describe("operation input/output round trips", () => { recoveryBackoffMs: 1, maxConcurrentRecoveries: 1, }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 1 } }, - android: { emulator: { headless: true, gpu: "host", audio: false, bootAnimation: false } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 1 } }, + android: { + defaultModels: {}, + emulator: { headless: true, gpu: "host", audio: false, bootAnimation: false }, + }, stalledTransition: { thresholdMultiplier: 1, minimumThresholdMs: 1 }, }; expect(OPERATIONS["config.get"].output.parse(config)).toBeDefined(); @@ -813,6 +822,23 @@ describe("operation input/output round trips", () => { expect(() => shape.parse({ ...budget, limitBytes: Number.POSITIVE_INFINITY })).toThrow(); }); + it("config.get: carries each platform's defaultModels as lists of names per class, and refuses anything else", () => { + const shape = OPERATIONS["config.get"].output.shape; + const parse = (defaultModels: unknown) => ({ + ios: shape.ios.shape.defaultModels.safeParse(defaultModels), + android: shape.android.shape.defaultModels.safeParse(defaultModels), + }); + + for (const parsed of Object.values(parse({ phone: ["iPhone 15", "iPhone 14"], tv: ["x"] }))) { + expect(parsed.success).toBe(true); + expect(parsed.data).toEqual({ phone: ["iPhone 15", "iPhone 14"], tv: ["x"] }); + } + for (const refused of [{ phone: [] }, { phone: [""] }, { fridge: ["x"] }, { phone: "x" }]) { + expect(parse(refused).ios.success).toBe(false); + expect(parse(refused).android.success).toBe(false); + } + }); + it("config.get: keeps both slim RAM sizes of the resource strategy when they are set", () => { const ramBudget = { androidBytesPerDevice: 4, diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index ab878e048..66b022e29 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -14,7 +14,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** - * The range this contract's daemon speaks. Both ends are 12, and every move that got it there + * The range this contract's daemon speaks. Both ends are 13, and every move that got it there * was breaking with no shim kept behind them, which is exactly when ADR 0003 §6's honesty * rule says a range must *not* widen: ADR 0004 removed `lease.heartbeat` and `mode` from the * wire (taking it to 4), and ADR 0005 adds `device.exec` and its `output` push family, a @@ -29,7 +29,7 @@ const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().in * workers, so a worker without it must be `incompatible` rather than fail in the middle of a * relay. ADR 0014 gives every event envelope an `id` (taking it to 10): a worker's pushed events * without one would fail the gateway's schema, so a worker on 9 is `incompatible` instead. ADR 0009 §7 makes `atRamBudget` a required field of each platform's `status.get` - * capacity (taking it to 11), which a gateway routing on it depends on. ADR 0015 §3 makes `modelClasses` a required field of each platform's catalog (taking it to 12): a gateway reading a worker's catalog would fail its schema without it, so a worker on 11 is `incompatible`. It only ever widens once a second version is actually kept alive side by side with the + * capacity (taking it to 11), which a gateway routing on it depends on. ADR 0015 §3 makes `modelClasses` a required field of each platform's catalog (taking it to 12): a gateway reading a worker's catalog would fail its schema without it, so a worker on 11 is `incompatible`. ADR 0015 §4 makes `classDefaults` a required field of each platform's catalog too (taking it to 13), for the same reason: a worker on 12 is `incompatible`. It only ever widens once a second version is actually kept alive side by side with the * first, which nothing here does. * * A client from before any of those changes simply does not overlap this daemon, and `hello` @@ -42,9 +42,9 @@ const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().in * The consequence ADR 0005 §31 names: a pre-0005 worker's uplink negotiates nothing, so its * gateway marks it `incompatible` -- with both ranges on the view -- and never dispatches to it. * A worker on 5 is marked `incompatible` the same way (ADR 0008 §10), and so is one on 7 - * (ADR 0007 §12), and so is one on 8 (ADR 0010 §9), one on 10 (ADR 0009 §7), and one on 11 (ADR 0015 §3). + * (ADR 0007 §12), and so is one on 8 (ADR 0010 §9), one on 10 (ADR 0009 §7), one on 11 (ADR 0015 §3), and one on 12 (ADR 0015 §4). */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 12, max: 12 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 13, max: 13 }; /** * The one protocol version that ever existed before ranges did. Used only to build the diff --git a/src/contract/schemas.test.ts b/src/contract/schemas.test.ts index 38131683d..8f2257eef 100644 --- a/src/contract/schemas.test.ts +++ b/src/contract/schemas.test.ts @@ -295,6 +295,7 @@ describe("fitPlatformCatalog", () => { defaultRuntime: "35", modelAliases: {}, modelClasses: {}, + classDefaults: {}, modelRuntimes: Object.fromEntries(customModels.map((model) => [model, ["35"]])), models: customModels, platform: "android" as const, @@ -327,6 +328,16 @@ describe("fitPlatformCatalog", () => { expect(() => platformCatalogSchema.parse(fitted)).not.toThrow(); }); + it("drops a classDefaults model name too long for the schema and keeps the rest", () => { + const fitted = fitPlatformCatalog({ + ...entry([]), + classDefaults: { phone: "Pixel 8", tv: "x".repeat(257) }, + }); + + expect(fitted.classDefaults).toEqual({ phone: "Pixel 8" }); + expect(() => platformCatalogSchema.parse(fitted)).not.toThrow(); + }); + it("leaves an entry that already fits as it is", () => { const fits = entry(["My Tablet"]); @@ -371,3 +382,39 @@ describe("leaseRequestRecordSchema", () => { expect(grantedDeviceSchema.safeParse(device).success).toBe(false); }); }); + +describe("platformCatalogSchema classDefaults", () => { + const entry = { + defaultRuntime: "35", + modelAliases: {}, + modelClasses: {}, + modelRuntimes: {}, + models: [], + platform: "android" as const, + runtimes: ["35"], + }; + + it("requires classDefaults", () => { + expect(platformCatalogSchema.safeParse(entry).success).toBe(false); + expect(platformCatalogSchema.safeParse({ ...entry, classDefaults: {} }).success).toBe(true); + }); + + it("accepts a model name for a class", () => { + const parsed = platformCatalogSchema.parse({ ...entry, classDefaults: { phone: "Pixel 9" } }); + + expect(parsed.classDefaults).toEqual({ phone: "Pixel 9" }); + }); + + it("refuses a key that is not a class", () => { + expect( + platformCatalogSchema.safeParse({ ...entry, classDefaults: { fridge: "Pixel 9" } }).success, + ).toBe(false); + }); + + it("refuses a model name longer than the catalog's name bound", () => { + expect( + platformCatalogSchema.safeParse({ ...entry, classDefaults: { phone: "x".repeat(257) } }) + .success, + ).toBe(false); + }); +}); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 75bf8330b..c3366e980 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -491,6 +491,14 @@ export const platformCatalogSchema = z.object({ modelClasses: z .record(z.string().max(CATALOG_NAME_MAX), deviceClassSchema) .refine((classes) => Object.keys(classes).length <= CATALOG_ALIASED_MODELS_MAX), + /** + * ADR 0015 §4: for a class, the model Simlock would create for it on this host -- of the + * names on the class's preference list that `models` lists and that are of the class, the + * first that pairs with an installed runtime, else the first of them. A class in which no + * listed model counts has no entry. On a gateway a class's entry is kept only when every + * connected worker reports the same model for it, and that worker lists it itself. + */ + classDefaults: z.record(deviceClassSchema, z.string().max(CATALOG_NAME_MAX)), /** * ADR 0008 §1: every installed image, present only for a platform whose driver has images * (Android). `runtime` is a value from `runtimes`; an image of an ABI the host cannot run @@ -526,9 +534,10 @@ export function fitPlatformCatalog< Entry extends { readonly customModels?: readonly string[]; readonly modelClasses?: Readonly>; + readonly classDefaults?: Readonly>>; }, >(entry: Entry): Entry { - const { customModels, modelClasses, ...rest } = entry; + const { classDefaults, customModels, modelClasses, ...rest } = entry; const fitting = (customModels ?? []) .filter((model) => model.length <= CATALOG_NAME_MAX) .slice(0, CATALOG_CUSTOM_MODELS_MAX); @@ -541,6 +550,13 @@ export function fitPlatformCatalog< Object.entries(modelClasses).filter(([model]) => model.length <= CATALOG_NAME_MAX), ), }), + ...(classDefaults === undefined + ? {} + : { + classDefaults: Object.fromEntries( + Object.entries(classDefaults).filter(([, model]) => model.length <= CATALOG_NAME_MAX), + ), + }), ...(fitting.length === 0 ? {} : { customModels: fitting }), } as unknown as Entry; } @@ -697,6 +713,9 @@ const capacityConfigSchema = z.discriminatedUnion("strategy", [ ]); /** Mirrors `Config` (src/core/config.ts) field for field. */ +/** ADR 0015 §4: `ios.defaultModels` and `android.defaultModels`, a list of model names per class. */ +const defaultModelsSchema = z.record(deviceClassSchema, z.array(z.string().min(1)).min(1)); + export const configSchema = z.object({ /** ADR 0005 §1. `config.get` is how a caller learns which mode the daemon it is talking to * runs in without inferring it from behaviour; `status.get`'s `daemon.mode` is the @@ -754,12 +773,14 @@ export const configSchema = z.object({ }), ios: z.object({ defaultMode: deviceModeSchema, + defaultModels: defaultModelsSchema, slim: z.object({ categories: z.array(z.string()).optional(), bootTimeoutMs: z.number(), }), }), android: z.object({ + defaultModels: defaultModelsSchema, emulator: z.object({ headless: z.boolean(), gpu: z.string().min(1), diff --git a/src/core/acquisition-planner.test.ts b/src/core/acquisition-planner.test.ts index 771d24df2..b9e2c4ba7 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -32,8 +32,11 @@ const config: Config = { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, warmPool: { quarantine: { diff --git a/src/core/catalog-match.test.ts b/src/core/catalog-match.test.ts new file mode 100644 index 000000000..e838c85e9 --- /dev/null +++ b/src/core/catalog-match.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from "vitest"; + +import { findCatalogModel } from "./catalog-match.js"; + +describe("findCatalogModel", () => { + const entry = { + modelAliases: { "Pixel 8": ["pixel_8", "P8"], "Pixel 9": ["pixel_9"] }, + models: ["Pixel 9", "Pixel 8"], + }; + + it("matches a model name in any letter case and returns the listed spelling", () => { + expect(findCatalogModel(entry, "pIxEl 8")).toBe("Pixel 8"); + }); + + it("matches an alias in any letter case and returns the model it belongs to", () => { + expect(findCatalogModel(entry, "PIXEL_9")).toBe("Pixel 9"); + expect(findCatalogModel(entry, "p8")).toBe("Pixel 8"); + }); + + it("returns the first listed model whose name or alias matches", () => { + expect( + findCatalogModel( + { modelAliases: { "Pixel 8": ["Pixel 9"] }, models: ["Pixel 8", "Pixel 9"] }, + "pixel 9", + ), + ).toBe("Pixel 8"); + }); + + it("returns undefined for a name nothing lists", () => { + expect(findCatalogModel(entry, "Pixel 10")).toBeUndefined(); + }); + + it("ignores inherited keys, so a model named constructor reads no aliases off Object.prototype", () => { + expect( + findCatalogModel({ modelAliases: {}, models: ["constructor"] }, "tostring"), + ).toBeUndefined(); + expect(findCatalogModel({ modelAliases: {}, models: ["constructor"] }, "constructor")).toBe( + "constructor", + ); + }); +}); diff --git a/src/core/catalog-match.ts b/src/core/catalog-match.ts new file mode 100644 index 000000000..d062578f3 --- /dev/null +++ b/src/core/catalog-match.ts @@ -0,0 +1,32 @@ +/** The part of a platform catalog entry that says which names a model answers to. */ +interface CatalogNames { + readonly models: readonly string[]; + readonly modelAliases: Readonly>; +} + +/** + * The first entry of `models` whose name or whose `modelAliases` entry equals `name`, ignoring + * letter case, as the listed spelling. A name a request or a preference list uses is a claim + * about this host; this is how it is checked against what the catalog lists. + */ +export function findCatalogModel(entry: CatalogNames, name: string): string | undefined { + const wanted = fold(name); + return entry.models.find( + (model) => + fold(model) === wanted || + ownList(entry.modelAliases, model).some((alias) => fold(alias) === wanted), + ); +} + +/** Locale-independent, so two hosts on different locales fold a name alike. */ +function fold(name: string): string { + return name.toLowerCase(); +} + +/** A record lookup that ignores inherited keys, so a model named `constructor` reads nothing. */ +function ownList( + record: Readonly>, + key: string, +): readonly string[] { + return (Object.hasOwn(record, key) ? record[key] : undefined) ?? []; +} diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index cf8ccfd5e..09207b688 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -28,8 +28,11 @@ const config: Config = { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, idle: { deleteAfterMs: 30_000, shutdownAfterMs: 10_000 }, warmPool: { quarantine: { diff --git a/src/core/cleanup/idle-shutdown.test.ts b/src/core/cleanup/idle-shutdown.test.ts index 77ce7ef13..81825bbad 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -26,8 +26,11 @@ const config: Config = { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, idle: { deleteAfterMs: 30_000, shutdownAfterMs: 10_000 }, warmPool: { quarantine: { diff --git a/src/core/config.test.ts b/src/core/config.test.ts index db287a17f..bf38c10fb 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -119,7 +119,7 @@ describe("loadConfig", () => { }, }, stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, }); expect(Object.isFrozen(config)).toBe(true); expect(Object.isFrozen(resourceOptions(config).limits)).toBe(true); @@ -815,11 +815,17 @@ describe("loadConfig", () => { }); it.each([ - [{ android: { emulator: { headless: "yes" } } }, "android.emulator.headless"], - [{ android: { emulator: { audio: 0 } } }, "android.emulator.audio"], - [{ android: { emulator: { bootAnimation: "false" } } }, "android.emulator.bootAnimation"], - [{ android: { emulator: { gpu: "" } } }, "android.emulator.gpu"], - [{ android: { emulator: { gpu: true } } }, "android.emulator.gpu"], + [ + { android: { defaultModels: {}, emulator: { headless: "yes" } } }, + "android.emulator.headless", + ], + [{ android: { defaultModels: {}, emulator: { audio: 0 } } }, "android.emulator.audio"], + [ + { android: { defaultModels: {}, emulator: { bootAnimation: "false" } } }, + "android.emulator.bootAnimation", + ], + [{ android: { defaultModels: {}, emulator: { gpu: "" } } }, "android.emulator.gpu"], + [{ android: { defaultModels: {}, emulator: { gpu: true } } }, "android.emulator.gpu"], ])("rejects a malformed android.emulator key at load, naming it", async (contents, path) => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); @@ -836,7 +842,9 @@ describe("loadConfig", () => { await filesystem.mkdirp("/home/agent/.simlock"); await filesystem.writeFileAtomic( configPath, - JSON.stringify({ android: { emulator: { launchArgs: ["-port", "5554"] } } }), + JSON.stringify({ + android: { defaultModels: {}, emulator: { launchArgs: ["-port", "5554"] } }, + }), ); const config = await loadConfig({ configPath, filesystem, systemStats: createStats(), warn }); @@ -849,6 +857,110 @@ describe("loadConfig", () => { ]); }); + it.each(["ios", "android"] as const)( + "%s.defaultModels defaults to no class having a list", + async (platform) => { + const config = await loadConfig({ + configPath, + filesystem: new MemoryFilesystem(), + systemStats: createStats(), + }); + + expect(config[platform].defaultModels).toEqual({}); + }, + ); + + it.each([ + ["ios", "phone", "iPhone 15"], + ["ios", "tablet", ["iPad (A16)", "iPad (10th generation)"]], + ["android", "phone", "Pixel 7"], + ["android", "tv", ["Television (4K)"]], + ] as const)( + "%s.defaultModels.%s accepts one model name or a list of them", + async (platform, deviceClass, value) => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic( + configPath, + JSON.stringify({ [platform]: { defaultModels: { [deviceClass]: value } } }), + ); + + const config = await loadConfig({ configPath, filesystem, systemStats: createStats() }); + + expect(config[platform].defaultModels[deviceClass]).toEqual( + typeof value === "string" ? [value] : value, + ); + }, + ); + + it("stores a string ios.defaultModels value as a one-element list", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic( + configPath, + JSON.stringify({ ios: { defaultModels: { phone: "iPhone 15" } } }), + ); + + const config = await loadConfig({ configPath, filesystem, systemStats: createStats() }); + + expect(config.ios.defaultModels).toStrictEqual({ phone: ["iPhone 15"] }); + }); + + it.each([ + [{ phone: "" }, "ios.defaultModels.phone"], + [{ phone: [] }, "ios.defaultModels.phone"], + [{ phone: ["iPhone 15", ""] }, "ios.defaultModels.phone"], + [{ phone: 15 }, "ios.defaultModels.phone"], + [{ phone: [15] }, "ios.defaultModels.phone"], + [{ phone: [["iPhone 15"]] }, "ios.defaultModels.phone"], + [{ mobile: "iPhone 15" }, "ios.defaultModels.mobile"], + [{ constructor: "iPhone 15" }, "ios.defaultModels.constructor"], + ])("refuses ios.defaultModels %j, naming the key", async (defaultModels, path) => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic(configPath, JSON.stringify({ ios: { defaultModels } })); + + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow(`Invalid config value for "${path}"`); + }); + + it("says what ios.defaultModels expects: a device class for a key, a name or a list of names for a value", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + const load = async (defaultModels: unknown) => { + await filesystem.writeFileAtomic(configPath, JSON.stringify({ ios: { defaultModels } })); + return loadConfig({ configPath, filesystem, systemStats: createStats() }); + }; + + await expect(load({ mobile: "iPhone 15" })).rejects.toThrow( + "expected a device class (phone, tablet, watch, tv, vision, auto, desktop)", + ); + await expect(load({ phone: [] })).rejects.toThrow( + "expected a model name or a non-empty list of model names", + ); + }); + + it("refuses an empty android.defaultModels list and a key that is not a class, naming the key", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic( + configPath, + JSON.stringify({ android: { defaultModels: { phone: [] } } }), + ); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow('Invalid config value for "android.defaultModels.phone"'); + + await filesystem.writeFileAtomic( + configPath, + JSON.stringify({ android: { defaultModels: { fridge: "Pixel 8" } } }), + ); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow('Invalid config value for "android.defaultModels.fridge"'); + }); + it("applies a file-level stalledTransition override", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); @@ -1252,7 +1364,7 @@ describe("loadConfig modes (ADR 0005)", () => { it("warns about android.emulator on a gateway without refusing the config", async () => { const warn = vi.fn(); const config = await load( - { mode: "gateway", android: { emulator: { headless: true } } }, + { mode: "gateway", android: { defaultModels: {}, emulator: { headless: true } } }, { warn }, ); diff --git a/src/core/config.ts b/src/core/config.ts index 9e3255e71..a005ee567 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -11,7 +11,7 @@ import { type ResourceStrategyOptions, } from "./capacity/index.js"; import { resourceOptionValidators } from "./capacity/strategies/resource/index.js"; -import type { DeviceMode, LeaseIdentity } from "./domain.js"; +import { DEVICE_CLASSES, type DeviceClass, type DeviceMode, type LeaseIdentity } from "./domain.js"; import { booleanValue, ConfigError, @@ -204,6 +204,8 @@ export interface Config { * Default `"full"`. Every worker makes both kinds of device whatever this says. */ readonly defaultMode: DeviceMode; + /** The operator's own preference list per class, ahead of the driver's built-in one. */ + readonly defaultModels: DefaultModels; /** How a slim device is made, whatever the default mode is. */ readonly slim: { /** Which daemon categories to disable. Undefined means "every category the driver knows". */ @@ -220,6 +222,8 @@ export interface Config { * next boot. */ readonly android: { + /** The operator's own preference list per class, ahead of the driver's built-in one. */ + readonly defaultModels: DefaultModels; readonly emulator: { readonly headless: boolean; /** An emulator GPU mode; `"auto"` leaves the emulator's own default. */ @@ -664,11 +668,13 @@ function defaultConfig( }, ios: { defaultMode: "full", + defaultModels: {}, slim: { bootTimeoutMs: 600_000, }, }, android: { + defaultModels: {}, emulator: { headless: false, gpu: "auto", @@ -806,12 +812,14 @@ function configValidators(strategy: CapacityStrategyName): Record>; + +/** + * Each key is a device class and each value one non-empty model name or a non-empty list of + * them, stored as a list. Any other key is refused rather than warned about: a misspelled class + * would otherwise leave the operator's preference silently unused. + */ +const defaultModelsValidator: Validator = (value, path) => { + const object = requireObject(value, path); + const result: Record = {}; + + for (const [key, names] of Object.entries(object)) { + const keyPath = `${path}.${key}`; + if (!(DEVICE_CLASSES as readonly string[]).includes(key)) { + throw invalidValue(keyPath, `a device class (${DEVICE_CLASSES.join(", ")})`); + } + const list = typeof names === "string" ? [names] : names; + if (!Array.isArray(list) || list.length === 0 || !list.every(isNonEmptyString)) { + throw invalidValue(keyPath, "a model name or a non-empty list of model names"); + } + result[key] = list; + } + + return result; +}; + +function isNonEmptyString(value: unknown): value is string { + return typeof value === "string" && value.length > 0; +} + /** * Checks the shape of `drivers` and nothing else. Every leaf is type-checked, because a * config file is hand-edited and a nested object or array there is a mistake worth diff --git a/src/core/doctor.test.ts b/src/core/doctor.test.ts index e9ec4f6f1..91e55aadc 100644 --- a/src/core/doctor.test.ts +++ b/src/core/doctor.test.ts @@ -2329,7 +2329,10 @@ function config(stalledTransitionOverrides: Partial }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, }; } diff --git a/src/core/domain.ts b/src/core/domain.ts index 5fb234b21..ae5d364d0 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -6,7 +6,16 @@ export type Platform = "ios" | "android"; * ADR 0015 §3: the kind of device a model is. Declared here beside `Platform` rather than * imported from the contract; which family or tag is which class is the driver's to say. */ -export type DeviceClass = "phone" | "tablet" | "watch" | "tv" | "vision" | "auto" | "desktop"; +export const DEVICE_CLASSES = [ + "phone", + "tablet", + "watch", + "tv", + "vision", + "auto", + "desktop", +] as const; +export type DeviceClass = (typeof DEVICE_CLASSES)[number]; /** The mode a device actually has: slimmed by its driver, or not. */ export type DeviceMode = "slim" | "full"; diff --git a/src/core/driver-catalog.test.ts b/src/core/driver-catalog.test.ts index ea3b64b77..2b87ea6ff 100644 --- a/src/core/driver-catalog.test.ts +++ b/src/core/driver-catalog.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { FakeClock, type Logger } from "../ports/index.js"; import { PassthroughRefusedError } from "./driver.js"; @@ -49,6 +49,7 @@ describe("DriverCatalog", () => { await expect(catalog.listCatalog()).resolves.toEqual([ { + classDefaults: {}, defaultRuntime: "26.5", modelAliases: {}, modelClasses: {}, @@ -58,6 +59,7 @@ describe("DriverCatalog", () => { runtimes: ["18.4", "26.5"], }, { + classDefaults: {}, defaultRuntime: "34", modelAliases: {}, modelClasses: {}, @@ -77,6 +79,7 @@ describe("DriverCatalog", () => { await expect(catalog.listCatalog("ios")).resolves.toEqual([ { + classDefaults: {}, defaultRuntime: "26.5", modelAliases: {}, modelClasses: {}, @@ -98,6 +101,7 @@ describe("DriverCatalog", () => { await expect(catalog.listCatalog()).resolves.toEqual([ { + classDefaults: {}, defaultRuntime: "26.5", modelAliases: {}, modelClasses: {}, @@ -199,4 +203,161 @@ describe("DriverCatalog", () => { expect(() => catalog.passthrough("adb", ["devices"])).toThrow(UnknownPassthroughToolError); }); + + describe("classDefaults", () => { + type Classes = Readonly>; + + async function defaultsOf(options: { + readonly models: readonly string[]; + readonly classes: Classes; + readonly preferences: readonly string[]; + readonly tabletPreferences?: readonly string[]; + readonly modelRuntimes?: Readonly>; + readonly modelAliases?: Readonly>; + }) { + const driver = new FakeDriver({ + availableOsVersions: ["18.4", "26.5"], + clock: new FakeClock(), + knownModels: options.models, + modelAliases: options.modelAliases ?? {}, + modelClasses: options.classes, + ...(options.modelRuntimes === undefined ? {} : { modelRuntimes: options.modelRuntimes }), + platform: "ios", + }); + const catalog = new DriverCatalog([driver], { + preferences: { + ios: { + phone: options.preferences, + ...(options.tabletPreferences === undefined + ? {} + : { tablet: options.tabletPreferences }), + }, + }, + }); + return (await catalog.listCatalog())[0]?.classDefaults; + } + + it("is the first name on the preference list the catalog lists", async () => { + await expect( + defaultsOf({ + classes: { "iPhone 15": "phone", "iPhone 16": "phone" }, + models: ["iPhone 15", "iPhone 16"], + preferences: ["iPhone 17", "iPhone 16", "iPhone 15"], + }), + ).resolves.toEqual({ phone: "iPhone 16" }); + }); + + it("matches a listed name by its alias in any letter case, and names the listed model", async () => { + await expect( + defaultsOf({ + classes: { "Pixel 9": "phone" }, + modelAliases: { "Pixel 9": ["pixel_9"] }, + models: ["Pixel 9"], + preferences: ["PIXEL_9"], + }), + ).resolves.toEqual({ phone: "Pixel 9" }); + }); + + it("matches a listed name in any letter case", async () => { + await expect( + defaultsOf({ + classes: { "iPhone 17": "phone" }, + models: ["iPhone 17"], + preferences: ["iphone 17"], + }), + ).resolves.toEqual({ phone: "iPhone 17" }); + }); + + it("skips a configured name of another class and falls to the next name that counts", async () => { + await expect( + defaultsOf({ + classes: { "iPad (A16)": "tablet", "iPhone 17": "phone", "iPhone 16": "phone" }, + models: ["iPad (A16)", "iPhone 17", "iPhone 16"], + // The merged list: the configured iPad first, the built-in phones after it. + preferences: ["iPad (A16)", "iPhone 17", "iPhone 16"], + }), + ).resolves.toEqual({ phone: "iPhone 17" }); + }); + + it("skips a name whose model has no class", async () => { + await expect( + defaultsOf({ + classes: { "iPhone 16": "phone" }, + models: ["Mystery", "iPhone 16"], + preferences: ["Mystery", "iPhone 16"], + }), + ).resolves.toEqual({ phone: "iPhone 16" }); + }); + + it("skips a name with no paired runtime for a later one that pairs", async () => { + await expect( + defaultsOf({ + classes: { "iPhone 16": "phone", "iPhone 17": "phone" }, + modelRuntimes: { "iPhone 16": ["18.4"], "iPhone 17": [] }, + models: ["iPhone 17", "iPhone 16"], + preferences: ["iPhone 17", "iPhone 16"], + }), + ).resolves.toEqual({ phone: "iPhone 16" }); + }); + + it("shows the first name of the class when none of them pairs with a runtime", async () => { + await expect( + defaultsOf({ + classes: { "iPhone 16": "phone", "iPhone 17": "phone" }, + modelRuntimes: { "iPhone 16": [], "iPhone 17": [] }, + models: ["iPhone 17", "iPhone 16"], + preferences: ["iPhone 17", "iPhone 16"], + }), + ).resolves.toEqual({ phone: "iPhone 17" }); + }); + + it("has no entry for a class in which no name is listed, or in which every listed name is of another class", async () => { + await expect( + defaultsOf({ + classes: { "iPad (A16)": "tablet", "iPhone 16": "phone" }, + models: ["iPad (A16)", "iPhone 16"], + preferences: ["iPhone 15", "iPad (A16)"], + tabletPreferences: ["iPad Pro"], + }), + ).resolves.toEqual({}); + }); + + it("reads only a model's own runtimes: a classed model named constructor pairs with nothing, and a listed model with no runtimes entry pairs with nothing", async () => { + const driver = new FakeDriver({ + availableOsVersions: ["26.5"], + clock: new FakeClock(), + platform: "ios", + }); + vi.spyOn(driver, "listCatalog").mockResolvedValue({ + defaultRuntime: "26.5", + modelAliases: {}, + modelClasses: { constructor: "phone", "iPhone 15": "phone", "iPhone 16": "phone" } as const, + modelRuntimes: { "iPhone 16": ["26.5"] }, + models: ["constructor", "iPhone 15", "iPhone 16"], + runtimes: ["26.5"], + }); + const catalog = new DriverCatalog([driver], { + preferences: { ios: { phone: ["constructor", "iPhone 15", "iPhone 16"] } }, + }); + + const [entry] = await catalog.listCatalog(); + + // Inherited `Object.prototype.constructor` has a length; a read of it would count as paired. + expect(entry?.classDefaults).toEqual({ phone: "iPhone 16" }); + }); + + it("has no entry for a class that has no preference list", async () => { + const driver = new FakeDriver({ + availableOsVersions: ["26.5"], + clock: new FakeClock(), + knownModels: ["iPhone 16"], + modelClasses: { "iPhone 16": "phone" }, + platform: "ios", + }); + + const [entry] = await new DriverCatalog([driver]).listCatalog(); + + expect(entry?.classDefaults).toEqual({}); + }); + }); }); diff --git a/src/core/driver-catalog.ts b/src/core/driver-catalog.ts index 9617d7502..72cd70f5f 100644 --- a/src/core/driver-catalog.ts +++ b/src/core/driver-catalog.ts @@ -1,5 +1,6 @@ import { type Logger, NoopLogger } from "../ports/index.js"; -import type { DeviceSpec, Platform } from "./domain.js"; +import { findCatalogModel } from "./catalog-match.js"; +import { DEVICE_CLASSES, type DeviceClass, type DeviceSpec, type Platform } from "./domain.js"; import type { DeviceRequest, Driver, @@ -25,18 +26,36 @@ export class UnknownPassthroughToolError extends Error { } } +/** + * The model names to try for each class, per platform, most preferred first: the operator's own + * list followed by the driver's built-in one (ADR 0015 §4). Built once, by the composition root. + */ +export type ModelPreferences = Readonly< + Partial>>>> +>; + /** One registered driver's catalog entry, tagged with its platform. */ export interface PlatformCatalog extends DriverCatalogEntry { readonly platform: Platform; + /** ADR 0015 §4: the model Simlock would create for each class on this host. */ + readonly classDefaults: Readonly>>; } /** Immutable platform-to-driver lookup used by the lease path. */ export class DriverCatalog { readonly #drivers: ReadonlyMap; readonly #logger: Logger; + readonly #preferences: ModelPreferences; - constructor(drivers: readonly Driver[], options: { readonly logger?: Logger | undefined } = {}) { + constructor( + drivers: readonly Driver[], + options: { + readonly logger?: Logger | undefined; + readonly preferences?: ModelPreferences | undefined; + } = {}, + ) { this.#drivers = new Map(drivers.map((driver) => [driver.platform, driver])); + this.#preferences = options.preferences ?? {}; this.#logger = options.logger?.child("driver-catalog") ?? new NoopLogger(); } @@ -87,7 +106,12 @@ export class DriverCatalog { const listed = await Promise.all( this.select(platform).map(async (driver): Promise => { try { - return { platform: driver.platform, ...(await driver.listCatalog()) }; + const entry = await driver.listCatalog(); + return { + platform: driver.platform, + ...entry, + classDefaults: this.#classDefaults(driver.platform, entry), + }; } catch (error: unknown) { if (platform !== undefined) throw error; this.#logger.warn("A driver could not read its catalog", { @@ -101,6 +125,28 @@ export class DriverCatalog { return listed.filter((entry) => entry !== undefined); } + /** + * For each class, the model Simlock would create on this host (ADR 0015 §4): of the names on + * the class's preference list that the entry lists and that are of that class, the first that + * pairs with an installed runtime, else the first of them. A class in which no name counts has + * no entry. + */ + #classDefaults( + platform: Platform, + entry: DriverCatalogEntry, + ): Partial> { + const defaults: Partial> = {}; + for (const deviceClass of DEVICE_CLASSES) { + const counted = (this.#preferences[platform]?.[deviceClass] ?? []).flatMap((name) => { + const model = findCatalogModel(entry, name); + return model !== undefined && classOf(entry, model) === deviceClass ? [model] : []; + }); + const chosen = counted.find((model) => pairedRuntimes(entry, model).length > 0) ?? counted[0]; + if (chosen !== undefined) defaults[deviceClass] = chosen; + } + return defaults; + } + /** * 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. @@ -111,3 +157,13 @@ export class DriverCatalog { return driver === undefined ? [] : [driver]; } } + +/** A model's class; an inherited property of a name like `constructor` is never a class string. */ +function classOf(entry: DriverCatalogEntry, model: string): DeviceClass | undefined { + return entry.modelClasses[model]; +} + +/** The installed runtimes a model pairs with, reading own keys only. */ +function pairedRuntimes(entry: DriverCatalogEntry, model: string): readonly string[] { + return (Object.hasOwn(entry.modelRuntimes, model) ? entry.modelRuntimes[model] : undefined) ?? []; +} diff --git a/src/core/driver.ts b/src/core/driver.ts index 333b5c428..62f970944 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -221,6 +221,12 @@ export interface DriverToolVersion { export interface Driver { readonly platform: Platform; + /** + * ADR 0015 §4: the model names this driver's platform offers for each class, newest first. + * The core merges it behind the operator's own list and holds no model name itself; a class + * with no list has no entry. + */ + readonly defaultModels: Readonly>>; /** * Absolute path of the root this driver owns and scopes every platform command to. * Membership in it is what proves a device is Simlock's; the core carries the string diff --git a/src/core/fake-driver.test.ts b/src/core/fake-driver.test.ts index 28845784b..a6c03c569 100644 --- a/src/core/fake-driver.test.ts +++ b/src/core/fake-driver.test.ts @@ -203,6 +203,15 @@ describe("FakeDriver", () => { expect((await new FakeDriver(options).listCatalog()).modelClasses).toEqual({}); }); + it("reports the built-in preference lists its options name, and none without them", () => { + const options = { clock: new FakeClock(), platform: "ios" as const }; + + expect( + new FakeDriver({ ...options, defaultModels: { phone: ["iPhone 17"] } }).defaultModels, + ).toEqual({ phone: ["iPhone 17"] }); + expect(new FakeDriver(options).defaultModels).toEqual({}); + }); + it("reports the custom models its options name, and no customModels field without them", async () => { const options = { availableOsVersions: ["35"], diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index a195c73c1..68c1f9246 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -91,6 +91,8 @@ export interface FakeDriverOptions { readonly modelRuntimes?: Readonly>; /** What `listCatalog` reports as other names per model; none unless a test says otherwise. */ readonly modelAliases?: Readonly>; + /** The built-in preference lists the driver carries, per class; none unless a test says otherwise. */ + readonly defaultModels?: Readonly>>; /** What `listCatalog` reports as each model's class; empty unless a test says otherwise. */ readonly modelClasses?: Readonly>; /** @@ -137,6 +139,7 @@ export class FakeDriverUnknownDeviceError extends Error { export class FakeDriver implements Driver { readonly platform: Platform; + readonly #defaultModels: FakeDriverOptions["defaultModels"]; readonly deviceRoot: string; readonly #availableOsVersions: Set; /** One receipt per installed version; an install replaces it with a new one. */ @@ -197,6 +200,7 @@ export class FakeDriver implements Driver { this.#modelRuntimes = options.modelRuntimes; this.#modelAliases = options.modelAliases; this.#modelClasses = options.modelClasses; + this.#defaultModels = options.defaultModels; this.#images = options.images; this.#customModels = options.customModels; this.#latencyMs = options.latencyMs; @@ -220,6 +224,10 @@ export class FakeDriver implements Driver { return this.#calls.map((call) => ({ ...call, arguments: [...call.arguments] })); } + get defaultModels(): Readonly>> { + return this.#defaultModels ?? {}; + } + /** * Succeeds unless a test fails it through `failOn`. A real driver re-runs the filesystem * checks here; the fake only has to be refusable, since what `Doctor` does with a refusal diff --git a/src/core/index.ts b/src/core/index.ts index 31e127366..867d2ce44 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -11,6 +11,7 @@ export { redactConfig, } from "./config.js"; export { + DEVICE_CLASSES, type DeviceClass, type DeviceMode, type DeviceRecord, @@ -62,7 +63,11 @@ export { UnknownModelError, UnsupportedRequestOptionError, } from "./driver.js"; -export { DriverCatalog, UnknownPassthroughToolError } from "./driver-catalog.js"; +export { + DriverCatalog, + type ModelPreferences, + UnknownPassthroughToolError, +} from "./driver-catalog.js"; // fallow-ignore-next-line unused-type -- wire-visible rejection vocabulary for Simlock's own adb server. export type { AdbServerRejectionReason, DriverRejectionReason } from "./driver.js"; export { Doctor, isStalledTransition, type StallInput } from "./doctor.js"; diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 63ffbf329..aafc0f377 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -58,8 +58,11 @@ function config(maxDevices = 1, maxRunning = 1): Config { downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, eventBuffer: { capacity: 100 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, health: { enabled: true, maxConcurrentRecoveries: 1, diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 5013384e8..b2b3fc981 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -45,8 +45,11 @@ function config(overrides: Partial = {}): Config { downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, eventBuffer: { capacity: 100 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, health: { enabled: true, maxConcurrentRecoveries: 1, diff --git a/src/core/lease-engine.ts b/src/core/lease-engine.ts index 0bc303323..7a66414cb 100644 --- a/src/core/lease-engine.ts +++ b/src/core/lease-engine.ts @@ -16,7 +16,7 @@ import type { Platform, } from "./domain.js"; import type { DeviceRequest, Driver, PassthroughCommand, PassthroughContext } from "./driver.js"; -import { DriverCatalog, type PlatformCatalog } from "./driver-catalog.js"; +import { DriverCatalog, type ModelPreferences, type PlatformCatalog } from "./driver-catalog.js"; import { LeaseAcquisitionCoordinator, type LeaseGrant, @@ -75,6 +75,11 @@ export interface LeaseEngineOptions { * (ADR 0007 §2). Omitted, or silent on a platform, means `"full"`. */ readonly defaultModes?: Readonly>>; + /** + * ADR 0015 §4: the model names to try for each class, per platform, operator's list first. + * Absent means none, so the catalog names no class default. + */ + readonly modelPreferences?: ModelPreferences; } export { @@ -127,7 +132,10 @@ export class LeaseEngine { ); this.claimReader = this.#claims; this.#planner = new AcquisitionPlanner(this.#capacity, this.#claims); - this.#drivers = new DriverCatalog(options.drivers, { logger: options.logger }); + this.#drivers = new DriverCatalog(options.drivers, { + logger: options.logger, + preferences: options.modelPreferences, + }); this.#deviceLifecycle = new ManagedDeviceLifecycle( this.#drivers, options.registry, diff --git a/src/core/lease-health-monitor.test.ts b/src/core/lease-health-monitor.test.ts index a30c2dba3..a0009e786 100644 --- a/src/core/lease-health-monitor.test.ts +++ b/src/core/lease-health-monitor.test.ts @@ -69,8 +69,11 @@ function config(overrides: Partial = {}): Config { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, }; } diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index da1aad3d7..7eb6b6aa3 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -178,8 +178,11 @@ function config(): Config { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, idle: { deleteAfterMs: 10, shutdownAfterMs: 5 }, lease: { defaultTtlMs: 60_000, diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index dcfaca5ec..11457ef92 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -74,8 +74,11 @@ function config(): Config { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, idle: { deleteAfterMs: 30_000, shutdownAfterMs: 10_000 }, lease: { defaultTtlMs: 100, diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index 686728b7f..6f72d81a6 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -48,8 +48,11 @@ const config: Config = { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, warmPool: { quarantine: { diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 43123b854..9e469c9ea 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -18,8 +18,8 @@ describe("daemon protocol", () => { // lets a lease request choose it, taking it to 8, each the same way. ADR 0010 adds // `component.install` and its `component-progress` push, which a gateway relays to its // workers, taking it to 9. ADR 0014 gives every event envelope an `id`, taking it to 10. ADR 0009 §7 makes `atRamBudget` a - // required field of each platform's `status.get` capacity, taking it to 11, then ADR 0015 §3 made `modelClasses` a required field of each platform catalog, taking it to 12. - expect(DAEMON_PROTOCOL_VERSION).toBe(12); + // required field of each platform's `status.get` capacity, taking it to 11, then ADR 0015 §3 made `modelClasses` a required field of each platform catalog, taking it to 12, then ADR 0015 §4 made `classDefaults` a required field of each platform catalog too, taking it to 13. + expect(DAEMON_PROTOCOL_VERSION).toBe(13); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index e723dfbcd..dfebe1da9 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -552,6 +552,7 @@ describe("Dispatcher: the fleet operations on a worker", () => { { defaultRuntime: "26.5", modelAliases: {}, + classDefaults: {}, modelClasses: {}, models: [], modelRuntimes: {}, @@ -2919,8 +2920,11 @@ function testConfig( stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: downloadsPolicy, acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, lease: { defaultTtlMs: 60_000, diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 06a651ae6..5f6b5b5e1 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -30,6 +30,7 @@ import { } from "../ports/index.js"; import { deviceModeWiring, + modelPreferenceWiring, discoverDrivers, emitSlimDiagnostic, processRunnerFor, @@ -1196,7 +1197,11 @@ describe("deviceModeWiring", () => { it.each(["slim", "full"] as const)( "maps ios.defaultMode %s to the default-mode map and to whether the iOS default is slim", (defaultMode) => { - expect(deviceModeWiring({ ios: { defaultMode, slim: { bootTimeoutMs: 1 } } })).toEqual({ + expect( + deviceModeWiring({ + ios: { defaultMode, defaultModels: {}, slim: { bootTimeoutMs: 1 } }, + }), + ).toEqual({ defaultModes: { ios: defaultMode }, slimByDefault: defaultMode === "slim", }); @@ -1204,6 +1209,53 @@ describe("deviceModeWiring", () => { ); }); +describe("modelPreferenceWiring", () => { + const drivers = [ + { + defaultModels: { phone: ["iPhone 17", "iPhone 16"], tablet: ["iPad (A16)"] }, + platform: "ios" as const, + }, + { defaultModels: { phone: ["Pixel 9"] }, platform: "android" as const }, + ]; + const config = ( + ios: Config["ios"]["defaultModels"], + android: Config["android"]["defaultModels"], + ) => + ({ + android: { defaultModels: android }, + ios: { defaultModels: ios }, + }) as Pick; + + it("puts the configured names of a class before the driver's built-in ones", () => { + expect( + modelPreferenceWiring( + config({ phone: ["iPhone 15", "iPhone 14"] }, { phone: ["Pixel 7"] }), + drivers, + ), + ).toEqual({ + android: { phone: ["Pixel 7", "Pixel 9"] }, + ios: { phone: ["iPhone 15", "iPhone 14", "iPhone 17", "iPhone 16"], tablet: ["iPad (A16)"] }, + }); + }); + + it("is the driver's built-in list alone for a class the config does not name", () => { + expect(modelPreferenceWiring(config({}, {}), drivers)).toEqual({ + android: { phone: ["Pixel 9"] }, + ios: { phone: ["iPhone 17", "iPhone 16"], tablet: ["iPad (A16)"] }, + }); + }); + + it("keeps a configured class the driver has no built-in list for", () => { + expect( + modelPreferenceWiring(config({ vision: ["Apple Vision Pro"] }, {}), drivers).ios?.vision, + ).toEqual(["Apple Vision Pro"]); + }); + + it("leaves out a platform with no driver", () => { + expect(modelPreferenceWiring(config({}, {}), [drivers[0]!])).not.toHaveProperty("android"); + }); +}); + describe("slim diagnostic bridging", () => { it("emits device.slimmed with the driver-diagnostics module for a SlimmedFact", () => { const clock = new FakeClock(1_000); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 022aa9318..428e11fb6 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -7,12 +7,15 @@ import { fitHostFacts } from "../contract/index.js"; import { type Config, type ConfigOverrides, + type DeviceClass, type DeviceMode, type Driver, type DriverRejection, + type ModelPreferences, type PrerequisiteCheck, CleanupReaper, ComponentInstaller, + DEVICE_CLASSES, DiskSpaceGuard, DriverCatalog, Doctor, @@ -257,6 +260,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise): { }; } +/** + * The one place a class's preference list is merged (ADR 0015 §4): the operator's names from + * `ios.defaultModels` or `android.defaultModels` first, then the driver's built-in ones, per + * platform that has a driver. The catalog reads the result; nothing else builds the list. + */ +export function modelPreferenceWiring( + config: Pick, + drivers: readonly Pick[], +): ModelPreferences { + return Object.fromEntries( + drivers.map((driver) => { + const configured = + driver.platform === "ios" ? config.ios.defaultModels : config.android.defaultModels; + const merged: Partial> = {}; + for (const deviceClass of DEVICE_CLASSES) { + const names = [ + ...(configured[deviceClass] ?? []), + ...(driver.defaultModels[deviceClass] ?? []), + ]; + if (names.length > 0) merged[deviceClass] = names; + } + return [driver.platform, merged]; + }), + ); +} + /** * Turns the iOS driver's `SlimmedFact` into the matching `device.slimmed` bus event. The driver * never depends on the event bus directly (architecture rule 5) -- this is the one place, at driver construction, that bridges the diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 1713ed35c..066372faf 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -3252,8 +3252,11 @@ function testConfig( ...downloadsOverrides, }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, lease: { defaultTtlMs: 60_000, diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 99e12ac28..e5ad3748d 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -3674,6 +3674,32 @@ async function provisionedHarness( * paths are covered against the supervisor itself in `adb-server.test.ts`, and end to end * in this file's own `AndroidDriver.create` block. */ +describe("AndroidDriver defaultModels", () => { + it("lists the built-in Android preference list per class, newest first, with phone starting at Pixel 9", async () => { + const driver = await createDriver(await androidFilesystem(), new ScriptedProcessRunner([])); + + expect(driver.defaultModels).toEqual({ + auto: ["Automotive (1080p landscape)", "Automotive (1024p landscape)"], + desktop: ["Medium Desktop", "Large Desktop"], + phone: ["Pixel 9", "Pixel 8", "Pixel 7", "Pixel 6", "Medium Phone"], + tv: ["Television (1080p)", "Television (4K)"], + watch: ["Wear OS Large Round", "Wear OS Small Round"], + }); + }); + + it("has no Android list for tablet or vision", async () => { + const driver = await createDriver(await androidFilesystem(), new ScriptedProcessRunner([])); + + expect(Object.keys(driver.defaultModels).sort()).toEqual([ + "auto", + "desktop", + "phone", + "tv", + "watch", + ]); + }); +}); + describe("AndroidDriver toolVersions()", () => { it("reports emulator, platform-tools, and command-line tools revisions from each package's source.properties", async () => { const filesystem = await androidFilesystem(); diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index f32357c2b..691f7b6b8 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -1,6 +1,6 @@ import { dirname, isAbsolute, join } from "node:path"; -import type { DeviceSpec } from "../../core/domain.js"; +import type { DeviceClass, DeviceSpec } from "../../core/domain.js"; import { BootTimeoutError, type ComponentInstallProgress, @@ -253,6 +253,18 @@ interface SystemImage { */ export const ANDROID_PASSTHROUGH_TOOL = "adb"; +/** + * ADR 0015 §4: the models Simlock tries for each class on Android when the operator names none + * first, newest first. A profile is never `tablet` or `vision` on Android, so neither has a list. + */ +const ANDROID_DEFAULT_MODELS: Readonly>> = { + auto: ["Automotive (1080p landscape)", "Automotive (1024p landscape)"], + desktop: ["Medium Desktop", "Large Desktop"], + phone: ["Pixel 9", "Pixel 8", "Pixel 7", "Pixel 6", "Medium Phone"], + tv: ["Television (1080p)", "Television (4K)"], + watch: ["Wear OS Large Round", "Wear OS Small Round"], +}; + /** Every refusal ends the same way: the Simlock command that does it safely. */ const RECLAIM_INSTEAD = "Use `simlock release` (which reclaims the device for you) or `simlock cleanup` instead."; @@ -429,6 +441,7 @@ function containsSequence(args: readonly string[], sequence: readonly string[]): export class AndroidDriver implements Driver { readonly platform = "android" as const; + readonly defaultModels = ANDROID_DEFAULT_MODELS; readonly #adbServer: AdbServerSupervisor; readonly #adbServerPort: number; readonly #baseEnv: Readonly>; diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 358d7de9c..90c9f2db3 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -4296,6 +4296,42 @@ async function settledValue(promise: Promise): Promise { return state.value; } +describe("IosSimctlDriver defaultModels", () => { + it("lists the built-in iOS preference list per class, newest first, with phone starting at iPhone 17", async () => { + const driver = await createDriver(new ScriptedProcessRunner([])); + + expect(driver.defaultModels).toEqual({ + phone: ["iPhone 17", "iPhone 16", "iPhone 15", "iPhone 14", "iPhone 13"], + tablet: [ + "iPad Pro 11-inch (M5)", + "iPad Pro 11-inch (M4)", + "iPad Air 11-inch (M3)", + "iPad (A16)", + "iPad (10th generation)", + ], + tv: ["Apple TV 4K (3rd generation)", "Apple TV"], + vision: ["Apple Vision Pro"], + watch: [ + "Apple Watch Series 11 (46mm)", + "Apple Watch Series 10 (46mm)", + "Apple Watch Series 9 (45mm)", + ], + }); + }); + + it("has no iOS list for auto or desktop", async () => { + const driver = await createDriver(new ScriptedProcessRunner([])); + + expect(Object.keys(driver.defaultModels).sort()).toEqual([ + "phone", + "tablet", + "tv", + "vision", + "watch", + ]); + }); +}); + 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 6cafc2189..3d462cd2a 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -91,6 +91,28 @@ const MARK_FILE_NAME = "simlock-mark.json"; */ export const IOS_PASSTHROUGH_TOOL = "simctl"; +/** + * ADR 0015 §4: the models Simlock tries for each class on iOS when the operator names none + * first, newest first. `auto` and `desktop` have no iOS device type, so they have no list. + */ +const IOS_DEFAULT_MODELS: Readonly>> = { + phone: ["iPhone 17", "iPhone 16", "iPhone 15", "iPhone 14", "iPhone 13"], + tablet: [ + "iPad Pro 11-inch (M5)", + "iPad Pro 11-inch (M4)", + "iPad Air 11-inch (M3)", + "iPad (A16)", + "iPad (10th generation)", + ], + tv: ["Apple TV 4K (3rd generation)", "Apple TV"], + vision: ["Apple Vision Pro"], + watch: [ + "Apple Watch Series 11 (46mm)", + "Apple Watch Series 10 (46mm)", + "Apple Watch Series 9 (45mm)", + ], +}; + /** * Verbs `simlock simctl` will not proxy. Every one of them changes a device's lifecycle, * which the registry -- not `simctl` -- is the record of: a device created here has no @@ -321,6 +343,7 @@ type ProcessOutcome = /** iOS simulator implementation. Its simctl details remain opaque to the core. */ export class IosSimctlDriver implements Driver { readonly platform = "ios" as const; + readonly defaultModels = IOS_DEFAULT_MODELS; readonly #clock: Clock; readonly componentFootprint: { readonly path: string; readonly bytes: number }; readonly #filesystem: Filesystem; diff --git a/src/gateway/aggregate.test.ts b/src/gateway/aggregate.test.ts index 3f4c1bf06..f1e9ee754 100644 --- a/src/gateway/aggregate.test.ts +++ b/src/gateway/aggregate.test.ts @@ -332,6 +332,7 @@ describe("aggregateCatalog", () => { const iosOnA = { defaultRuntime: "26.0", modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, models: ["iPhone 17"], @@ -342,6 +343,7 @@ describe("aggregateCatalog", () => { const iosOnB = { defaultRuntime: "26.0", modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPad Pro": ["25.4", "26.0"], "iPhone 17": ["26.0"] }, models: ["iPhone 17", "iPad Pro"], @@ -401,6 +403,59 @@ describe("aggregateCatalog", () => { expect(catalog.platforms[0]?.modelClasses).toEqual({ "iPhone 17": "phone" }); }); + it("carries a class default only when every connected worker reports the same one", () => { + // Every default names a model its worker lists, so a disagreement reaches agreedClassDefaults. + const withDefaults = ( + classDefaults: Record, + base: typeof iosOnA | typeof iosOnB = iosOnA, + ) => ({ + ...base, + classDefaults, + models: [...new Set([...base.models, "iPad Pro", "iPad (A16)"])], + }); + + const agreed = aggregateCatalog([ + view({ catalog: [withDefaults({ phone: "iPhone 17", tablet: "iPad Pro" })], id: "wrk_a" }), + view({ + catalog: [withDefaults({ phone: "iPhone 17", tablet: "iPad (A16)" }, iosOnB)], + id: "wrk_b", + }), + ]); + + expect(agreed.platforms[0]?.classDefaults).toEqual({ phone: "iPhone 17" }); + expect(() => OPERATIONS["catalog.get"].output.parse(agreed)).not.toThrow(); + }); + + it("drops a class default when a connected worker has none for that class", () => { + const catalog = aggregateCatalog([ + view({ catalog: [{ ...iosOnA, classDefaults: { phone: "iPhone 17" } }], id: "wrk_a" }), + view({ catalog: [{ ...iosOnB, classDefaults: {} }], id: "wrk_b" }), + ]); + + expect(catalog.platforms[0]?.classDefaults).toEqual({}); + }); + + it("drops a class default naming a model the worker does not list", () => { + const catalog = aggregateCatalog([ + view({ catalog: [{ ...iosOnB, classDefaults: { phone: "Ghost" } }], id: "wrk_a" }), + ]); + + expect(catalog.platforms[0]?.classDefaults).toEqual({}); + }); + + it("keeps a class default a lone connected worker reports, and ignores a disconnected worker's", () => { + const catalog = aggregateCatalog([ + view({ catalog: [{ ...iosOnA, classDefaults: { phone: "iPhone 17" } }], id: "wrk_a" }), + view({ + catalog: [{ ...iosOnB, classDefaults: { phone: "iPhone 16" } }], + connection: "disconnected", + id: "wrk_b", + }), + ]); + + expect(catalog.platforms[0]?.classDefaults).toEqual({ phone: "iPhone 17" }); + }); + it("keeps a default runtime only when every worker agrees on it", () => { const agreed = aggregateCatalog([ view({ catalog: [iosOnA], id: "wrk_a" }), @@ -434,6 +489,7 @@ describe("aggregateCatalog", () => { it("pairs a model with a runtime when at least one connected worker pairs them", () => { const iosOnC = { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17": ["25.4"] }, models: ["iPhone 17"], @@ -465,6 +521,7 @@ describe("aggregateCatalog", () => { it("ignores the pairings of disconnected and incompatible workers", () => { const pairsOld = { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17": ["25.4"] }, models: ["iPhone 17"], @@ -483,6 +540,7 @@ describe("aggregateCatalog", () => { it("gives every model in the fleet catalog a modelRuntimes entry, empty when nothing pairs", () => { const unpaired = { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone XS": [] }, models: ["iPhone XS"], @@ -508,6 +566,7 @@ describe("aggregateCatalog", () => { platforms: [ { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: {}, models: ["constructor"], @@ -525,6 +584,7 @@ describe("aggregateCatalog", () => { it("drops a pairing with a runtime the worker does not list itself, even when another worker has it", () => { const claimsMore = { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17": ["25.4", "26.0"] }, models: ["iPhone 17"], @@ -548,6 +608,7 @@ describe("aggregateCatalog", () => { iosOnA, { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "Pixel 9": ["35"] }, models: ["Pixel 9"], @@ -572,6 +633,7 @@ describe("aggregateCatalog", () => { images: { runtime: string; tag: string; abi: string }[]; runtimes: string[]; customModels: string[]; + classDefaults: {}; modelClasses: Record; }>, ) => { @@ -581,6 +643,7 @@ describe("aggregateCatalog", () => { ...(overrides.customModels === undefined ? {} : { customModels: overrides.customModels }), ...(overrides.images === undefined ? {} : { images: overrides.images }), modelAliases: overrides.modelAliases ?? {}, + classDefaults: {}, modelClasses: overrides.modelClasses ?? {}, modelRuntimes: Object.fromEntries(models.map((model) => [model, runtimes])), models, @@ -701,6 +764,7 @@ describe("aggregateCatalog", () => { "Pixel 8": names(prefix, 32), }, customModels: ["Pixel 8", ...names(`${prefix}m`, 4095)], + classDefaults: {}, modelClasses: Object.fromEntries( ["Pixel 8", ...names(`${prefix}m`, 4095)].map((model) => [model, "phone" as const]), ), @@ -737,6 +801,7 @@ describe("aggregateCatalog", () => { Array.from({ length: 4096 }, (_, index) => `${prefix}${index}`); const worker = (prefix: string) => androidOn({ + classDefaults: {}, modelClasses: Object.fromEntries(names(prefix).map((model) => [model, "phone" as const])), models: names(prefix), }); diff --git a/src/gateway/aggregate.ts b/src/gateway/aggregate.ts index ed6c783b9..d73c61dcd 100644 --- a/src/gateway/aggregate.ts +++ b/src/gateway/aggregate.ts @@ -7,6 +7,7 @@ import type { z } from "zod"; import { CATALOG_LIST_LIMITS, + deviceClassSchema, INSTALL_LIST_LIMIT, OPERATIONS, type DeviceClass, @@ -226,6 +227,8 @@ interface CatalogBucket { /** Models any worker that lists them marks custom. */ readonly customModels: Set; readonly defaults: Set; + /** Each worker's own `classDefaults`, so a class a worker has none for is seen as disagreement. */ + readonly classDefaults: Partial>[]; } function indexCatalogs( @@ -253,6 +256,7 @@ function addCatalogEntry( workerId: string, ): void { const bucket = byPlatform.get(entry.platform) ?? { + classDefaults: [], customModels: new Set(), defaults: new Set(), images: undefined, @@ -271,6 +275,20 @@ function addCatalogEntry( addCustomModels(bucket.customModels, entry); if (entry.images !== undefined) bucket.images = addImages(bucket.images, entry, entry.images); bucket.defaults.add(entry.defaultRuntime); + bucket.classDefaults.push(listedClassDefaults(entry)); +} + +/** + * A worker's class defaults with any naming a model the worker does not list itself dropped, so + * the fleet never shows a default nobody can lease; a dropped class counts as the worker having none. + */ +function listedClassDefaults(entry: PlatformCatalog): Partial> { + const listed: Partial> = {}; + for (const deviceClass of deviceClassSchema.options) { + const model = entry.classDefaults[deviceClass]; + if (model !== undefined && entry.models.includes(model)) listed[deviceClass] = model; + } + return listed; } /** Folds one worker's other names for `model` into the fleet's, once per spelling ignoring case. */ @@ -332,10 +350,27 @@ function addPairings(index: Map>, entry: PlatformCatalog, mo index.set(model, paired); } +/** + * A class's default is kept when every worker reports the same model for it, as `defaultRuntime` + * is; a worker with no entry for the class counts as disagreeing. + */ +function agreedClassDefaults( + workers: readonly Partial>[], +): Partial> { + const agreed: Partial> = {}; + for (const deviceClass of deviceClassSchema.options) { + const reported = new Set(workers.map((worker) => worker[deviceClass])); + const [only] = reported; + if (reported.size === 1 && only !== undefined) agreed[deviceClass] = only; + } + return agreed; +} + function renderPlatform(platform: Platform, bucket: CatalogBucket): PlatformCatalog { const agreedDefault = bucket.defaults.size === 1 ? [...bucket.defaults][0] : undefined; const runtimes = [...bucket.runtimes.keys()].sort(); return { + classDefaults: agreedClassDefaults(bucket.classDefaults), ...(bucket.customModels.size === 0 ? {} : { diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 8174be08e..16615bb94 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -49,8 +49,11 @@ const gatewayConfig = { }, http: { enabled: true, host: "127.0.0.1", port: 4700 }, idle: { deleteAfterMs: 1, shutdownAfterMs: 1 }, - ios: { defaultMode: "full" as const, slim: { bootTimeoutMs: 1 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full" as const, defaultModels: {}, slim: { bootTimeoutMs: 1 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, lease: { defaultTtlMs: 900_000, maxTtlMs: 3_600_000, @@ -347,6 +350,7 @@ describe("GatewayDispatcher", () => { catalog: [ { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, models: ["iPhone 17"], diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index 9322b8d8e..268de34c4 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -104,15 +104,21 @@ export function deviceFixture( /** * A worker's catalog. An entry without `modelRuntimes` pairs each of its models with every one of * its runtimes -- a single worker's answer, so this is never the fleet cross product. An entry - * without `modelAliases` lists no other names, and one without `modelClasses` classes no model. + * without `modelAliases` lists no other names, one without `modelClasses` classes no model, and one without `classDefaults` has no class default. */ export function catalogFixture( - entries: readonly (Omit & - Partial>)[], + entries: readonly (Omit< + PlatformCatalog, + "modelRuntimes" | "modelAliases" | "modelClasses" | "classDefaults" + > & + Partial< + Pick + >)[], ): CatalogOutput { return { platforms: entries.map((entry) => ({ ...entry, + classDefaults: entry.classDefaults ?? {}, modelAliases: entry.modelAliases ?? {}, modelClasses: entry.modelClasses ?? {}, modelRuntimes: diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index f45ec62d4..c61205cd6 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -120,6 +120,7 @@ describe("WorkerRegistry", () => { catalog: [ { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, models: ["iPhone 17"], @@ -134,6 +135,7 @@ describe("WorkerRegistry", () => { expect(workers.view("wrk_1")?.catalog).toEqual([ { modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, models: ["iPhone 17"], diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index a83e59f2a..3e347f781 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -55,8 +55,11 @@ export function testConfig( }, http: { enabled: true, host: "127.0.0.1", port: 4700 }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, - ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, - android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, + ios: { defaultMode: "full", defaultModels: {}, slim: { bootTimeoutMs: 600_000 } }, + android: { + defaultModels: {}, + emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true }, + }, lease: { defaultTtlMs: 900_000, maxTtlMs: 14_400_000, diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 903fba8cb..6b759b33e 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -25,6 +25,7 @@ describe("MCP server (smoke)", () => { { defaultRuntime: "26.5", modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17 Pro": ["26.5"] }, models: ["iPhone 17 Pro"], @@ -86,6 +87,7 @@ describe("MCP server (smoke)", () => { { defaultRuntime: "26.5", modelAliases: {}, + classDefaults: {}, modelClasses: {}, modelRuntimes: { "iPhone 17 Pro": ["26.5"] }, models: ["iPhone 17 Pro"], diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 93896d404..0e433bb64 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -144,7 +144,7 @@ export function createMcpServer(session: McpSession): McpServer { { title: "List devices", description: - "List resolvable device models and installed runtimes per available platform, marking each platform's default runtime (the newest installed). modelRuntimes gives, for each model, the installed runtimes it pairs with; pick a model and os from it, since a listed model and a listed runtime do not always pair. modelAliases gives other names a model answers to (on Android, the device profile id); modelClasses gives the class of each model whose tooling reports one (phone, tablet, watch, tv, vision, auto or desktop); images lists Android's installed system images with API level, tag, and ABI. Read-only: never downloads a runtime or system image. Call this once to pick a valid device/os combination before lease_simulator, instead of guessing.", + "List resolvable device models and installed runtimes per available platform, marking each platform's default runtime (the newest installed). modelRuntimes gives, for each model, the installed runtimes it pairs with; pick a model and os from it, since a listed model and a listed runtime do not always pair. modelAliases gives other names a model answers to (on Android, the device profile id); modelClasses gives the class of each model whose tooling reports one (phone, tablet, watch, tv, vision, auto or desktop); classDefaults gives, per class, the model Simlock would create for it on this host; images lists Android's installed system images with API level, tag, and ABI. Read-only: never downloads a runtime or system image. Call this once to pick a valid device/os combination before lease_simulator, instead of guessing.", inputSchema: listDevicesInputSchema, outputSchema: listDevicesOutputSchema, },