diff --git a/docs/CLI.md b/docs/CLI.md index 9be1b8065..0c0f9f203 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -912,7 +912,8 @@ why its Android catalog looks thin, trimmed to one worker: "runtimes": ["18.4", "26.0"], "defaultRuntime": "26.0", "modelRuntimes": {"iPhone 16": ["18.4"]}, - "modelAliases": {} + "modelAliases": {}, + "modelClasses": {"iPhone 16": "phone"} }, { "platform": "android", @@ -921,6 +922,7 @@ why its Android catalog looks thin, trimmed to one worker: "defaultRuntime": "18.0", "modelRuntimes": {}, "modelAliases": {}, + "modelClasses": {}, "images": [{"runtime": "18.0", "tag": "google_apis", "abi": "arm64-v8a"}] } ], @@ -1242,6 +1244,16 @@ level (`runtime`), tag, and ABI. An image whose ABI the host cannot run natively is listed too, with its ABI. A tag listed here is what `simlock lease --image-tag` accepts. +`modelClasses` gives, for a model, its class: `phone`, `tablet`, `watch`, +`tv`, `vision`, `auto` or `desktop`. On iOS the class comes from the device +type's product family: iPhone is `phone`, iPad is `tablet`, Apple Watch is +`watch`, Apple TV is `tv` and Apple Vision is `vision`. On Android it comes +from the device profile's tag: `android-tv` is `tv`, `android-wear` is +`watch`, an `android-automotive` tag is `auto` and `android-desktop` is +`desktop`; a profile with no tag, and a custom profile, is `phone`. A model +whose tools report no class, or one this list does not name, is still +listed and still leasable; it has no entry in `modelClasses`. + `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 @@ -1256,16 +1268,19 @@ same way, unless `--platform` names it: then the command fails with that error. downloads a runtime or system image, and lists only what is installed, whatever `downloads.policy` says. -Human-oriented by default, one line per model with the runtimes it pairs -with, its other names on the line below it, and then each image: +Human-oriented by default, the models grouped under a line per class (in the +order `phone`, `tablet`, `watch`, `tv`, `vision`, `auto`, `desktop`, then +`(no class)` for a model with none), 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: - My Tablet (custom): 34, 35 - Pixel 8: 34, 35 - Other names: pixel_8 + phone: + My Tablet (custom): 34, 35 + Pixel 8: 34, 35 + Other names: pixel_8 Images (runtime, tag, ABI): 34 default x86_64 35 google_apis arm64-v8a @@ -1277,12 +1292,15 @@ Platform: android {"platforms":[{"platform":"android","models":["My Tablet","Pixel 8"],"runtimes":["34","35"],"defaultRuntime":"35", "modelRuntimes":{"My Tablet":["34","35"],"Pixel 8":["34","35"]}, "modelAliases":{"Pixel 8":["pixel_8"]}, + "modelClasses":{"My Tablet":"phone","Pixel 8":"phone"}, "customModels":["My Tablet"], "images":[{"runtime":"34","tag":"default","abi":"x86_64"},{"runtime":"35","tag":"google_apis","abi":"arm64-v8a"}]}]} ``` Against a gateway, `modelAliases` is the union of each worker's other names -for a model, and `images` the union of their images. A model is in +for a model, `modelClasses` the union of their classes (when two workers class +a model differently, the first worker in id order wins), and `images` the union +of their images. 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 0637ddf6e..92a425f75 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -242,7 +242,8 @@ const { platforms } = await client.getCatalog({ platform: "ios" }); // runtimes: ["18.4", "26.0"], // defaultRuntime: "26.0", // modelRuntimes: { "iPhone 16": ["18.4", "26.0"], "iPhone XS": ["18.4"] }, -// modelAliases: {} }] +// modelAliases: {}, +// modelClasses: { "iPhone 16": "phone", "iPhone XS": "phone" } }] ``` - `models` and `runtimes` are what is installed. A model and a runtime that @@ -255,6 +256,11 @@ const { platforms } = await client.getCatalog({ platform: "ios" }); it, in any letter case. Only models with another name appear. On Android a built-in profile's AVD id is one (`{ "Pixel 8": ["pixel_8"] }`); iOS has none. +- `modelClasses` maps a model to its class: `phone`, `tablet`, `watch`, `tv`, + `vision`, `auto` or `desktop`. On iOS it comes from the device type's + product family, on Android from the profile's tag, and a custom Android + profile is a `phone`. A model whose tools report no class, or one this list + does not name, has no entry; it is still listed and still leasable. - `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. @@ -274,8 +280,9 @@ Against a gateway the catalog is the union of the connected workers'. A model is paired with a runtime when at least one worker pairs them, and `modelWorkers` and `runtimeWorkers` say which workers have each model 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. A model is in `customModels` when any worker that lists it +with the runtime. `modelAliases`, `modelClasses` and `images` are the unions +of each worker's own; when two workers class a model differently, the first +worker in id order wins. 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/HTTP-API.md b/docs/HTTP-API.md index 255629965..3305ba839 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -278,6 +278,15 @@ for that platform has an `images` field. A gateway accepts any name a worker lists for a model, in any letter case, and sends that worker its own name for it. +Each entry also carries `modelClasses`: for a name in `models` whose tooling +reports one, its class, one of `phone`, `tablet`, `watch`, `tv`, `vision`, +`auto` or `desktop`. On iOS it comes from the device type's product family, +on Android from the device profile's tag, and a custom Android profile is a +`phone`. A model whose tools report no class, or one this API does not name, +is still listed and still leasable, and has no entry. On a gateway it is the +union over the connected workers; when two workers class a model differently, +the first worker in id order wins. + 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 @@ -294,7 +303,8 @@ that lists it marks it custom; each worker's own list is in its catalog in "runtimes": ["18.4", "26.0"], "defaultRuntime": "26.0", "modelRuntimes": { "iPhone 16": ["18.4", "26.0"], "iPhone XS": ["18.4"] }, - "modelAliases": {} + "modelAliases": {}, + "modelClasses": { "iPhone 16": "phone", "iPhone XS": "phone" } }, { "platform": "android", "models": ["My Tablet", "Pixel 8"], @@ -302,6 +312,7 @@ that lists it marks it custom; each worker's own list is in its catalog in "defaultRuntime": "35", "modelRuntimes": { "My Tablet": ["34", "35"], "Pixel 8": ["34", "35"] }, "modelAliases": { "Pixel 8": ["pixel_8"] }, + "modelClasses": { "My Tablet": "phone", "Pixel 8": "phone" }, "customModels": ["My Tablet"], "images": [ { "runtime": "34", "tag": "default", "abi": "x86_64" }, { "runtime": "35", "tag": "google_apis", "abi": "arm64-v8a" } ] @@ -1053,7 +1064,8 @@ simulated (hence the thin Android catalog), trimmed to one worker: "runtimes": ["18.4", "26.0"], "defaultRuntime": "26.0", "modelRuntimes": {"iPhone 16": ["18.4"]}, - "modelAliases": {} + "modelAliases": {}, + "modelClasses": {"iPhone 16": "phone"} }, { "platform": "android", @@ -1062,6 +1074,7 @@ simulated (hence the thin Android catalog), trimmed to one worker: "defaultRuntime": "18.0", "modelRuntimes": {}, "modelAliases": {}, + "modelClasses": {}, "images": [{"runtime": "18.0", "tag": "google_apis", "abi": "arm64-v8a"}] } ], diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index b8dca50d2..a49864e87 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -191,8 +191,10 @@ agent / console ──token auth──> │ HTTP frontend + unix socket array of views and `daemon.mode: "gateway"`. `catalog.get` is the union of the connected workers' catalogs, each model and runtime annotated with the workers that have it, `modelRuntimes` per model the union of each - worker's own pairings, `modelAliases` the union per model, and `images` - the union by runtime, tag, and ABI (ADR 0008 §4). Worker events are republished on the gateway's bus + worker's own pairings, `modelAliases` the union per model, `modelClasses` + the union with the first worker in id order winning a model two classify + differently (ADR 0015 §3), and `images` the union by runtime, tag, and ABI + (ADR 0008 §4). Worker events are republished on the gateway's bus with `workerId` added, so `simlock events --follow` against a gateway shows the fleet. - **What a gateway does not do.** It starts no drivers, validates no device @@ -267,8 +269,9 @@ gateway's `worker.install-component` (ADR 0010 §7) 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. So the range both -sides advertise is `{min: 11, max: 11}`, an older client and a current daemon simply +required capacity field, taking it to 11, and ADR 0015 §3 makes the catalog's +`modelClasses` required, taking it to 12. So the range both +sides advertise is `{min: 12, max: 12}`, 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` @@ -829,7 +832,9 @@ annotated with the workers that have it. A model's `modelRuntimes` is the union of what each connected worker pairs it with, never the cross product 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, and `images` the union by runtime, tag, +model, deduplicated ignoring case, `modelClasses` the union per model with +the first worker in id order winning a disagreement (a class a worker gives a +name it does not list is dropped), 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 @@ -852,7 +857,12 @@ back to that profile. A listed model is in `customModels` when the profile the matcher sends its name to is a `devices.xml` one (parsed by Simlock, or listed by `avdmanager` with `OEM : User`), so the mark and the resolution cannot disagree. The iOS driver matches a device type's name -only. `DriverCatalog.listCatalog` leaves out and logs a driver whose catalog +only. Each driver also classes the models it lists (ADR 0015 §3): the iOS driver +from the device type's `productFamily`, the Android driver from the profile's +`Tag :` line (a `devices.xml` profile is a phone), each in one table inside its +own module; the core and the contract carry the class names and read nothing +from them, and a family or tag a table does not know lists no class and stays +leasable. `DriverCatalog.listCatalog` leaves out and logs a driver whose catalog rejects when no platform is named, and fails with that driver's error when its platform is named. @@ -903,7 +913,8 @@ emits its own facts — `worker.connected`, `worker.disconnected`, `{min: 8, max: 8}`, because a lease request chooses it, and ADR 0010 to `{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; a + ADR 0009 to `{min: 11, max: 11}`, because `atRamBudget` is required, and + ADR 0015 to `{min: 12, max: 12}`, because `modelClasses` is required; 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 5be4c1c26..7527e8ec5 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -471,6 +471,7 @@ export class OutOfProcessFakeDriver implements Driver { ...(script.images === undefined ? {} : { images: [...script.images] }), ...(script.customModels === undefined ? {} : { customModels: [...script.customModels] }), modelAliases: { ...script.modelAliases }, + modelClasses: { ...script.modelClasses }, modelRuntimes: Object.fromEntries( models.map((model) => [model, [...(script.modelRuntimes?.[model] ?? runtimes)]]), ), diff --git a/e2e/fake-driver/types.ts b/e2e/fake-driver/types.ts index 68f6f3624..de3d3c734 100644 --- a/e2e/fake-driver/types.ts +++ b/e2e/fake-driver/types.ts @@ -7,6 +7,15 @@ export type FakeDriverPlatform = "ios" | "android"; +export type FakeDriverDeviceClass = + | "phone" + | "tablet" + | "watch" + | "tv" + | "vision" + | "auto" + | "desktop"; + export type FakeDriverOperation = | "resolveSpec" | "findComponent" @@ -78,6 +87,8 @@ export interface FakeDriverPlatformScript { readonly modelRuntimes?: Readonly>; /** What `listCatalog` reports as other names per model; none unless set. */ readonly modelAliases?: Readonly>; + /** What `listCatalog` reports as each model's class; none unless set. */ + readonly modelClasses?: Readonly>; /** What `listCatalog` reports as custom models; the field is absent unless set. */ readonly customModels?: readonly string[]; /** diff --git a/e2e/gateway-fleet.test.ts b/e2e/gateway-fleet.test.ts index dc1c8e658..34f1f938b 100644 --- a/e2e/gateway-fleet.test.ts +++ b/e2e/gateway-fleet.test.ts @@ -25,6 +25,7 @@ interface WorkerView { readonly modelRuntimes: Readonly>; readonly modelAliases: Readonly>; readonly customModels?: readonly string[]; + readonly modelClasses?: Readonly>; readonly images?: readonly { readonly runtime: string; readonly tag: string; @@ -430,6 +431,56 @@ describe("gateway fleet", () => { expect(human.stdout).toContain(" Pixel 8: 35"); }); + it("carries the union of the workers' model classes in the gateway catalog, and prints each model under its class", async () => { + const port = await freeLoopbackPort(); + const gateway = await withDaemon({ + configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + driver: "none", + }); + const minted = await gateway.cli(["token", "create", "--role", "worker"]); + const { secret } = minted.json as { secret: string }; + const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; + await withDaemon({ + configOverrides: { gateway: { ...uplink, label: "worker-a" } }, + driverScript: { + android: { + availableOsVersions: ["35"], + knownModels: ["Pixel 8"], + modelClasses: { "Pixel 8": "phone" }, + }, + }, + }); + await withDaemon({ + configOverrides: { gateway: { ...uplink, label: "worker-b" } }, + driverScript: { + android: { + availableOsVersions: ["35"], + knownModels: ["Television (1080p)", "Mystery"], + modelClasses: { "Television (1080p)": "tv" }, + }, + }, + }); + await waitForWorkers( + gateway, + (views) => + views.length === 2 && + views.every((view) => view.connection === "connected" && view.catalog.length > 0), + "both workers connected with their catalogs", + ); + + const catalog = await gateway.cli(["catalog", "--json"]); + expect(catalog.code).toBe(0); + const android = (catalog.json as { platforms: WorkerView["catalog"] }).platforms.find( + (entry) => entry.platform === "android", + ); + expect(android?.modelClasses).toEqual({ "Pixel 8": "phone", "Television (1080p)": "tv" }); + + const human = await gateway.cli(["catalog"]); + expect(human.stdout).toContain( + " phone:\n Pixel 8: 35\n tv:\n Television (1080p): 35\n (no class):\n Mystery: 35", + ); + }); + it("gives a request with a mode that mode on either worker, and a request with none the default of the worker it landed on", async () => { const port = await freeLoopbackPort(); const gateway = await withDaemon({ diff --git a/e2e/slow-android-smoke.test.ts b/e2e/slow-android-smoke.test.ts index 98d0894ec..bb0af9c6e 100644 --- a/e2e/slow-android-smoke.test.ts +++ b/e2e/slow-android-smoke.test.ts @@ -45,6 +45,7 @@ interface AndroidCatalogOutput { readonly models: readonly string[]; readonly runtimes: readonly string[]; readonly modelAliases: Readonly>; + readonly modelClasses: Readonly>; readonly images?: readonly { runtime: string; tag: string; abi: string }[]; }[]; } @@ -75,6 +76,12 @@ function avdIdFromCatalog(output: AndroidCatalogOutput): string { expect(existsSync(path), `listed image ${JSON.stringify(image)} is not installed`).toBe(true); } + // avdmanager's tag classes the models: a stock Pixel is a phone, the stock TV profile a tv. + if (android.models.includes("Pixel 8")) expect(android.modelClasses["Pixel 8"]).toBe("phone"); + if (android.models.includes("Television (1080p)")) { + expect(android.modelClasses["Television (1080p)"]).toBe("tv"); + } + const aliases = android.models.flatMap((name) => android.modelAliases[name] ?? []); expect( aliases.length, diff --git a/e2e/slow-ios-smoke.test.ts b/e2e/slow-ios-smoke.test.ts index 90f7ea24c..176b1f833 100644 --- a/e2e/slow-ios-smoke.test.ts +++ b/e2e/slow-ios-smoke.test.ts @@ -47,6 +47,18 @@ async function expectSimctlPassthrough(env: TestEnv, udid: string): Promise> } | undefined, +): void { + const classes = Object.entries(catalog?.modelClasses ?? {}); + expect(classes.length, "simlock catalog classed no iOS model").toBeGreaterThan(0); + for (const [name, deviceClass] of classes) { + if (name.startsWith("iPhone ")) expect(deviceClass, name).toBe("phone"); + if (name.startsWith("Apple Watch ")) expect(deviceClass, name).toBe("watch"); + } +} + describe.skipIf(process.platform !== "darwin")( "iOS smoke (real simctl)", { tags: ["slow", "ios"] }, @@ -67,7 +79,12 @@ describe.skipIf(process.platform !== "darwin")( expect(catalog.code).toBe(0); const platforms = ( catalog.json as { - platforms: { platform: string; models: string[]; runtimes: string[] }[]; + platforms: { + platform: string; + models: string[]; + runtimes: string[]; + modelClasses: Record; + }[]; } ).platforms; const iosCatalog = platforms.find((platform) => platform.platform === "ios"); @@ -82,6 +99,7 @@ describe.skipIf(process.platform !== "darwin")( "simlock catalog's runtimes must agree with real simctl", ).toContain(runtime); } + expectProductFamilyClasses(iosCatalog); 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 8197718d3..6e159cc2f 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1889,6 +1889,7 @@ describe("CLI: catalog", () => { platforms: [ { modelAliases: {}, + modelClasses: {}, modelRuntimes: {}, models: ["constructor"], platform: "ios", @@ -1914,6 +1915,7 @@ describe("CLI: catalog", () => { platforms: [ { modelAliases: {}, + modelClasses: {}, modelRuntimes: {}, models: [], platform: "android", @@ -1942,6 +1944,7 @@ describe("CLI: catalog", () => { { defaultRuntime: "26.0", modelAliases: {}, + modelClasses: { "iPhone 16": "phone", "iPhone 8": "phone", "iPhone XS": "phone" }, modelRuntimes: { "iPhone 16": ["18.4", "26.0"], "iPhone 8": [], @@ -1963,9 +1966,10 @@ describe("CLI: catalog", () => { "Platform: ios", " Runtimes: 18.4, 26.0 (default: 26.0)", " Models:", - " iPhone 16: 18.4, 26.0", - " iPhone XS: 18.4", - " iPhone 8: (no paired runtime)", + " phone:", + " iPhone 16: 18.4, 26.0", + " iPhone XS: 18.4", + " iPhone 8: (no paired runtime)", "", ].join("\n"), ); @@ -1982,6 +1986,7 @@ describe("CLI: catalog", () => { { images: [], modelAliases: {}, + modelClasses: {}, modelRuntimes: {}, models: [], platform: "android", @@ -2020,6 +2025,7 @@ describe("CLI: catalog", () => { { abi: "arm64-v8a", runtime: "35", tag: "google_apis" }, ], modelAliases: { "Pixel 8": ["pixel_8"] }, + modelClasses: { "My Tablet": "tablet", "Pixel 8": "phone" }, modelRuntimes: { "My Tablet": ["34", "35"], "Pixel 8": ["34", "35"] }, models: ["My Tablet", "Pixel 8"], platform: "android", @@ -2037,9 +2043,11 @@ describe("CLI: catalog", () => { "Platform: android", " Runtimes: 34, 35 (default: 35)", " Models:", - " My Tablet: 34, 35", - " Pixel 8: 34, 35", - " Other names: pixel_8", + " phone:", + " Pixel 8: 34, 35", + " Other names: pixel_8", + " tablet:", + " My Tablet: 34, 35", " Images (runtime, tag, ABI):", " 34 default x86_64", " 35 google_apis arm64-v8a", @@ -2048,6 +2056,119 @@ 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 output = outputCapture(); + const environment = output.environmentWith({ + connectAdmin: async () => + fakeClient({ + getCatalog: () => + Promise.resolve({ + platforms: [ + { + defaultRuntime: "26.0", + modelAliases: { "iPhone 17": ["iphone17", "iphone-17"] }, + modelClasses: { + "Apple TV 4K": "tv", + "Apple Watch Series 11 (46mm)": "watch", + "iPad Pro": "tablet", + "iPhone 17": "phone", + "iPhone 16": "phone", + }, + modelRuntimes: { + "Apple TV 4K": ["26.0"], + "Apple Watch Series 11 (46mm)": ["26.0"], + "Mystery Box": [], + "iPad Pro": ["26.0"], + "iPhone 16": ["26.0"], + "iPhone 17": ["26.0"], + }, + models: [ + "Apple TV 4K", + "Mystery Box", + "iPhone 17", + "Apple Watch Series 11 (46mm)", + "iPad Pro", + "iPhone 16", + ], + platform: "ios", + runtimes: ["26.0"], + }, + ], + }), + }), + }); + + await expect(runCli(["catalog"], environment)).resolves.toBe(0); + + expect(output.stdout).toBe( + [ + "Platform: ios", + " Runtimes: 26.0 (default: 26.0)", + " Models:", + " phone:", + " iPhone 17: 26.0", + " Other names: iphone17, iphone-17", + " iPhone 16: 26.0", + " tablet:", + " iPad Pro: 26.0", + " watch:", + " Apple Watch Series 11 (46mm): 26.0", + " tv:", + " Apple TV 4K: 26.0", + " (no class):", + " Mystery Box: (no paired runtime)", + "", + ].join("\n"), + ); + }); + + it("does not read a class from the prototype for a model named constructor", async () => { + const output = outputCapture(); + const environment = output.environmentWith({ + connectAdmin: async () => + fakeClient({ + getCatalog: () => + Promise.resolve({ + platforms: [ + { + modelAliases: {}, + modelClasses: {}, + modelRuntimes: {}, + models: ["constructor"], + platform: "ios", + runtimes: [], + }, + ], + }), + }), + }); + + await runCli(["catalog"], environment); + + expect(output.stdout).toContain(" (no class):\n constructor: (no paired runtime)\n"); + }); + + it("carries modelClasses as received in the --json output", async () => { + const output = outputCapture(); + const platforms = [ + { + modelAliases: {}, + modelClasses: { "Pixel 8": "phone" as const, "Television (1080p)": "tv" as const }, + modelRuntimes: { "Pixel 8": ["35"], "Television (1080p)": ["35"] }, + models: ["Pixel 8", "Television (1080p)"], + platform: "android" as const, + runtimes: ["35"], + }, + ]; + const environment = output.environmentWith({ + connectAdmin: async () => fakeClient({ getCatalog: () => Promise.resolve({ platforms }) }), + }); + + await expect(runCli(["catalog", "--json"], environment)).resolves.toBe(0); + + expect(JSON.parse(output.stdout)).toEqual({ platforms }); + }); + it("prints (custom) after a custom model and not after a built-in one", async () => { const output = outputCapture(); const environment = output.environmentWith({ @@ -2060,6 +2181,7 @@ describe("CLI: catalog", () => { customModels: ["My Tablet"], defaultRuntime: "35", modelAliases: {}, + modelClasses: { "My Tablet": "phone", "Pixel 8": "phone" }, modelRuntimes: { "My Tablet": ["35"], "Pixel 8": ["35"] }, models: ["My Tablet", "Pixel 8"], platform: "android", @@ -2077,8 +2199,9 @@ describe("CLI: catalog", () => { "Platform: android", " Runtimes: 35 (default: 35)", " Models:", - " My Tablet (custom): 35", - " Pixel 8: 35", + " phone:", + " My Tablet (custom): 35", + " Pixel 8: 35", "", ].join("\n"), ); diff --git a/src/cli/index.ts b/src/cli/index.ts index 2e4ddb447..fb8eec7ac 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -40,7 +40,7 @@ import { type StatusGetOutput, type WorkerView, } from "../admin/index.js"; -import { type Role, waitingRequestSchema } from "../contract/index.js"; +import { deviceClassSchema, type Role, waitingRequestSchema } from "../contract/index.js"; import type { PassthroughCommand } from "../client/index.js"; import { awaitWithin, @@ -2369,19 +2369,28 @@ function formatCatalog(response: CatalogGetOutput): string { const defaultRuntime = entry.defaultRuntime ?? "(none)"; // Each model with the runtimes it pairs with: a model and a runtime both listed for the // platform are not necessarily leasable together. + // Models are grouped under a line per class, in the enum's order, then `(no class)`. // A model's other names follow it on a line of their own. // A model that exists only because of something on that machine is marked `(custom)`. const custom = new Set(entry.customModels ?? []); - const models = entry.models.flatMap((model) => { + const modelLines = (model: string): string[] => { const paired = (Object.hasOwn(entry.modelRuntimes, model) ? entry.modelRuntimes[model] : undefined) ?? []; const aliases = (Object.hasOwn(entry.modelAliases, model) ? entry.modelAliases[model] : undefined) ?? []; return [ - ` ${model}${custom.has(model) ? " (custom)" : ""}: ${paired.length > 0 ? paired.join(", ") : "(no paired runtime)"}`, - ...(aliases.length > 0 ? [` Other names: ${aliases.join(", ")}`] : []), + ` ${model}${custom.has(model) ? " (custom)" : ""}: ${paired.length > 0 ? paired.join(", ") : "(no paired runtime)"}`, + ...(aliases.length > 0 ? [` Other names: ${aliases.join(", ")}`] : []), ]; + }; + const classOf = (model: string) => + Object.hasOwn(entry.modelClasses, model) ? entry.modelClasses[model] : undefined; + const models = [...deviceClassSchema.options, undefined].flatMap((deviceClass) => { + const inClass = entry.models.filter((model) => classOf(model) === deviceClass); + return inClass.length === 0 + ? [] + : [` ${deviceClass ?? "(no class)"}:`, ...inClass.flatMap(modelLines)]; }); 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 e9e0bd918..ccb85fcc5 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; import { OPERATIONS, type Effect, type OperationName } from "./operations.js"; import { PUSH_SCHEMAS } from "./pushes.js"; import type { Role } from "./roles.js"; +import { platformCatalogSchema } from "./schemas.js"; /** * The ADR §3 operation matrix, name -> role. A table-driven test against this makes @@ -480,6 +481,7 @@ describe("operation input/output round trips", () => { models: ["iPhone 17"], runtimes: ["26.0"], modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, }, ], @@ -510,6 +512,7 @@ describe("operation input/output round trips", () => { models: ["iPhone 17"], runtimes: ["26.0"], modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, modelWorkers: { "iPhone 17": ["wrk_1", "wrk_2"] }, runtimeWorkers: { "26.0": ["wrk_1"] }, @@ -520,7 +523,13 @@ describe("operation input/output round trips", () => { }); it("catalog.get rejects a platform entry without modelRuntimes", () => { - const entry = { platform: "ios", models: ["iPhone 17"], runtimes: ["26.0"], modelAliases: {} }; + const entry = { + platform: "ios", + models: ["iPhone 17"], + runtimes: ["26.0"], + modelAliases: {}, + modelClasses: {}, + }; expect(() => OPERATIONS["catalog.get"].output.parse({ platforms: [entry] })).toThrow( /modelRuntimes/, ); @@ -546,6 +555,7 @@ describe("operation input/output round trips", () => { { ...entry, modelAliases: { "Pixel 8": ["pixel_8"] }, + modelClasses: {}, images: [{ runtime: "35", tag: "google_apis", abi: "arm64-v8a" }], }, ], @@ -555,6 +565,35 @@ describe("operation input/output round trips", () => { ]); }); + it("platformCatalogSchema rejects an entry without modelClasses and one whose class is not one of the seven", () => { + const entry = { + platform: "ios", + models: ["iPhone 17"], + runtimes: ["26.0"], + modelAliases: {}, + modelRuntimes: { "iPhone 17": ["26.0"] }, + }; + expect(() => platformCatalogSchema.parse(entry)).toThrow(/modelClasses/); + for (const deviceClass of ["phone", "tablet", "watch", "tv", "vision", "auto", "desktop"]) { + expect( + platformCatalogSchema.parse({ ...entry, modelClasses: { "iPhone 17": deviceClass } }) + .modelClasses, + ).toEqual({ "iPhone 17": deviceClass }); + } + for (const bad of ["Phone", "car", "", "wearable"]) { + expect(() => + platformCatalogSchema.parse({ ...entry, modelClasses: { "iPhone 17": bad } }), + ).toThrow(/modelClasses/); + } + expect(() => + platformCatalogSchema.parse({ ...entry, modelClasses: { ["x".repeat(257)]: "phone" } }), + ).toThrow(/modelClasses/); + expect( + platformCatalogSchema.parse({ ...entry, modelClasses: { ["x".repeat(256)]: "phone" } }) + .modelClasses, + ).toEqual({ ["x".repeat(256)]: "phone" }); + }); + it("catalog.get bounds every string and list in modelAliases, customModels and images", () => { const base = { platform: "android", @@ -562,6 +601,7 @@ describe("operation input/output round trips", () => { runtimes: ["35"], modelRuntimes: { "Pixel 8": ["35"] }, modelAliases: {}, + modelClasses: {}, }; const image = { runtime: "35", tag: "google_apis", abi: "arm64-v8a" }; const names = (count: number) => Array.from({ length: count }, (_, index) => `p${index}`); diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 134f316db..8b13922d2 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 11, and every move that got it there + * The range this contract's daemon speaks. Both ends are 12, 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. 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 the catalog carry a required `modelClasses` per platform (taking it to 12), which a gateway reading a worker's catalog depends on. 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), and one on 10 (ADR 0009 §7). + * (ADR 0007 §12), and so is one on 8 (ADR 0010 §9), and one on 10 (ADR 0009 §7), and one on 11 (ADR 0015 §3). */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 11, max: 11 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 12, max: 12 }; /** * 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 0a86f6bf1..722807134 100644 --- a/src/contract/schemas.test.ts +++ b/src/contract/schemas.test.ts @@ -294,6 +294,7 @@ describe("fitPlatformCatalog", () => { customModels, defaultRuntime: "35", modelAliases: {}, + modelClasses: {}, modelRuntimes: Object.fromEntries(customModels.map((model) => [model, ["35"]])), models: customModels, platform: "android" as const, @@ -316,6 +317,22 @@ describe("fitPlatformCatalog", () => { expect(fitted.models).toEqual(["x".repeat(257)]); }); + it("drops the class of a model whose name is too long to be a modelClasses key, in an entry the schema accepts", () => { + const long = "x".repeat(257); + const longest = "y".repeat(256); + const fitted = fitPlatformCatalog({ + ...entry(["Pixel 8"]), + modelClasses: { + [long]: "phone" as const, + [longest]: "tv" as const, + "Pixel 8": "phone" as const, + }, + }); + + expect(fitted.modelClasses).toEqual({ [longest]: "tv", "Pixel 8": "phone" }); + expect(() => platformCatalogSchema.parse(fitted)).not.toThrow(); + }); + it("leaves an entry that already fits as it is", () => { const fits = entry(["My Tablet"]); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 8896b554f..130123a44 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -22,6 +22,21 @@ import { z } from "zod"; export const platformSchema = z.enum(["ios", "android"]); export type Platform = z.infer; +/** + * ADR 0015 §3: the class of a device model, in the order a catalog lists them. Which product + * family or tag is which class is each driver's knowledge; the names live here. + */ +export const deviceClassSchema = z.enum([ + "phone", + "tablet", + "watch", + "tv", + "vision", + "auto", + "desktop", +]); +export type DeviceClass = z.infer; + const deviceStateSchema = z.enum([ "provisioning", "ready", @@ -467,6 +482,12 @@ export const platformCatalogSchema = z.object({ .refine((aliases) => Object.keys(aliases).length <= CATALOG_ALIASED_MODELS_MAX, { message: `modelAliases lists more than ${CATALOG_ALIASED_MODELS_MAX} models`, }), + /** + * ADR 0015 §3: for a name in `models` whose tooling reports one, its device class. A model + * the tooling gives no recognised class has no entry. On a gateway it is the union over + * workers; when two class a model differently, the first worker in id order wins. + */ + modelClasses: z.record(z.string().max(CATALOG_NAME_MAX), deviceClassSchema), /** * 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 @@ -498,15 +519,30 @@ export const platformCatalogSchema = z.object({ * answer. A name that does not fit loses its mark and stays in `models`; the list stops at its * maximum, and an empty list is left out. Lives beside the schema so the bounds are written once. */ -export function fitPlatformCatalog( - entry: Entry, -): Entry { - if (entry.customModels === undefined) return entry; - const { customModels, ...rest } = entry; +export function fitPlatformCatalog< + Entry extends { + readonly customModels?: readonly string[]; + readonly modelClasses?: Readonly>; + }, +>(entry: Entry): Entry { + const { customModels, modelClasses, ...rest } = entry; + // A class keyed by a name too long to be a `modelClasses` key loses its entry, not the answer. + // An entry with no `modelClasses` at all is left for the schema to refuse. + const fitted = { + ...rest, + ...(modelClasses === undefined + ? {} + : { + modelClasses: Object.fromEntries( + Object.entries(modelClasses).filter(([model]) => model.length <= CATALOG_NAME_MAX), + ), + }), + }; + if (customModels === undefined) return fitted as unknown as Entry; const fitting = customModels .filter((model) => model.length <= CATALOG_NAME_MAX) .slice(0, CATALOG_CUSTOM_MODELS_MAX); - return (fitting.length === 0 ? rest : { ...rest, customModels: fitting }) as Entry; + return (fitting.length === 0 ? fitted : { ...fitted, customModels: fitting }) as unknown as Entry; } export const proposalSchema = z.object({ diff --git a/src/core/domain.ts b/src/core/domain.ts index fea580b8a..b6e33876f 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -2,6 +2,9 @@ import type { DeviceRequest } from "./driver.js"; export type Platform = "ios" | "android"; +/** ADR 0015 §3: the class of a device model. Which family or tag is which is each driver's own. */ +export type DeviceClass = "phone" | "tablet" | "watch" | "tv" | "vision" | "auto" | "desktop"; + /** 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 a5fd9630f..ea3b64b77 100644 --- a/src/core/driver-catalog.test.ts +++ b/src/core/driver-catalog.test.ts @@ -51,6 +51,7 @@ describe("DriverCatalog", () => { { defaultRuntime: "26.5", modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 16": ["18.4", "26.5"] }, models: ["iPhone 16"], platform: "ios", @@ -59,6 +60,7 @@ describe("DriverCatalog", () => { { defaultRuntime: "34", modelAliases: {}, + modelClasses: {}, modelRuntimes: { "Pixel 8": ["34"] }, models: ["Pixel 8"], platform: "android", @@ -77,6 +79,7 @@ describe("DriverCatalog", () => { { defaultRuntime: "26.5", modelAliases: {}, + modelClasses: {}, modelRuntimes: {}, models: [], platform: "ios", @@ -97,6 +100,7 @@ describe("DriverCatalog", () => { { defaultRuntime: "26.5", modelAliases: {}, + modelClasses: {}, modelRuntimes: {}, models: [], platform: "ios", diff --git a/src/core/driver.ts b/src/core/driver.ts index 856ba8982..f181fddba 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -1,7 +1,13 @@ import type { EventMap } from "../bus/index.js"; import type { Filesystem } from "../ports/index.js"; import type { RootRejectionReason } from "./device-root.js"; -import type { DeviceMode, DeviceSpec, DeviceTransitionUpdate, Platform } from "./domain.js"; +import type { + DeviceClass, + DeviceMode, + DeviceSpec, + DeviceTransitionUpdate, + Platform, +} from "./domain.js"; export interface DeviceRequest { readonly platform: Platform; @@ -136,6 +142,10 @@ export type DriverEstimate = * the same matcher `resolveSpec` uses; a model with no other name has no entry. `images` is * present only for a driver whose runtimes come as installed images, one entry per image. * + * `modelClasses` maps a name in `models` to its device class, for every model the driver's tooling + * reports one for; a model it reports none for, or one it does not recognise, has no entry. The + * core carries it and reads nothing from it. + * * `customModels` names the values from `models` that exist because of something on this * machine, not because of the platform's tools. The core carries it and never reads it; a * driver with no such models omits the field. @@ -146,6 +156,7 @@ export interface DriverCatalogEntry { readonly defaultRuntime: string | undefined; readonly modelRuntimes: Readonly>; readonly modelAliases: Readonly>; + readonly modelClasses: Readonly>; readonly images?: readonly DriverCatalogImage[]; readonly customModels?: readonly string[]; } diff --git a/src/core/fake-driver.test.ts b/src/core/fake-driver.test.ts index 7ebcdebc3..48c3917ee 100644 --- a/src/core/fake-driver.test.ts +++ b/src/core/fake-driver.test.ts @@ -144,12 +144,27 @@ describe("FakeDriver", () => { await expect(driver.listCatalog()).resolves.toEqual({ defaultRuntime: "26.5", modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 16": ["18.4", "26.5"], "iPhone 17 Pro": ["18.4", "26.5"] }, models: ["iPhone 16", "iPhone 17 Pro"], runtimes: ["18.4", "26.5"], }); }); + it("carries the modelClasses its options name, and an empty map without them", async () => { + const options = { + availableOsVersions: ["35"], + clock: new FakeClock(), + knownModels: ["Pixel 8", "Television (1080p)"], + platform: "android" as const, + }; + + const scripted = new FakeDriver({ ...options, modelClasses: { "Television (1080p)": "tv" } }); + + expect((await scripted.listCatalog()).modelClasses).toEqual({ "Television (1080p)": "tv" }); + expect((await new FakeDriver(options).listCatalog()).modelClasses).toEqual({}); + }); + it("pairs a model with only the runtimes its modelRuntimes option names", async () => { const driver = new FakeDriver({ availableOsVersions: ["18.4", "26.5"], diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index 02a91d191..13700ad70 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -1,5 +1,5 @@ import type { Clock } from "../ports/index.js"; -import type { DeviceMode, DeviceSpec, Platform } from "./domain.js"; +import type { DeviceClass, DeviceMode, DeviceSpec, Platform } from "./domain.js"; import { type ComponentInstallProgress, type ComponentInstallResult, @@ -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>; + /** What `listCatalog` reports as each model's class; none unless set. */ + readonly modelClasses?: Readonly>; /** * What `listCatalog` reports as installed images; the field is absent unless set. A request * naming an image tag resolves only to a runtime listed here with that tag. @@ -164,6 +166,7 @@ export class FakeDriver implements Driver { readonly #knownModels: Set | undefined; readonly #modelRuntimes: FakeDriverOptions["modelRuntimes"]; readonly #modelAliases: FakeDriverOptions["modelAliases"]; + readonly #modelClasses: FakeDriverOptions["modelClasses"]; readonly #images: FakeDriverOptions["images"]; readonly #customModels: FakeDriverOptions["customModels"]; readonly #latencyMs: FakeDriverOptions["latencyMs"]; @@ -193,6 +196,7 @@ export class FakeDriver implements Driver { options.knownModels === undefined ? undefined : new Set(options.knownModels); this.#modelRuntimes = options.modelRuntimes; this.#modelAliases = options.modelAliases; + this.#modelClasses = options.modelClasses; this.#images = options.images; this.#customModels = options.customModels; this.#latencyMs = options.latencyMs; @@ -514,6 +518,7 @@ export class FakeDriver implements Driver { ...(this.#images === undefined ? {} : { images: [...this.#images] }), ...(this.#customModels === undefined ? {} : { customModels: [...this.#customModels] }), modelAliases: { ...this.#modelAliases }, + modelClasses: { ...this.#modelClasses }, modelRuntimes: Object.fromEntries( models.map((model) => [model, [...(this.#modelRuntimes?.[model] ?? runtimes)]]), ), diff --git a/src/core/index.ts b/src/core/index.ts index e35e9e131..31e127366 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -11,6 +11,7 @@ export { redactConfig, } from "./config.js"; export { + type DeviceClass, type DeviceMode, type DeviceRecord, type DeviceSpec, diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index d0b32e2b1..1d4d0f76f 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. - expect(DAEMON_PROTOCOL_VERSION).toBe(11); + // required field of each platform's `status.get` capacity, taking it to 11, then a required `modelClasses` on each catalog entry, taking it to 12. + expect(DAEMON_PROTOCOL_VERSION).toBe(12); 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 29202394b..e723dfbcd 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: {}, + modelClasses: {}, models: [], modelRuntimes: {}, platform: "ios", diff --git a/src/drivers/android/device-profile-source.test.ts b/src/drivers/android/device-profile-source.test.ts index c678cd8f0..18bb67fd0 100644 --- a/src/drivers/android/device-profile-source.test.ts +++ b/src/drivers/android/device-profile-source.test.ts @@ -4,6 +4,7 @@ import { MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; import { BuiltinDeviceProfileSource, DeviceProfileRegistry, + parseAvdmanagerDeviceProfiles, parseDevicesXml, UserDeviceProfileSource, type DeviceProfileSourceDiagnostic, @@ -22,6 +23,7 @@ describe("BuiltinDeviceProfileSource", () => { { avdmanagerId: "pixel_8", custom: false, + deviceClass: "phone", kind: "builtin", name: "Pixel 8", names: ["Pixel 8", "pixel_8"], @@ -60,6 +62,7 @@ describe("BuiltinDeviceProfileSource", () => { { avdmanagerId: "TV_1080p", custom: false, + deviceClass: "phone", kind: "builtin", name: "tv_1080p", names: ["tv_1080p"], @@ -68,6 +71,97 @@ describe("BuiltinDeviceProfileSource", () => { }); }); +describe("parseAvdmanagerDeviceProfiles", () => { + it("keeps the Tag line of the entry it belongs to and reads none before the first id", () => { + const output = + `Available devices:\n Tag : android-tv\n` + + `id: 0 or "pixel_8"\n Name: Pixel 8\n OEM : Google\n---------\n` + + `id: 1 or "tv_1080p"\n Name: Television (1080p)\n OEM : Google\n Tag : android-tv\n---------\n` + + `id: 2 or "wear_round"\n Name: Wear Round\n Tag : android-wear\n---------\n` + + `id: 3 or "tight"\n Name: Tight\n Tag:android-desktop\n---------\n` + + `id: 4 or "prefixed"\n Name: Prefixed\n SubTag : android-tv\n`; + + expect(parseAvdmanagerDeviceProfiles(output)).toEqual([ + { id: "pixel_8", name: "Pixel 8", oem: "Google", tag: undefined }, + { id: "tv_1080p", name: "Television (1080p)", oem: "Google", tag: "android-tv" }, + { id: "wear_round", name: "Wear Round", oem: undefined, tag: "android-wear" }, + { id: "tight", name: "Tight", oem: undefined, tag: "android-desktop" }, + { id: "prefixed", name: "Prefixed", oem: undefined, tag: undefined }, + ]); + }); +}); + +describe("device classes in the catalog", () => { + function registryFor(entries: readonly [name: string, tag: string | undefined][]) { + const stdout = + "Available devices:\n" + + entries + .map( + ([name, tag], index) => + `id: ${index} or "dev_${index}"\n Name: ${name}\n OEM : Google\n` + + (tag === undefined ? "" : ` Tag : ${tag}\n`), + ) + .join("---------\n"); + return new DeviceProfileRegistry([ + new BuiltinDeviceProfileSource( + avdmanager, + new ScriptedProcessRunner([processResult(stdout)]), + ), + ]); + } + + it("classes a profile by its tag: android-tv is tv, android-wear is watch, android-automotive, android-automotive-playstore and android-automotive-distantdisplay are auto, android-desktop is desktop", async () => { + const registry = registryFor([ + ["Television (1080p)", "android-tv"], + ["Wear Round", "android-wear"], + ["Car", "android-automotive"], + ["Car Play Store", "android-automotive-playstore"], + ["Car Distant", "android-automotive-distantdisplay"], + ["Desktop (Large)", "android-desktop"], + ]); + + await expect(registry.catalog()).resolves.toMatchObject({ + modelClasses: { + Car: "auto", + "Car Distant": "auto", + "Car Play Store": "auto", + "Desktop (Large)": "desktop", + "Television (1080p)": "tv", + "Wear Round": "watch", + }, + }); + }); + + it("classes an untagged avdmanager profile and a devices.xml profile as phone", async () => { + const registry = new DeviceProfileRegistry([ + new BuiltinDeviceProfileSource( + avdmanager, + new ScriptedProcessRunner([processResult(pixelDevices)]), + ), + new UserDeviceProfileSource(devicesXmlPath, await filesystemWithDevicesXml(devicesXml())), + ]); + + await expect(registry.catalog()).resolves.toMatchObject({ + modelClasses: { "My Custom Phone": "phone", "Pixel 8": "phone" }, + }); + }); + + it("lists a profile with any other tag in models and gives it no modelClasses entry", async () => { + const registry = registryFor([ + ["Pixel 8", undefined], + ["Odd Thing", "android-xr"], + ["Car-ish", "android-automotiv"], + ["Prefix", "x-android-tv"], + ]); + + const catalog = await registry.catalog(); + + expect(catalog.models).toEqual(["Pixel 8", "Odd Thing", "Car-ish", "Prefix"]); + // Strict: a model with no class must be absent, not present as undefined. + expect(catalog.modelClasses).toStrictEqual({ "Pixel 8": "phone" }); + }); +}); + describe("UserDeviceProfileSource", () => { it("lists a properties profile mapped from devices.xml hardware fields, answering to its name only", async () => { const filesystem = await filesystemWithDevicesXml(devicesXml()); @@ -324,6 +418,7 @@ describe("DeviceProfileRegistry", () => { await expect(registry.resolve("Pixel 8")).resolves.toEqual({ avdmanagerId: "pixel_8", custom: false, + deviceClass: "phone", kind: "builtin", name: "Pixel 8", names: ["Pixel 8", "pixel_8"], @@ -417,6 +512,7 @@ describe("DeviceProfileRegistry", () => { await expect(registry.catalog()).resolves.toEqual({ customModels: ["My Custom Phone"], modelAliases: { "Pixel 8": ["pixel_8"] }, + modelClasses: { "My Custom Phone": "phone", "Pixel 8": "phone" }, models: ["Pixel 8", "My Custom Phone"], }); }); @@ -437,6 +533,7 @@ describe("DeviceProfileRegistry", () => { await expect(registry.catalog()).resolves.toEqual({ customModels: [], modelAliases: { "Pixel 8": ["pixel_8"] }, + modelClasses: { "Pixel 8": "phone", "Pixel 8 Copy": "phone" }, models: ["Pixel 8", "Pixel 8 Copy"], }); }); @@ -472,6 +569,7 @@ describe("DeviceProfileRegistry", () => { await expect(registry.catalog()).resolves.toEqual({ customModels: ["My Custom Phone"], modelAliases: { "Pixel 8": ["pixel_8"] }, + modelClasses: { "My Custom Phone": "phone", "Pixel 8": "phone" }, models: ["Pixel 8", "My Custom Phone"], }); }); @@ -587,6 +685,7 @@ describe("DeviceProfileRegistry", () => { await expect(registry.catalog()).resolves.toEqual({ customModels: [], modelAliases: { "Pixel 8": ["pixel_8"] }, + modelClasses: { "Pixel 8": "phone" }, models: ["Pixel 8"], }); expect(diagnostics).toEqual([ diff --git a/src/drivers/android/device-profile-source.ts b/src/drivers/android/device-profile-source.ts index 0a9b433b5..3cf03ad3e 100644 --- a/src/drivers/android/device-profile-source.ts +++ b/src/drivers/android/device-profile-source.ts @@ -1,3 +1,4 @@ +import type { DeviceClass } from "../../core/domain.js"; import { DriverCrashError, UnknownModelError } from "../../core/driver.js"; import type { Filesystem, ProcessRunner } from "../../ports/index.js"; @@ -12,6 +13,9 @@ import type { Filesystem, ProcessRunner } from "../../ports/index.js"; * A `builtin` profile is `custom` when `avdmanager` lists it with `OEM : User`: that is how it * prints a profile from Android Studio's `devices.xml`, which it reads itself. * + * A `properties` profile is a phone. A `builtin` one has the class its `Tag :` line gives it + * (`deviceClassOfTag`), or none for a tag the table does not know. + * * `names` is every name the profile answers to, `name` first, no two equal ignoring case. * `DeviceProfileRegistry` matches a requested model against it and lists the rest as the * model's other names, so the two can never disagree. @@ -23,6 +27,8 @@ export type DeviceProfile = readonly names: readonly string[]; readonly avdmanagerId: string; readonly custom: boolean; + /** From the entry's `Tag :` line; undefined when the tag is one no class is known for. */ + readonly deviceClass: DeviceClass | undefined; } | { readonly kind: "properties"; @@ -63,6 +69,8 @@ export interface DeviceProfileCatalog { * one: a custom profile from this machine rather than one the SDK ships. In `models` order. */ readonly customModels: readonly string[]; + /** The class of each listed model that has one, keyed by its spelling in `models`. */ + readonly modelClasses: Readonly>; } /** @@ -110,7 +118,13 @@ export class DeviceProfileRegistry { const profile = matchProfile(profiles, model); return profile !== undefined && isCustom(profile); }); - return { customModels, modelAliases, models }; + const modelClasses = Object.fromEntries( + [...listed.values()].flatMap((profile) => { + const deviceClass = profile.kind === "properties" ? "phone" : profile.deviceClass; + return deviceClass === undefined ? [] : [[profile.name, deviceClass] as const]; + }), + ); + return { customModels, modelAliases, modelClasses, models }; } /** @@ -185,6 +199,7 @@ export class BuiltinDeviceProfileSource implements DeviceProfileSource { (profile): DeviceProfile => ({ avdmanagerId: profile.id, custom: profile.oem === "User", + deviceClass: deviceClassOfTag(profile.tag), kind: "builtin", name: profile.name, names: @@ -214,23 +229,41 @@ export class BuiltinDeviceProfileSource implements DeviceProfileSource { } } +/** + * `avdmanager`'s `Tag :` -> class. No tag is a phone; a tag not listed here has no class, and + * its profile stays leasable. + */ +function deviceClassOfTag(tag: string | undefined): DeviceClass | undefined { + if (tag === undefined) return "phone"; + if (tag === "android-tv") return "tv"; + if (tag === "android-wear") return "watch"; + if (tag.startsWith("android-automotive")) return "auto"; + if (tag === "android-desktop") return "desktop"; + return undefined; +} + interface AvdmanagerDeviceProfile { readonly id: string; readonly name: string; /** The entry's `OEM :` line, or undefined without one. `User` marks a devices.xml profile. */ readonly oem: string | undefined; + /** The entry's `Tag :` line, or undefined without one. */ + readonly tag: string | undefined; } /** - * One profile per `id:` entry that has a `Name:` line. `OEM :` comes after `Name:`, so an - * entry is complete only at the next `id:` line or the end of the output. + * One profile per `id:` entry that has a `Name:` line. `OEM :` and `Tag :` come after `Name:`, + * so an entry is complete only at the next `id:` line or the end of the output; a `Tag :` line + * before the first `id:` belongs to no entry. */ export function parseAvdmanagerDeviceProfiles(output: string): AvdmanagerDeviceProfile[] { const profiles: AvdmanagerDeviceProfile[] = []; - let entry: { id: string; name: string | undefined; oem: string | undefined } | undefined; + let entry: + | { id: string; name: string | undefined; oem: string | undefined; tag: string | undefined } + | undefined; const flush = (): void => { if (entry?.name !== undefined) { - profiles.push({ id: entry.id, name: entry.name, oem: entry.oem }); + profiles.push({ id: entry.id, name: entry.name, oem: entry.oem, tag: entry.tag }); } }; for (const line of output.split(/\r?\n/)) { @@ -238,7 +271,7 @@ export function parseAvdmanagerDeviceProfiles(output: string): AvdmanagerDeviceP const idMatch = /^id:\s*\d+\s+or\s+"([^"]+)"/.exec(trimmed); if (idMatch?.[1] !== undefined) { flush(); - entry = { id: idMatch[1], name: undefined, oem: undefined }; + entry = { id: idMatch[1], name: undefined, oem: undefined, tag: undefined }; continue; } if (entry === undefined) { @@ -252,6 +285,11 @@ export function parseAvdmanagerDeviceProfiles(output: string): AvdmanagerDeviceP const oemMatch = /^OEM\s*:\s*(.+)$/.exec(trimmed); if (oemMatch?.[1] !== undefined) { entry.oem = oemMatch[1]; + continue; + } + const tagMatch = /^Tag\s*:\s*(.+)$/.exec(trimmed); + if (tagMatch?.[1] !== undefined) { + entry.tag = tagMatch[1]; } } flush(); diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 120baa00b..99e12ac28 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -1200,6 +1200,7 @@ describe("AndroidDriver", () => { { abi: "x86_64", runtime: "35", tag: "google_apis" }, ], modelAliases: { "Pixel 8": ["pixel_8"] }, + modelClasses: { "Pixel 8": "phone" }, modelRuntimes: { "Pixel 8": ["34", "35"] }, models: ["Pixel 8"], runtimes: ["34", "35"], @@ -1264,6 +1265,7 @@ describe("AndroidDriver", () => { defaultRuntime: undefined, images: [], modelAliases: { "Pixel 8": ["pixel_8"] }, + modelClasses: { "Pixel 8": "phone" }, modelRuntimes: { "Pixel 8": [] }, models: ["Pixel 8"], runtimes: [], diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index dfcfc8f23..f32357c2b 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -1162,7 +1162,7 @@ export class AndroidDriver implements Driver { } async listCatalog(): Promise { - const [{ customModels, modelAliases, models }, images] = await Promise.all([ + const [{ customModels, modelAliases, modelClasses, models }, images] = await Promise.all([ this.#deviceProfiles.catalog(), this.#installedImages(), ]); @@ -1175,6 +1175,7 @@ export class AndroidDriver implements Driver { .map((image) => ({ abi: image.abi, runtime: image.apiLevel, tag: image.tag })) .sort(compareCatalogImages), modelAliases, + modelClasses, modelRuntimes: Object.fromEntries(models.map((model) => [model, [...runtimes]])), models: [...models], runtimes, diff --git a/src/drivers/ios/fixtures/simctl-list.json b/src/drivers/ios/fixtures/simctl-list.json index f1c6287d1..a706e2d1a 100644 --- a/src/drivers/ios/fixtures/simctl-list.json +++ b/src/drivers/ios/fixtures/simctl-list.json @@ -4,19 +4,22 @@ "identifier": "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro", "name": "iPhone 17 Pro", "minRuntimeVersion": 0, - "maxRuntimeVersion": 16777215 + "maxRuntimeVersion": 16777215, + "productFamily": "iPhone" }, { "identifier": "com.apple.CoreSimulator.SimDeviceType.iPhone-16", "name": "iPhone 16", "minRuntimeVersion": 0, - "maxRuntimeVersion": 16777215 + "maxRuntimeVersion": 16777215, + "productFamily": "iPhone" }, { "identifier": "com.apple.CoreSimulator.SimDeviceType.iPhone-15-Pro", "name": "iPhone 15 Pro", "minRuntimeVersion": 0, - "maxRuntimeVersion": 16777215 + "maxRuntimeVersion": 16777215, + "productFamily": "iPhone" } ], "runtimes": [ diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 0878d8309..c7e49df5c 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -72,12 +72,18 @@ const modelRuntimesFixture = JSON.stringify({ ], }); -function deviceType(id: string, name: string, maxRuntimeVersion = 0xffffff) { +function deviceType( + id: string, + name: string, + maxRuntimeVersion = 0xffffff, + productFamily?: string, +) { return { identifier: `com.apple.CoreSimulator.SimDeviceType.${id}`, maxRuntimeVersion, minRuntimeVersion: 0, name, + ...(productFamily === undefined ? {} : { productFamily }), }; } @@ -426,6 +432,7 @@ describe("IosSimctlDriver", () => { await expect(driver.listCatalog()).resolves.toEqual({ defaultRuntime: undefined, modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 16": [] }, models: ["iPhone 16"], runtimes: [], @@ -1031,6 +1038,11 @@ describe("IosSimctlDriver", () => { await expect(driver.listCatalog()).resolves.toStrictEqual({ defaultRuntime: "26.5", modelAliases: {}, + modelClasses: { + "iPhone 15 Pro": "phone", + "iPhone 16": "phone", + "iPhone 17 Pro": "phone", + }, modelRuntimes: { "iPhone 15 Pro": ["18.4", "26.5"], "iPhone 16": ["18.4", "26.5"], @@ -1041,6 +1053,84 @@ describe("IosSimctlDriver", () => { }); }); + describe("model classes", () => { + function classRunner(types: ReturnType[]): ScriptedProcessRunner { + return new ScriptedProcessRunner([ + { + match: listInvocation, + result: { + code: 0, + stderr: "", + stdout: JSON.stringify({ devicetypes: types, runtimes: [] }), + }, + }, + ]); + } + + it("classes a device type by its product family: iPhone is phone, iPad is tablet, Apple Watch is watch, Apple TV is tv, Apple Vision is vision", async () => { + const driver = await createDriver( + classRunner([ + deviceType("iPhone-17", "iPhone 17", 0xffffff, "iPhone"), + deviceType("iPad-Pro", "iPad Pro", 0xffffff, "iPad"), + deviceType("Watch-11", "Apple Watch Series 11 (46mm)", 0xffffff, "Apple Watch"), + deviceType("TV-4K", "Apple TV 4K", 0xffffff, "Apple TV"), + deviceType("Vision", "Apple Vision Pro", 0xffffff, "Apple Vision"), + ]), + ); + + const catalog = await driver.listCatalog(); + + expect(catalog.modelClasses).toEqual({ + "Apple TV 4K": "tv", + "Apple Vision Pro": "vision", + "Apple Watch Series 11 (46mm)": "watch", + "iPad Pro": "tablet", + "iPhone 17": "phone", + }); + }); + + it("keeps a device type with no product family, or one outside those five, in models with no modelClasses entry", async () => { + const driver = await createDriver( + classRunner([ + deviceType("iPhone-17", "iPhone 17", 0xffffff, "iPhone"), + deviceType("Old", "Old Device"), + deviceType("Pod", "iPod touch", 0xffffff, "iPod"), + deviceType("Mac", "Mac Thing", 0xffffff, ""), + deviceType("Lower", "Lower Phone", 0xffffff, "iphone"), + ]), + ); + + const catalog = await driver.listCatalog(); + + expect(catalog.models).toEqual([ + "iPhone 17", + "Old Device", + "iPod touch", + "Mac Thing", + "Lower Phone", + ]); + // Strict: a model with no class must be absent, not present as undefined. + expect(catalog.modelClasses).toStrictEqual({ "iPhone 17": "phone" }); + }); + + it("ignores a product family that is not a string", async () => { + const stdout = JSON.stringify({ + devicetypes: [{ ...deviceType("iPhone-17", "iPhone 17"), productFamily: 7 }], + runtimes: [], + }); + const driver = await createDriver( + new ScriptedProcessRunner([ + { match: listInvocation, result: { code: 0, stderr: "", stdout } }, + ]), + ); + + await expect(driver.listCatalog()).resolves.toMatchObject({ + models: ["iPhone 17"], + modelClasses: {}, + }); + }); + }); + describe("model and runtime pairing", () => { function pairingRunner(calls = 1): ScriptedProcessRunner { return new ScriptedProcessRunner( diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 1f5f9b0b1..2211d669f 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -33,7 +33,7 @@ import { UnsupportedRequestOptionError, } from "../../core/index.js"; import type { ObservedMark } from "../../core/driver.js"; -import type { DeviceMode, DeviceSpec } from "../../core/index.js"; +import type { DeviceClass, DeviceMode, DeviceSpec } from "../../core/index.js"; import type { Clock, Filesystem, @@ -262,6 +262,8 @@ interface DeviceType { readonly minRuntimeVersion: number; /** Same encoding; `UNBOUNDED_VERSION` means "no upper bound". */ readonly maxRuntimeVersion: number; + /** simctl's `productFamily` ("iPhone", "iPad", ...), or undefined when it is absent or not a string. */ + readonly productFamily: string | undefined; } interface Runtime { @@ -1268,12 +1270,19 @@ export class IosSimctlDriver implements Driver { const catalog = await this.#loadCatalog(); const installedRuntimes = catalog.runtimes.filter((runtime) => runtime.isAvailable); const models = catalog.deviceTypes.map((deviceType) => deviceType.name); + const modelClasses = Object.fromEntries( + catalog.deviceTypes.flatMap((deviceType) => { + const deviceClass = PRODUCT_FAMILY_CLASSES.get(deviceType.productFamily); + return deviceClass === undefined ? [] : [[deviceType.name, deviceClass] as const]; + }), + ); return { defaultRuntime: newestRuntime(installedRuntimes)?.version, // Keyed by name and paired through the device type `resolveSpec` would pick for that name, // so two device types that differ only in letter case both list the first one's runtimes. // A device type answers to its name only, in any letter case (`findDeviceType`). modelAliases: {}, + modelClasses, modelRuntimes: Object.fromEntries( models.map((model) => [model, pairedVersions(catalog, findDeviceType(catalog, model))]), ), @@ -1997,6 +2006,15 @@ function parseCatalog(value: unknown): SimctlCatalog { return { deviceTypes, runtimes }; } +/** simctl's `productFamily` -> class. A family not listed here has no class and stays leasable. */ +const PRODUCT_FAMILY_CLASSES: ReadonlyMap = new Map([ + ["iPhone", "phone"], + ["iPad", "tablet"], + ["Apple Watch", "watch"], + ["Apple TV", "tv"], + ["Apple Vision", "vision"], +]); + function parseDeviceType(value: unknown): readonly DeviceType[] { if (!isRecord(value) || typeof value.identifier !== "string" || typeof value.name !== "string") { return []; @@ -2008,6 +2026,7 @@ function parseDeviceType(value: unknown): readonly DeviceType[] { maxRuntimeVersion: versionIntOr(value.maxRuntimeVersion, UNBOUNDED_VERSION), minRuntimeVersion: versionIntOr(value.minRuntimeVersion, 0), name: value.name, + productFamily: typeof value.productFamily === "string" ? value.productFamily : undefined, }, ]; } diff --git a/src/gateway/aggregate.test.ts b/src/gateway/aggregate.test.ts index a34f64d8f..8f658b721 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: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, models: ["iPhone 17"], platform: "ios" as const, @@ -341,6 +342,7 @@ describe("aggregateCatalog", () => { const iosOnB = { defaultRuntime: "26.0", modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPad Pro": ["25.4", "26.0"], "iPhone 17": ["26.0"] }, models: ["iPhone 17", "iPad Pro"], platform: "ios" as const, @@ -364,6 +366,59 @@ describe("aggregateCatalog", () => { }); }); + it("carries modelClasses as the union over connected workers", () => { + const withClasses = (modelClasses: Record) => ({ + ...iosOnB, + modelClasses, + }); + const catalog = aggregateCatalog([ + view({ catalog: [{ ...iosOnA, modelClasses: { "iPhone 17": "phone" } }], id: "wrk_a" }), + view({ catalog: [withClasses({ "iPad Pro": "tablet" })], id: "wrk_b" }), + view({ + catalog: [withClasses({ "Apple Watch": "watch" })], + connection: "disconnected", + id: "wrk_c", + }), + ]); + + expect(catalog.platforms[0]?.modelClasses).toEqual({ + "iPad Pro": "tablet", + "iPhone 17": "phone", + }); + expect(() => OPERATIONS["catalog.get"].output.parse(catalog)).not.toThrow(); + }); + + it("keeps the class of the first worker in id order when two workers class a model differently", () => { + const classed = (deviceClass: "phone" | "tablet") => ({ + ...iosOnA, + modelClasses: { "iPhone 17": deviceClass }, + }); + + // Listed in either order, so neither first-listed nor last-listed alone picks the class. + const laterIdFirst = aggregateCatalog([ + view({ catalog: [classed("tablet")], id: "wrk_b" }), + view({ catalog: [classed("phone")], id: "wrk_a" }), + ]); + const earlierIdFirst = aggregateCatalog([ + view({ catalog: [classed("phone")], id: "wrk_a" }), + view({ catalog: [classed("tablet")], id: "wrk_b" }), + ]); + + expect(laterIdFirst.platforms[0]?.modelClasses).toEqual({ "iPhone 17": "phone" }); + expect(earlierIdFirst.platforms[0]?.modelClasses).toEqual({ "iPhone 17": "phone" }); + }); + + it("ignores a class a worker gives to a name it does not list, and does not read the prototype", () => { + const catalog = aggregateCatalog([ + view({ + catalog: [{ ...iosOnA, modelClasses: { "Not Listed": "tv", "iPhone 17": "phone" } }], + id: "wrk_a", + }), + ]); + + expect(catalog.platforms[0]?.modelClasses).toEqual({ "iPhone 17": "phone" }); + }); + it("keeps a default runtime only when every worker agrees on it", () => { const agreed = aggregateCatalog([ view({ catalog: [iosOnA], id: "wrk_a" }), @@ -397,6 +452,7 @@ describe("aggregateCatalog", () => { it("pairs a model with a runtime when at least one connected worker pairs them", () => { const iosOnC = { modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17": ["25.4"] }, models: ["iPhone 17"], platform: "ios" as const, @@ -427,6 +483,7 @@ describe("aggregateCatalog", () => { it("ignores the pairings of disconnected and incompatible workers", () => { const pairsOld = { modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17": ["25.4"] }, models: ["iPhone 17"], platform: "ios" as const, @@ -444,6 +501,7 @@ describe("aggregateCatalog", () => { it("gives every model in the fleet catalog a modelRuntimes entry, empty when nothing pairs", () => { const unpaired = { modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone XS": [] }, models: ["iPhone XS"], platform: "ios" as const, @@ -468,6 +526,7 @@ describe("aggregateCatalog", () => { platforms: [ { modelAliases: {}, + modelClasses: {}, modelRuntimes: {}, models: ["constructor"], platform: "ios", @@ -484,6 +543,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: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17": ["25.4", "26.0"] }, models: ["iPhone 17"], platform: "ios" as const, @@ -506,6 +566,7 @@ describe("aggregateCatalog", () => { iosOnA, { modelAliases: {}, + modelClasses: {}, modelRuntimes: { "Pixel 9": ["35"] }, models: ["Pixel 9"], platform: "android", @@ -537,6 +598,7 @@ describe("aggregateCatalog", () => { ...(overrides.customModels === undefined ? {} : { customModels: overrides.customModels }), ...(overrides.images === undefined ? {} : { images: overrides.images }), modelAliases: overrides.modelAliases ?? {}, + modelClasses: {}, modelRuntimes: Object.fromEntries(models.map((model) => [model, runtimes])), models, platform: "android" as const, diff --git a/src/gateway/aggregate.ts b/src/gateway/aggregate.ts index 4952e98de..7067a05e8 100644 --- a/src/gateway/aggregate.ts +++ b/src/gateway/aggregate.ts @@ -9,6 +9,7 @@ import { CATALOG_LIST_LIMITS, INSTALL_LIST_LIMIT, OPERATIONS, + type DeviceClass, type Platform, } from "../contract/index.js"; import type { FleetLeaseIndex } from "./lease-index.js"; @@ -189,7 +190,8 @@ function sumRamBudget( * §4). It is never built from the fleet's `models` and `runtimes`: one worker having a model and * another having a runtime does not make the pair leasable anywhere. * - * `customModels` lists a model when any worker that lists it marks it custom, and is absent when + * `modelClasses` is the union over workers, the lowest worker id winning a model two of them class + * differently. `customModels` lists a model when any worker that lists it marks it custom, and is absent when * none does. `modelAliases` is the union per model, deduplicated ignoring case. `images` is the union by * runtime, tag, and ABI, and is absent when no worker reports the field at all. Each worker's * lists fit the contract's bounds but their union may not, so both are cut to those bounds after @@ -221,6 +223,11 @@ interface CatalogBucket { images: Map | undefined; /** Models any worker that lists them marks custom. */ readonly customModels: Set; + /** Each model's class, with the worker it came from: the lowest worker id that classes it wins. */ + readonly modelClasses: Map< + string, + { readonly deviceClass: DeviceClass; readonly workerId: string } + >; readonly defaults: Set; } @@ -251,6 +258,7 @@ function addCatalogEntry( defaults: new Set(), images: undefined, modelAliases: new Map>(), + modelClasses: new Map(), modelRuntimes: new Map>(), models: new Map(), runtimes: new Map(), @@ -261,6 +269,7 @@ function addCatalogEntry( for (const model of entry.models) addPairings(bucket.modelRuntimes, entry, model); for (const model of entry.models) addAliases(bucket.modelAliases, entry, model); addCustomModels(bucket.customModels, entry); + addModelClasses(bucket.modelClasses, entry, workerId); if (entry.images !== undefined) bucket.images = addImages(bucket.images, entry, entry.images); bucket.defaults.add(entry.defaultRuntime); } @@ -281,6 +290,28 @@ function addAliases( if (aliases.size > 0) index.set(model, aliases); } +/** + * Folds one worker's classes into the fleet's. A name two workers class differently keeps the + * class of the lower worker id, whatever order the workers were folded in; a name the worker + * does not list itself is dropped. + */ +function addModelClasses( + index: CatalogBucket["modelClasses"], + entry: PlatformCatalog, + workerId: string, +): void { + for (const model of entry.models) { + const deviceClass = Object.hasOwn(entry.modelClasses, model) + ? entry.modelClasses[model] + : undefined; + if (deviceClass === undefined) continue; + const current = index.get(model); + if (current === undefined || workerId < current.workerId) { + index.set(model, { deviceClass, workerId }); + } + } +} + /** Folds one worker's custom models into the fleet's; a name the worker does not list itself is dropped. */ function addCustomModels(index: Set, entry: PlatformCatalog): void { for (const model of entry.customModels ?? []) { @@ -339,6 +370,9 @@ function renderPlatform(platform: Platform, bucket: CatalogBucket): PlatformCata [...aliases.values()].sort().slice(0, CATALOG_LIST_LIMITS.aliasesPerModel), ]), ), + modelClasses: Object.fromEntries( + [...bucket.modelClasses].map(([model, { deviceClass }]) => [model, deviceClass]), + ), modelRuntimes: Object.fromEntries( [...bucket.modelRuntimes].map(([model, paired]) => [model, [...paired].sort()]), ), diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 5badb184d..8174be08e 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -347,6 +347,7 @@ describe("GatewayDispatcher", () => { catalog: [ { modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, models: ["iPhone 17"], platform: "ios", diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index ca0669e11..9322b8d8e 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -104,16 +104,17 @@ 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. + * without `modelAliases` lists no other names, and one without `modelClasses` classes no model. */ export function catalogFixture( - entries: readonly (Omit & - Partial>)[], + entries: readonly (Omit & + Partial>)[], ): CatalogOutput { return { platforms: entries.map((entry) => ({ ...entry, modelAliases: entry.modelAliases ?? {}, + modelClasses: entry.modelClasses ?? {}, modelRuntimes: entry.modelRuntimes ?? Object.fromEntries(entry.models.map((model) => [model, [...entry.runtimes]])), diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index efa82122e..f45ec62d4 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -120,6 +120,7 @@ describe("WorkerRegistry", () => { catalog: [ { modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, models: ["iPhone 17"], platform: "ios", @@ -133,6 +134,7 @@ describe("WorkerRegistry", () => { expect(workers.view("wrk_1")?.catalog).toEqual([ { modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17": ["26.0"] }, models: ["iPhone 17"], platform: "ios", diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 0d9eb4fa3..e367eee26 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -238,6 +238,7 @@ describe("GET /v1/status, /v1/catalog", () => { platforms: [ { defaultRuntime: "26.5", + modelClasses: { "iPhone 17 Pro": "phone" }, models: ["iPhone 17 Pro"], platform: "ios", runtimes: ["26.5"], @@ -248,7 +249,13 @@ describe("GET /v1/status, /v1/catalog", () => { const response = await app.request("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/v1/catalog?platform=ios", { headers: agentAuth }); expect(await response.json()).toEqual({ platforms: [ - { defaultRuntime: "26.5", models: ["iPhone 17 Pro"], platform: "ios", runtimes: ["26.5"] }, + { + defaultRuntime: "26.5", + modelClasses: { "iPhone 17 Pro": "phone" }, + models: ["iPhone 17 Pro"], + platform: "ios", + runtimes: ["26.5"], + }, ], }); }); diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 2bd306558..c8ed36abe 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -14,6 +14,21 @@ import { FakeSimlockClient, sampleGrant } from "./test-support.js"; import { McpSession } from "./session.js"; import { createMcpServer } from "./server.js"; +describe("MCP server list_devices", () => { + it("describes modelClasses to an agent choosing a device", async () => { + const { mcpClient, close } = await connectedServer(new FakeSimlockClient()); + try { + const tools = await mcpClient.request({ method: "tools/list" }, ListToolsResultSchema); + + expect(tools.tools.find((tool) => tool.name === "list_devices")?.description).toContain( + "modelClasses", + ); + } finally { + await close(); + } + }); +}); + describe("MCP server (smoke)", () => { it("advertises exactly the lease, catalog, and status tools, and walks lease -> list -> status -> release", async () => { const client = new FakeSimlockClient(); @@ -25,6 +40,7 @@ describe("MCP server (smoke)", () => { { defaultRuntime: "26.5", modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17 Pro": ["26.5"] }, models: ["iPhone 17 Pro"], platform: "ios", @@ -82,6 +98,7 @@ describe("MCP server (smoke)", () => { { defaultRuntime: "26.5", modelAliases: {}, + modelClasses: {}, modelRuntimes: { "iPhone 17 Pro": ["26.5"] }, models: ["iPhone 17 Pro"], platform: "ios", diff --git a/src/mcp/server.ts b/src/mcp/server.ts index f6d27f906..b6e85e423 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); 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 a model's class (phone, tablet, watch, tv, vision, auto or desktop) where the platform's tools report one, and a model with no entry has none; 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, },