diff --git a/docs/internal/adr/0023-agent-device-is-served-by-an-optional-edge-module.md b/docs/internal/adr/0023-agent-device-is-served-by-an-optional-edge-module.md index ac953d285..fc654393b 100644 --- a/docs/internal/adr/0023-agent-device-is-served-by-an-optional-edge-module.md +++ b/docs/internal/adr/0023-agent-device-is-served-by-an-optional-edge-module.md @@ -71,7 +71,7 @@ An agent-device lease and its simlock lease share one id (the CLI chooses it; ADR 0020 lets simlock keep it) and one lifetime. - `allocate` becomes `lease.request` as the agent's principal, with the - CLI's selectors mapped to `platform`, `model` or `class`, `osVersion` and `imageTag`. A request + CLI's selectors mapped to `platform`, `model` or `class`, `osVersion`, `imageTag` and `baseline` (its `deviceBaseline`). A request that waits in simlock's queue holds the CLI's request open. When the CLI hangs up, the front cancels it; a grant that lands after that is released at once. diff --git a/docs/internal/adr/0061-every-virtual-device-is-a-copy-of-a-source-and-a-baseline-is-a-named-source.md b/docs/internal/adr/0061-every-virtual-device-is-a-copy-of-a-source-and-a-baseline-is-a-named-source.md index 3dc143f88..55f6c5b1a 100644 --- a/docs/internal/adr/0061-every-virtual-device-is-a-copy-of-a-source-and-a-baseline-is-a-named-source.md +++ b/docs/internal/adr/0061-every-virtual-device-is-a-copy-of-a-source-and-a-baseline-is-a-named-source.md @@ -208,7 +208,7 @@ mode, image tag, note, size, saved time and stale reason. A device record carries the baseline name and version it was copied from, or none. A request carries an optional `baseline` name beside its required -`platform` (CLI `--baseline`, `SIMLOCK_BASELINE`, HTTP, MCP, the client). +`platform` (CLI `--baseline`, `SIMLOCK_BASELINE`, HTTP, MCP, the client, agent-device's `deviceBaseline`). `fits` and `sameSpec` compare it like the image tag: unset matches only unset, a name matches only that name. A request naming a baseline takes the baseline's model, OS, mode and image tag; a request whose platform, model, @@ -218,8 +218,9 @@ OS, mode or image tag differs from the baseline's fails at once stale. One function decides a mismatch, and the worker and the gateway both call it. A device of an older version than the baseline's current one is never granted. A grant and `lease.granted` carry the -baseline name and version. agent-device does not send a baseline yet; that -is a later change on both sides. +baseline name and version. The agent-device front maps `deviceBaseline` to +`baseline`, sends no class beside it, and adds the baseline to the reply's +`data.lease.device`. A learned warm kind carries the baseline name, so the pool keeps baseline devices warm with no configuration. diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index 106037843..594bbd1d8 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -91,13 +91,13 @@ under leasing's signal (`lease.endWaitMs`). ## Flow: agent on a worker 1. CLI `open` → `POST /v1/agent-device/rpc` `agent_device.lease.allocate` with its lease id. -2. Front refuses a non-plain lease, no `--platform`, a bad `ttlMs`, no lease id, a `physical` that is not a boolean, or a `--target` it does not map. +2. Front refuses a non-plain lease, no `--platform`, a bad `ttlMs`, no lease id, a `physical` that is not a boolean, a `deviceBaseline` that is not text, or a `--target` it does not map. 3. `lease.request`: `leaseId` = `requesterId` = the CLI's lease id; `--device` → model, - `--target` → class, `--os` → `osVersion`, `--image-tag` → `imageTag`, `physical: true` → `physical: true` (Simlock picks an enrolled phone); TTL = sent, capped by `capabilities.agent-device.leaseTtlCapMs`, at least 5 s; + `--target` → class, `--os` → `osVersion`, `--image-tag` → `imageTag`, `deviceBaseline` → `baseline` (and then no class from `--target`), `physical: true` → `physical: true` (Simlock picks an enrolled phone); TTL = sent, capped by `capabilities.agent-device.leaseTtlCapMs`, at least 5 s; queue wait 330 s. CLI hangs up → `lease.cancel`, retried every 1 s. 4. Grant → allocate forwarded with the device address (`udid`/`serial`; a phone's is its enrolled id), to the phone daemon for a phone and the simulator daemon otherwise (`RoutedHostLink`, which remembers each lease's daemon until the lease ends), no - `device`/`deviceKey`/`target`/`osVersion`/`imageTag`/`physical` (commands lose both keys too), `ttlMs` = max(24 h, 2 × `lease.maxTtlMs`). -5. agent-device error → simlock lease released. Success → front map entry; reply relayed with `data.lease.device` `{ model, osVersion, physical, imageTag? }` added from the grant. + `device`/`deviceKey`/`target`/`osVersion`/`imageTag`/`deviceBaseline`/`physical` (commands lose `osVersion`, `imageTag` and `deviceBaseline` too), `ttlMs` = max(24 h, 2 × `lease.maxTtlMs`). +5. agent-device error → simlock lease released. Success → front map entry; reply relayed with `data.lease.device` `{ model, osVersion, physical, imageTag?, baseline? { name, version } }` added from the grant. 6. Commands carry the lease id; rules check, renewals run, `devices` filtered. 7. Release → agent-device first, then `lease.release` → the device is deleted; lease-end finds no scope left. @@ -140,7 +140,7 @@ Local profile: a standalone worker with HTTP and this module on keeps ` { + const grant = await rig.daemon.dispatch("lease.request", spec, sessionFor(principals.one)); + await rig.daemon.dispatch("baseline.save", { leaseId: grant.lease.id, name }, adminSession); +} + +describe("the agent-device front's `deviceBaseline`", () => { + it('allocate with `deviceBaseline` "logged-in" makes a lease request with `baseline: "logged-in"`, alone on iOS and (a baseline of its own) on Android, with `target: "mobile"` (no class) and with `device` (the model too)', async () => { + const rig = await setUp({ + drivers: (clock) => [iosDriver(clock), androidDriver(clock)], + maxRunning: 8, + }); + await saveBaseline(rig, "logged-in", { model: "iPhone 17 Pro", platform: "ios" }); + await saveBaseline(rig, "logged-in-android", { model: "Pixel 8", platform: "android" }); + const cases = [ + [1, { platform: "ios" }, { baseline: "logged-in", platform: "ios" }], + [ + 2, + { deviceBaseline: "logged-in-android", platform: "android" }, + { baseline: "logged-in-android", platform: "android" }, + ], + [3, { platform: "ios", target: "mobile" }, { baseline: "logged-in", platform: "ios" }], + [ + 4, + { device: "iPhone 17 Pro", platform: "ios" }, + { baseline: "logged-in", model: "iPhone 17 Pro", platform: "ios" }, + ], + ] as const; + + for (const [n, extra, spec] of cases) { + await granted(rig, n, { deviceBaseline: "logged-in", ...extra }); + expect(await requestedSpecs(rig, hex(n))).toEqual([spec]); + } + }); + + it("the allocate the agent-device daemon receives carries no `deviceBaseline`", async () => { + const rig = await setUp({ drivers: (clock) => [androidDriver(clock)], maxRunning: 8 }); + await saveBaseline(rig, "logged-in", { model: "Pixel 8", platform: "android" }); + + await granted(rig, 1, { deviceBaseline: "logged-in", platform: "android" }); + + expect(receivedAllocate(rig, 1)).not.toHaveProperty("deviceBaseline"); + }); + + it("the relayed allocate reply carries `data.lease.device.baseline` as `{ name, version }` for a grant from a baseline, with the daemon's `deviceKey` and `data.device` unchanged", async () => { + const rig = await setUp(); + await saveBaseline(rig, "logged-in", { model: "iPhone 16", platform: "ios" }); + await saveBaseline(rig, "logged-in", { model: "iPhone 16", platform: "ios" }); + rig.fake.nameDeviceKeyInNextReply("key-1"); + rig.fake.nameDeviceInNextReply({}); + + const result = (await envelopeOf(await allocate(rig, 1, { deviceBaseline: "logged-in" }))) + .result as { data: { device: unknown; lease: Record } }; + + expect(result.data.lease["device"]).toEqual({ + baseline: { name: "logged-in", version: 2 }, + model: "iPhone 16", + osVersion: "26.5", + physical: false, + }); + expect(result.data.lease["deviceKey"]).toBe("key-1"); + expect(result.data.device).toMatchObject({ id: expect.any(String) }); + }); + + it("allocate with a `deviceBaseline` Simlock refuses (unknown, model or platform mismatch, stale, an invalid name, beside `physical`) answers `refused by simlock:` with simlock's own message and leaves no lease", async () => { + const rig = await setUp({ drivers: (clock) => [iosDriver(clock), androidDriver(clock)] }); + await saveBaseline(rig, "logged-in", { model: "iPhone 16", platform: "ios" }); + await saveBaseline(rig, "went-stale", { model: "iPhone 16", platform: "ios" }); + const sources = await rig.driver.listSources(); + const [, staleSource] = sources; + rig.driver.setSources( + sources.map((source) => + source === staleSource ? { ...source, staleReason: "runtime is not installed" } : source, + ), + ); + await rig.daemon.dispatch("baseline.list", {}, adminSession); + const refusals: readonly (readonly [Record, Record])[] = [ + [{ deviceBaseline: "no-such" }, { baseline: "no-such" }], + [ + { device: "iPhone 17 Pro", deviceBaseline: "logged-in" }, + { baseline: "logged-in", model: "iPhone 17 Pro" }, + ], + [ + { deviceBaseline: "logged-in", platform: "android" }, + { baseline: "logged-in", platform: "android" }, + ], + [{ deviceBaseline: "went-stale" }, { baseline: "went-stale" }], + [{ deviceBaseline: "Logged In" }, { baseline: "Logged In" }], + [ + { deviceBaseline: "logged-in", physical: true }, + { baseline: "logged-in", physical: true }, + ], + ]; + const before = (await leases(rig)).length; + + for (const [index, [extra, spec]] of refusals.entries()) { + const expected = await simlockMessage(rig, { + leaseId: hex(190 + index), + platform: "ios", + ...spec, + }); + const answer = await envelopeOf(await allocate(rig, 100 + index, extra)); + expect(answer.error?.message).toBe(`refused by simlock: ${expected}`); + } + expect((await leases(rig)).length).toBe(before); + expect(allocatesReceived(rig)).toEqual([]); + }); + + it('allocate with `target: "watch"` beside a `deviceBaseline` answers `refused: unknown --target watch; use mobile, tv or desktop` and leaves no lease', async () => { + const rig = await setUp(); + + const answer = await envelopeOf( + await allocate(rig, 1, { deviceBaseline: "logged-in", target: "watch" }), + ); + + expect(answer.error).toMatchObject( + refusal("refused: unknown --target watch; use mobile, tv or desktop"), + ); + expect(await leases(rig)).toEqual([]); + expect(allocatesReceived(rig)).toEqual([]); + }); + + it("a command with `deviceBaseline` on `flags`, on `input` or inside a batch step reaches agent-device without it", async () => { + const rig = await setUp(); + await granted(rig, 1); + const sent = { deviceBaseline: "logged-in", platform: "ios" }; + + const onFlags = await forwarded(rig, () => runCommand(rig, "snapshot", 1, { flags: sent })); + const onInput = await forwarded(rig, () => runCommand(rig, "snapshot", 1, { input: sent })); + const inStep = await forwarded(rig, () => + runCommand(rig, "batch", 1, { + flags: { batchSteps: [{ command: "snapshot", flags: sent }] }, + }), + ); + + expect(onFlags["flags"]).toEqual({ platform: "ios" }); + expect(onInput["input"]).toEqual({ platform: "ios" }); + const steps = (inStep["flags"] as { batchSteps: { flags: unknown }[] }).batchSteps; + expect(steps[0]?.flags).toEqual({ platform: "ios" }); + }); + + it("allocate with a `deviceBaseline` that is a number is refused with `refused: malformed deviceBaseline`", async () => { + const rig = await setUp(); + + await refused( + rig, + () => allocate(rig, 1, { deviceBaseline: 7 }), + "refused: malformed deviceBaseline", + ); + }); +}); diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 02369af9d..a4055dca1 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -1,264 +1,55 @@ import { createHash } from "node:crypto"; -import { mkdtemp, rm } from "node:fs/promises"; -import { createServer } from "node:net"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { afterEach, describe, expect, it, vi } from "vitest"; - -import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; -import { NodeSqliteOpener } from "../ports/index.js"; -import { startDaemon, type StartDaemonOptions } from "../daemon/main.js"; -import type { DaemonServer } from "../daemon/server.js"; -import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; -import { seedTokensDatabase } from "../auth/testing.js"; -import { agentDeviceModuleWith, FakeAgentDevice } from "./testing.js"; - -const runningDaemons: DaemonServer[] = []; -const temporaryDirectories: string[] = []; - -afterEach(async () => { - await Promise.all(runningDaemons.splice(0).map((daemon) => daemon.stop("test"))); - await Promise.all( - temporaryDirectories.splice(0).map((path) => rm(path, { force: true, recursive: true })), - ); -}); - -const secrets = { - one: "slk_test_agent_one", - operator: "slk_test_operator", - two: "slk_test_agent_two", - worker: "slk_test_worker_join", -} as const; -const principals = { one: "tok_one", two: "tok_two" } as const; - -const notAvailable = "agent-device is not available on this simlock: "; -const agentTokenOnly = "refused: agent-device through simlock needs an agent token"; -const queueTimeoutMessage = "timed out waiting for a device; nothing was leased"; -const defaultTtlMs = 600_000; -const maxTtlMs = 1_800_000; -const scope = { clientId: "client-1", leaseProvider: "proxy", runId: "run-1" } as const; - -const adminSession = { - manageEventSubscription: () => undefined, - via: "socket", - principal: "admin", - role: "admin", -} as const; - -function sessionFor(principal: string) { - return { - manageEventSubscription: () => undefined, - via: "socket", - principal, - role: "agent", - } as const; -} - -interface Envelope { - readonly id?: unknown; - readonly jsonrpc?: string; - readonly result?: Record; - readonly error?: { - readonly code: number; - readonly message: string; - readonly data?: { readonly code: string; readonly message: string }; - }; -} - -interface SetUpOptions { - readonly leaseTtlCapMs?: number; - readonly downloads?: "always"; - readonly drivers?: (clock: FakeClock) => FakeDriver[]; - readonly enabled?: boolean | "unset"; - readonly endWaitMs?: number; - readonly gatewayMode?: boolean; - readonly maxRunning?: number; - readonly slowStart?: boolean; - readonly upstream?: FakeAgentDevice; - readonly phoneUpstream?: FakeAgentDevice; -} - -interface Rig { - readonly clock: FakeClock; - readonly daemon: DaemonServer; - readonly driver: FakeDriver; - readonly fake: FakeAgentDevice; - readonly phone: FakeAgentDevice; - readonly filesystem: MemoryFilesystem; - readonly logs: MemoryLogSink; - readonly origin: string; - readonly stateDbPath: string; - readonly started: Promise; - readonly restart: (between?: () => void) => Promise; -} +import { describe, expect, it, vi } from "vitest"; + +import { FakeDriver } from "../core/testing.js"; +import { FakeClock, NodeSqliteOpener } from "../ports/index.js"; +import { FakeAgentDevice } from "./testing.js"; +import { + secrets, + principals, + notAvailable, + agentTokenOnly, + queueTimeoutMessage, + defaultTtlMs, + maxTtlMs, + scope, + adminSession, + sessionFor, + type Envelope, + type SetUpOptions, + type Rig, + iosDriver, + androidDriver, + taggedAndroidDriver, + sleep, + setUp, + type SendOptions, + send, + rpcBody, + rpc, + bodyOf, + envelopeOf, + hex, + allocateParams, + allocate, + granted, + command, + leases, + requestedSpecs, + receivedAllocate, + allocatesReceived, + simlockMessage, + refusal, + runCommand, + forwarded, + refused, +} from "./test-support.js"; const phoneModels = { defaultModels: { phone: ["iPhone 16"] }, modelClasses: { "iPhone 16": "phone" }, } as const; -function iosDriver(clock: FakeClock): FakeDriver { - return new FakeDriver({ - availableOsVersions: ["26.5"], - clock, - defaultModels: { desktop: ["Mac"], phone: ["iPhone 16"], tv: ["Apple TV 4K"] }, - knownModels: ["iPhone 16", "iPhone 17 Pro", "Apple TV 4K", "Mac"], - modelClasses: { - "Apple TV 4K": "tv", - "iPhone 16": "phone", - "iPhone 17 Pro": "phone", - Mac: "desktop", - }, - platform: "ios", - }); -} - -function androidDriver(clock: FakeClock): FakeDriver { - return new FakeDriver({ - availableOsVersions: ["35"], - clock, - defaultModels: { phone: ["Pixel 8"] }, - knownModels: ["Pixel 8"], - modelAliases: { "Pixel 8": ["P8"] }, - modelClasses: { "Pixel 8": "phone" }, - platform: "android", - }); -} - -function taggedAndroidDriver(clock: FakeClock): FakeDriver { - return new FakeDriver({ - availableOsVersions: ["33", "34", "35"], - clock, - defaultModels: { phone: ["Pixel 8"] }, - images: [ - { abi: "arm64-v8a", runtime: "33", tag: "google_apis_playstore" }, - { abi: "arm64-v8a", runtime: "34", tag: "google_apis_playstore" }, - { abi: "arm64-v8a", runtime: "35", tag: "default" }, - ], - knownModels: ["Pixel 8"], - modelClasses: { "Pixel 8": "phone" }, - platform: "android", - }); -} - -async function freeLoopbackPort(): Promise { - const server = createServer(); - await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); - const address = server.address(); - await new Promise((resolve) => server.close(() => resolve())); - if (typeof address !== "object" || address === null) throw new Error("no port bound"); - return address.port; -} - -async function sleep(ms: number): Promise { - await new Promise((resolve) => setTimeout(resolve, ms)); -} - -async function setUp(options: SetUpOptions = {}): Promise { - const directory = await mkdtemp(join(tmpdir(), "simlock-agent-device-edge-")); - temporaryDirectories.push(directory); - const clock = new FakeClock(1_000); - const filesystem = new MemoryFilesystem(); - await seedTokensDatabase(directory, [ - [principals.one, secrets.one, "agent"], - [principals.two, secrets.two, "agent"], - ["tok_operator", secrets.operator, "operator"], - ["tok_worker", secrets.worker, "worker"], - ]); - const port = await freeLoopbackPort(); - const fake = options.upstream ?? new FakeAgentDevice(); - const phone = options.phoneUpstream ?? new FakeAgentDevice(); - const drivers = options.drivers?.(clock) ?? [iosDriver(clock)]; - const stateDbPath = join(directory, "state.db"); - const logs = new MemoryLogSink(); - const launch = () => - startDaemon({ - clock, - configOverrides: { - ...(options.enabled === "unset" - ? {} - : { - capabilities: { - "agent-device": { - enabled: options.enabled ?? true, - ...(options.leaseTtlCapMs === undefined - ? {} - : { leaseTtlCapMs: options.leaseTtlCapMs }), - }, - }, - }), - capacity: { config: { maxRunning: options.maxRunning ?? 4 }, strategy: "fixed" }, - ...(options.downloads === undefined ? {} : { downloads: { policy: options.downloads } }), - http: { enabled: true, host: "127.0.0.1", port }, - lease: { - defaultTtlMs, - maxTtlMs, - ...(options.endWaitMs === undefined ? {} : { endWaitMs: options.endWaitMs }), - }, - }, - ...(options.gatewayMode === true ? { role: "gateway" as const } : {}), - dataDirectory: directory, - deviceDataTables: fakeDeviceDataTables, - drivers, - filesystem, - logger: new JsonLinesLogger({ clock, level: "debug", sink: logs }), - optionalModules: [agentDeviceModuleWith({ phoneUpstream: phone, upstream: fake })], - version: "1.2.3", - } as StartDaemonOptions).then((daemon) => { - runningDaemons.push(daemon); - return daemon; - }); - const started = launch(); - const origin = `http://127.0.0.1:${port}`; - if (options.slowStart === true) { - await waitListening(origin); - return { - clock, - daemon: undefined as never, - driver: drivers[0] as FakeDriver, - fake, - phone, - filesystem, - logs, - origin, - restart: () => Promise.reject(new Error("restart needs a started daemon")), - started, - stateDbPath, - }; - } - const rigFor = (daemon: DaemonServer, running: Promise): Rig => ({ - clock, - daemon, - driver: drivers[0] as FakeDriver, - fake, - phone, - filesystem, - logs, - origin, - restart: async (between) => { - await daemon.stop("test"); - between?.(); - const next = await launch(); - return rigFor(next, Promise.resolve(next)); - }, - started: running, - stateDbPath, - }); - return rigFor(await started, started); -} - -async function waitListening(origin: string): Promise { - for (let attempt = 0; attempt < 400; attempt += 1) { - try { - await fetch(`${origin}/v1/healthz`); - return; - } catch { - await sleep(5); - } - } - throw new Error("the daemon never listened"); -} - const phoneSerial = "R58Y61A60HN"; // why: one Android driver serving a virtual Pixel 8 and an enrolled, present phone, so a test can lease either through the same worker. @@ -295,122 +86,10 @@ async function advance(rig: Rig, ms: number, step = 1_000): Promise { } } -interface SendOptions { - readonly body?: string; - readonly headers?: Record; - readonly method?: string; - readonly signal?: AbortSignal; - readonly token?: string | null; -} - -function send(rig: Rig, path: string, options: SendOptions = {}): Promise { - const token = options.token === undefined ? secrets.one : options.token; - return fetch(`${rig.origin}/v1/agent-device${path}`, { - ...(options.body === undefined ? {} : { body: options.body }), - headers: { - // why: a pooled socket to a daemon the test restarted on the same port is closed by the server, so a request must not reuse one. - connection: "close", - ...(token === null ? {} : { authorization: `Bearer ${token}` }), - ...(options.body === undefined ? {} : { "content-type": "application/json" }), - ...options.headers, - }, - method: options.method ?? (options.body === undefined ? "GET" : "POST"), - ...(options.signal === undefined ? {} : { signal: options.signal }), - }); -} - -function rpcBody(method: string, params: Record, id: unknown = 1): string { - return JSON.stringify({ id, jsonrpc: "2.0", method, params }); -} - -function rpc( - rig: Rig, - method: string, - params: Record, - options: Omit & { readonly id?: unknown } = {}, -): Promise { - return send(rig, "/rpc", { ...options, body: rpcBody(method, params, options.id ?? 1) }); -} - -async function bodyOf(response: Response): Promise> { - const text = await response.text(); - expect( - text.trimStart().startsWith("{"), - `expected a JSON object body, got ${response.status} ${text.slice(0, 80)}`, - ).toBe(true); - return JSON.parse(text) as Record; -} - -async function envelopeOf(response: Response): Promise { - return (await bodyOf(response)) as Envelope; -} - -const hex = (n: number): string => n.toString(16).padStart(32, "0"); - -function allocateParams(n: number, extra: Record = {}): Record { - return { ...scope, leaseId: hex(n), platform: "ios", ttlMs: 120_000, ...extra }; -} - -function allocate( - rig: Rig, - n: number, - extra: Record = {}, - options: Omit = {}, -): Promise { - return rpc(rig, "agent_device.lease.allocate", allocateParams(n, extra), options); -} - -async function granted( - rig: Rig, - n: number, - extra: Record = {}, - options: Omit = {}, -): Promise { - const answer = await envelopeOf(await allocate(rig, n, extra, options)); - expect(answer.result).toMatchObject({ ok: true }); -} - function release(rig: Rig, n: number, options: Omit = {}): Promise { return rpc(rig, "agent_device.lease.release", { ...scope, leaseId: hex(n) }, options); } -function command( - rig: Rig, - name: string, - n: number | undefined, - options: Omit = {}, - extra: Record = {}, -): Promise { - return rpc( - rig, - "agent_device.command", - { - command: name, - ...(n === undefined ? {} : { meta: { leaseId: hex(n) } }), - ...extra, - }, - options, - ); -} - -interface LeaseView { - readonly id: string; - readonly deviceId: string; - readonly requesterId: string; - readonly ownerId: string; - readonly ttlMs: number; - readonly ttlDeadline: number; - readonly lastRenewedAt: number; -} - -async function leases(rig: Rig): Promise { - return (await rig.daemon.dispatch( - "list.get", - { kind: "leases" }, - adminSession, - )) as unknown as readonly LeaseView[]; -} - async function waiting( rig: Rig, ): Promise { @@ -433,42 +112,12 @@ async function devices(rig: Rig): Promise< return (await rig.daemon.dispatch("list.get", { kind: "devices" }, adminSession)) as never; } -async function requestedSpecs(rig: Rig, requester: string): Promise { - const events = await rig.daemon.dispatch("events.replay", {}, adminSession); - return events - .filter((entry) => entry.event === "lease.requested") - .map((entry) => entry.payload as { requester: string; requestSpec: unknown }) - .filter((payload) => payload.requester === requester) - .map((payload) => payload.requestSpec); -} - async function grantedDevice(rig: Rig) { const [device] = await devices(rig); expect(device?.address).toBeDefined(); return device as { readonly address: string; readonly driverDeviceId?: string }; } -function receivedAllocate(rig: Rig, n: number): Record { - const params = allocatesReceived(rig, n)[0]?.params; - expect(params).toBeDefined(); - return params as Record; -} - -function allocatesReceived(rig: Rig, n?: number) { - return rig.fake - .rpcRequests("agent_device.lease.allocate") - .filter((request) => n === undefined || request.params?.["leaseId"] === hex(n)); -} - -async function simlockMessage(rig: Rig, input: Record): Promise { - try { - await rig.daemon.dispatch("lease.request", input, sessionFor(principals.one)); - } catch (error) { - return (error as Error).message; - } - throw new Error("simlock accepted a request the test expected it to refuse"); -} - function track(promise: Promise): { readonly done: () => boolean; readonly promise: Promise; @@ -481,10 +130,6 @@ function track(promise: Promise): { return { done: () => settled, promise: tracked }; } -function refusal(message: string, code = "INVALID_ARGS") { - return { code: -32000, data: { code, message }, message }; -} - const endedMessage = "lease ended by simlock; run disconnect, then open"; function heartbeat( @@ -3314,22 +2959,6 @@ const allowlistRefusal = const bothDrivers = (clock: FakeClock): FakeDriver[] => [iosDriver(clock), androidDriver(clock)]; -function runCommand( - rig: Rig, - name: string, - n: number | undefined, - fields: Record = {}, - options: Omit = {}, -): Promise { - const { meta, ...rest } = fields; - return command(rig, name, undefined, options, { - ...(n === undefined && meta === undefined - ? {} - : { meta: { ...(n === undefined ? {} : { leaseId: hex(n) }), ...(meta as object) } }), - ...rest, - }); -} - // why: the fake agent-device names the device it leases `simlock-`, as the real one does. function nameOf(rig: Rig, n: number): string { return `simlock-${idOf(rig, n)}`; @@ -3344,32 +2973,6 @@ function commandsReceived(rig: Rig) { return rig.fake.rpcRequests("agent_device.command"); } -// why: a refusal test starts from a request that is accepted, then changes one thing (testing rule 2). -async function forwarded( - rig: Rig, - send: () => Promise, -): Promise> { - const before = rig.fake.requests.length; - const answer = await envelopeOf(await send()); - expect(answer.error).toBeUndefined(); - expect(answer.result).toBeDefined(); - // why: the front reads a leased device's name from agent-device's device list the first time a rule needs it, before it forwards the command. - const sent = rig.fake.requests.slice(before).filter((r) => r.params?.["command"] !== "devices"); - expect(sent.length).toBe(1); - return sent[0]?.params as Record; -} - -async function refused(rig: Rig, send: () => Promise, message: string): Promise { - const before = rig.fake.requests.length; - const answer = await envelopeOf(await send()); - expect(answer.error).toMatchObject(refusal(message)); - expect(answer.result).toBeUndefined(); - // why: a refusal can follow the front's one read of a leased device's name from agent-device's device list; no command reaches it. - expect( - rig.fake.requests.slice(before).filter((r) => r.params?.["command"] !== "devices"), - ).toEqual([]); -} - function flagsOf(params: Record): Record { return (params["flags"] ?? {}) as Record; } diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index e91c115ce..ab0685a58 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -49,6 +49,7 @@ interface Plan { readonly leaseId: string; readonly platform: "ios" | "android"; readonly model?: string; + readonly baseline?: string; readonly class?: "phone" | "tv" | "desktop"; readonly imageTag?: string; readonly osVersion?: string; @@ -122,16 +123,23 @@ function stringFields(fields: ReturnType) { }; } +// why: a named model wins over a class, and a baseline names a device of its own, so it replaces the class and rides beside a model. +function chosenDevice(fields: ReturnType) { + const { device, deviceBaseline, target } = fields; + const baseline = typeof deviceBaseline === "string" ? { baseline: deviceBaseline } : {}; + if (typeof device === "string" && device !== "") return { model: device, ...baseline }; + if (typeof deviceBaseline === "string") return baseline; + const klass = typeof target === "string" ? CLASS_OF_TARGET[target] : undefined; + return klass === undefined ? {} : { class: klass }; +} + function planOf(params: Record, cap: number | undefined): Plan { const fields = leaseCallFields(params); - const device = - typeof fields.device === "string" && fields.device !== "" ? fields.device : undefined; - const klass = typeof fields.target === "string" ? CLASS_OF_TARGET[fields.target] : undefined; const ttlMs = chosenTtl(fields.ttlMs, cap); return { leaseId: fields.leaseId as string, platform: fields.platform as "ios" | "android", - ...(device === undefined ? (klass === undefined ? {} : { class: klass }) : { model: device }), + ...chosenDevice(fields), ...stringFields(fields), ...(params["physical"] === true ? { physical: true as const } : {}), ...(ttlMs === undefined ? {} : { ttlMs }), @@ -267,6 +275,7 @@ function forwardedBody( ) { const { device: _device, + deviceBaseline: _deviceBaseline, deviceKey: _deviceKey, imageTag: _imageTag, osVersion: _osVersion, @@ -407,6 +416,7 @@ function withGrantedDevice( osVersion: spec.osVersion, physical: spec.physical, ...(spec.imageTag === undefined ? {} : { imageTag: spec.imageTag }), + ...(spec.baseline === undefined ? {} : { baseline: spec.baseline }), }; return { ...reply, text: JSON.stringify(body) }; } diff --git a/src/agent-device/front/request-rules.ts b/src/agent-device/front/request-rules.ts index 2ff4e0325..64a658304 100644 --- a/src/agent-device/front/request-rules.ts +++ b/src/agent-device/front/request-rules.ts @@ -133,11 +133,11 @@ function checkTypes(unit: Unit): void { } } -// why: the daemon behind the front does not know these two keys, so a request that is not the flat allocate form must not carry them; the flat allocate is exempt because simlock reads them from it. +// why: the daemon behind the front does not know these three keys, so a request that is not the flat allocate form must not carry them; the flat allocate is exempt because simlock reads them from it. function ruleLeaseKeys(check: Check, unit: Unit): void { if (isFlat(unit)) return; for (const place of places(unit)) { - for (const key of ["osVersion", "imageTag"]) { + for (const key of ["osVersion", "imageTag", "deviceBaseline"]) { if (!(key in place)) continue; delete place[key]; check.changed = true; diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index f76235f16..13a60d501 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -906,16 +906,40 @@ describe("the agent-device front, through a gateway", { timeout: 60_000 }, () => expect(reached()).toBe(4); }); - it('allocate through the gateway with `osVersion` ">=18" reaches the lease request with it and `requires: ["agent-device"]`, and the reply carries `data.lease.device`', async () => { + it('allocate through the gateway with `osVersion` ">=18" or a `deviceBaseline` reaches the lease request with it and `requires: ["agent-device"]`, and the reply carries `data.lease.device` (with `baseline` for the baseline); an unknown `deviceBaseline` answers `refused by simlock:`', async () => { const rig = await setUp(); const tap = tapDispatch(rig.gateway); + const worker = await first(rig).daemon; + const held = await worker.dispatch( + "lease.request", + { platform: "ios" }, + sessionFor(principals.one), + ); + await worker.dispatch( + "baseline.save", + { leaseId: held.lease.id, name: "logged-in" }, + adminSession, + ); + await expect + .poll(async () => + (await rig.gateway.dispatch("baseline.list", {}, adminSession)).baselines.map( + (entry) => entry.name, + ), + ) + .toEqual(["logged-in"]); const answer = await envelopeOf(await allocate(rig, 1, { osVersion: ">=18" })); - - const request = tap.inputs.find((entry) => entry.operation === "lease.request"); - expect(request?.input).toMatchObject({ osVersion: ">=18", requires: ["agent-device"] }); - const lease = (answer.result as { data: { lease: Record } }).data.lease; - expect(lease["device"]).toMatchObject({ osVersion: "26.5" }); + const based = await envelopeOf(await allocate(rig, 2, { deviceBaseline: "logged-in" })); + const unknown = await envelopeOf(await allocate(rig, 3, { deviceBaseline: "no-such" })); + + const requests = tap.inputs.filter((entry) => entry.operation === "lease.request"); + expect(requests[0]?.input).toMatchObject({ osVersion: ">=18", requires: ["agent-device"] }); + expect(requests[1]?.input).toMatchObject({ baseline: "logged-in", requires: ["agent-device"] }); + const leaseOf = (reply: typeof answer) => + (reply.result as { data: { lease: Record } }).data.lease; + expect(leaseOf(answer)["device"]).toMatchObject({ osVersion: "26.5" }); + expect(leaseOf(based)["device"]).toMatchObject({ baseline: { name: "logged-in", version: 1 } }); + expect(unknown.error?.message).toContain("refused by simlock: "); }); it("allocate on a worker, directly, sends no `requires`, as today", async () => { diff --git a/src/agent-device/shared/rpc.ts b/src/agent-device/shared/rpc.ts index e168d9e7f..501e89489 100644 --- a/src/agent-device/shared/rpc.ts +++ b/src/agent-device/shared/rpc.ts @@ -98,11 +98,13 @@ export interface LeaseCallFields { readonly deviceKey: unknown; readonly imageTag: unknown; readonly osVersion: unknown; + readonly deviceBaseline: unknown; } export function leaseCallFields(params: Record): LeaseCallFields { return { device: params["device"], + deviceBaseline: params["deviceBaseline"], deviceKey: params["deviceKey"], imageTag: params["imageTag"], leaseId: params["leaseId"], diff --git a/src/agent-device/shared/selectors.ts b/src/agent-device/shared/selectors.ts index 2165003fe..85ed718eb 100644 --- a/src/agent-device/shared/selectors.ts +++ b/src/agent-device/shared/selectors.ts @@ -17,6 +17,7 @@ const STRING_FIELDS = [ "deviceKey", "osVersion", "imageTag", + "deviceBaseline", ] as const; const BOOLEAN_FIELDS = ["physical"] as const; const INTEGER_FIELDS = ["shardAll", "shardSplit"] as const; diff --git a/src/agent-device/test-support.ts b/src/agent-device/test-support.ts new file mode 100644 index 000000000..deb5482b9 --- /dev/null +++ b/src/agent-device/test-support.ts @@ -0,0 +1,449 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect } from "vitest"; + +import { FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; +import { startDaemon, type StartDaemonOptions } from "../daemon/main.js"; +import type { DaemonServer } from "../daemon/server.js"; +import { FakeClock, JsonLinesLogger, MemoryFilesystem, MemoryLogSink } from "../ports/index.js"; +import { seedTokensDatabase } from "../auth/testing.js"; +import { agentDeviceModuleWith, FakeAgentDevice } from "./testing.js"; + +// why: the edge tests and the baseline tests share one daemon rig; its daemons and data directories are cleaned after each test of whichever file imports it. +afterEach(async () => { + await Promise.all(runningDaemons.splice(0).map((daemon) => daemon.stop("test"))); + await Promise.all( + temporaryDirectories.splice(0).map((path) => rm(path, { force: true, recursive: true })), + ); +}); + +const runningDaemons: DaemonServer[] = []; +const temporaryDirectories: string[] = []; + +export const secrets = { + one: "slk_test_agent_one", + operator: "slk_test_operator", + two: "slk_test_agent_two", + worker: "slk_test_worker_join", +} as const; +export const principals = { one: "tok_one", two: "tok_two" } as const; + +export const notAvailable = "agent-device is not available on this simlock: "; +export const agentTokenOnly = "refused: agent-device through simlock needs an agent token"; +export const queueTimeoutMessage = "timed out waiting for a device; nothing was leased"; +export const defaultTtlMs = 600_000; +export const maxTtlMs = 1_800_000; +export const scope = { clientId: "client-1", leaseProvider: "proxy", runId: "run-1" } as const; + +export const adminSession = { + manageEventSubscription: () => undefined, + via: "socket", + principal: "admin", + role: "admin", +} as const; + +export function sessionFor(principal: string) { + return { + manageEventSubscription: () => undefined, + via: "socket", + principal, + role: "agent", + } as const; +} + +export interface Envelope { + readonly id?: unknown; + readonly jsonrpc?: string; + readonly result?: Record; + readonly error?: { + readonly code: number; + readonly message: string; + readonly data?: { readonly code: string; readonly message: string }; + }; +} + +export interface SetUpOptions { + readonly leaseTtlCapMs?: number; + readonly downloads?: "always"; + readonly drivers?: (clock: FakeClock) => FakeDriver[]; + readonly enabled?: boolean | "unset"; + readonly endWaitMs?: number; + readonly gatewayMode?: boolean; + readonly maxRunning?: number; + readonly slowStart?: boolean; + readonly upstream?: FakeAgentDevice; + readonly phoneUpstream?: FakeAgentDevice; +} + +export interface Rig { + readonly clock: FakeClock; + readonly daemon: DaemonServer; + readonly driver: FakeDriver; + readonly fake: FakeAgentDevice; + readonly phone: FakeAgentDevice; + readonly filesystem: MemoryFilesystem; + readonly logs: MemoryLogSink; + readonly origin: string; + readonly stateDbPath: string; + readonly started: Promise; + readonly restart: (between?: () => void) => Promise; +} + +export function iosDriver(clock: FakeClock): FakeDriver { + return new FakeDriver({ + availableOsVersions: ["26.5"], + clock, + defaultModels: { desktop: ["Mac"], phone: ["iPhone 16"], tv: ["Apple TV 4K"] }, + knownModels: ["iPhone 16", "iPhone 17 Pro", "Apple TV 4K", "Mac"], + modelClasses: { + "Apple TV 4K": "tv", + "iPhone 16": "phone", + "iPhone 17 Pro": "phone", + Mac: "desktop", + }, + platform: "ios", + }); +} + +export function androidDriver(clock: FakeClock): FakeDriver { + return new FakeDriver({ + availableOsVersions: ["35"], + clock, + defaultModels: { phone: ["Pixel 8"] }, + knownModels: ["Pixel 8"], + modelAliases: { "Pixel 8": ["P8"] }, + modelClasses: { "Pixel 8": "phone" }, + platform: "android", + }); +} + +export function taggedAndroidDriver(clock: FakeClock): FakeDriver { + return new FakeDriver({ + availableOsVersions: ["33", "34", "35"], + clock, + defaultModels: { phone: ["Pixel 8"] }, + images: [ + { abi: "arm64-v8a", runtime: "33", tag: "google_apis_playstore" }, + { abi: "arm64-v8a", runtime: "34", tag: "google_apis_playstore" }, + { abi: "arm64-v8a", runtime: "35", tag: "default" }, + ], + knownModels: ["Pixel 8"], + modelClasses: { "Pixel 8": "phone" }, + platform: "android", + }); +} + +async function freeLoopbackPort(): Promise { + const server = createServer(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + await new Promise((resolve) => server.close(() => resolve())); + if (typeof address !== "object" || address === null) throw new Error("no port bound"); + return address.port; +} + +export async function sleep(ms: number): Promise { + await new Promise((resolve) => setTimeout(resolve, ms)); +} + +export async function setUp(options: SetUpOptions = {}): Promise { + const directory = await mkdtemp(join(tmpdir(), "simlock-agent-device-edge-")); + temporaryDirectories.push(directory); + const clock = new FakeClock(1_000); + const filesystem = new MemoryFilesystem(); + await seedTokensDatabase(directory, [ + [principals.one, secrets.one, "agent"], + [principals.two, secrets.two, "agent"], + ["tok_operator", secrets.operator, "operator"], + ["tok_worker", secrets.worker, "worker"], + ]); + const port = await freeLoopbackPort(); + const fake = options.upstream ?? new FakeAgentDevice(); + const phone = options.phoneUpstream ?? new FakeAgentDevice(); + const drivers = options.drivers?.(clock) ?? [iosDriver(clock)]; + const stateDbPath = join(directory, "state.db"); + const logs = new MemoryLogSink(); + const launch = () => + startDaemon({ + clock, + configOverrides: { + ...(options.enabled === "unset" + ? {} + : { + capabilities: { + "agent-device": { + enabled: options.enabled ?? true, + ...(options.leaseTtlCapMs === undefined + ? {} + : { leaseTtlCapMs: options.leaseTtlCapMs }), + }, + }, + }), + capacity: { config: { maxRunning: options.maxRunning ?? 4 }, strategy: "fixed" }, + ...(options.downloads === undefined ? {} : { downloads: { policy: options.downloads } }), + http: { enabled: true, host: "127.0.0.1", port }, + lease: { + defaultTtlMs, + maxTtlMs, + ...(options.endWaitMs === undefined ? {} : { endWaitMs: options.endWaitMs }), + }, + }, + ...(options.gatewayMode === true ? { role: "gateway" as const } : {}), + dataDirectory: directory, + deviceDataTables: fakeDeviceDataTables, + drivers, + filesystem, + logger: new JsonLinesLogger({ clock, level: "debug", sink: logs }), + optionalModules: [agentDeviceModuleWith({ phoneUpstream: phone, upstream: fake })], + version: "1.2.3", + } as StartDaemonOptions).then((daemon) => { + runningDaemons.push(daemon); + return daemon; + }); + const started = launch(); + const origin = `http://127.0.0.1:${port}`; + if (options.slowStart === true) { + await waitListening(origin); + return { + clock, + daemon: undefined as never, + driver: drivers[0] as FakeDriver, + fake, + phone, + filesystem, + logs, + origin, + restart: () => Promise.reject(new Error("restart needs a started daemon")), + started, + stateDbPath, + }; + } + const rigFor = (daemon: DaemonServer, running: Promise): Rig => ({ + clock, + daemon, + driver: drivers[0] as FakeDriver, + fake, + phone, + filesystem, + logs, + origin, + restart: async (between) => { + await daemon.stop("test"); + between?.(); + const next = await launch(); + return rigFor(next, Promise.resolve(next)); + }, + started: running, + stateDbPath, + }); + return rigFor(await started, started); +} + +async function waitListening(origin: string): Promise { + for (let attempt = 0; attempt < 400; attempt += 1) { + try { + await fetch(`${origin}/v1/healthz`); + return; + } catch { + await sleep(5); + } + } + throw new Error("the daemon never listened"); +} + +export interface SendOptions { + readonly body?: string; + readonly headers?: Record; + readonly method?: string; + readonly signal?: AbortSignal; + readonly token?: string | null; +} + +export function send(rig: Rig, path: string, options: SendOptions = {}): Promise { + const token = options.token === undefined ? secrets.one : options.token; + return fetch(`${rig.origin}/v1/agent-device${path}`, { + ...(options.body === undefined ? {} : { body: options.body }), + headers: { + // why: a pooled socket to a daemon the test restarted on the same port is closed by the server, so a request must not reuse one. + connection: "close", + ...(token === null ? {} : { authorization: `Bearer ${token}` }), + ...(options.body === undefined ? {} : { "content-type": "application/json" }), + ...options.headers, + }, + method: options.method ?? (options.body === undefined ? "GET" : "POST"), + ...(options.signal === undefined ? {} : { signal: options.signal }), + }); +} + +export function rpcBody(method: string, params: Record, id: unknown = 1): string { + return JSON.stringify({ id, jsonrpc: "2.0", method, params }); +} + +export function rpc( + rig: Rig, + method: string, + params: Record, + options: Omit & { readonly id?: unknown } = {}, +): Promise { + return send(rig, "/rpc", { ...options, body: rpcBody(method, params, options.id ?? 1) }); +} + +export async function bodyOf(response: Response): Promise> { + const text = await response.text(); + expect( + text.trimStart().startsWith("{"), + `expected a JSON object body, got ${response.status} ${text.slice(0, 80)}`, + ).toBe(true); + return JSON.parse(text) as Record; +} + +export async function envelopeOf(response: Response): Promise { + return (await bodyOf(response)) as Envelope; +} + +export const hex = (n: number): string => n.toString(16).padStart(32, "0"); + +export function allocateParams( + n: number, + extra: Record = {}, +): Record { + return { ...scope, leaseId: hex(n), platform: "ios", ttlMs: 120_000, ...extra }; +} + +export function allocate( + rig: Rig, + n: number, + extra: Record = {}, + options: Omit = {}, +): Promise { + return rpc(rig, "agent_device.lease.allocate", allocateParams(n, extra), options); +} + +export async function granted( + rig: Rig, + n: number, + extra: Record = {}, + options: Omit = {}, +): Promise { + const answer = await envelopeOf(await allocate(rig, n, extra, options)); + expect(answer.result).toMatchObject({ ok: true }); +} + +export function command( + rig: Rig, + name: string, + n: number | undefined, + options: Omit = {}, + extra: Record = {}, +): Promise { + return rpc( + rig, + "agent_device.command", + { + command: name, + ...(n === undefined ? {} : { meta: { leaseId: hex(n) } }), + ...extra, + }, + options, + ); +} + +interface LeaseView { + readonly id: string; + readonly deviceId: string; + readonly requesterId: string; + readonly ownerId: string; + readonly ttlMs: number; + readonly ttlDeadline: number; + readonly lastRenewedAt: number; +} + +export async function leases(rig: Rig): Promise { + return (await rig.daemon.dispatch( + "list.get", + { kind: "leases" }, + adminSession, + )) as unknown as readonly LeaseView[]; +} + +export async function requestedSpecs(rig: Rig, requester: string): Promise { + const events = await rig.daemon.dispatch("events.replay", {}, adminSession); + return events + .filter((entry) => entry.event === "lease.requested") + .map((entry) => entry.payload as { requester: string; requestSpec: unknown }) + .filter((payload) => payload.requester === requester) + .map((payload) => payload.requestSpec); +} + +export function receivedAllocate(rig: Rig, n: number): Record { + const params = allocatesReceived(rig, n)[0]?.params; + expect(params).toBeDefined(); + return params as Record; +} + +export function allocatesReceived(rig: Rig, n?: number) { + return rig.fake + .rpcRequests("agent_device.lease.allocate") + .filter((request) => n === undefined || request.params?.["leaseId"] === hex(n)); +} + +export async function simlockMessage(rig: Rig, input: Record): Promise { + try { + await rig.daemon.dispatch("lease.request", input, sessionFor(principals.one)); + } catch (error) { + return (error as Error).message; + } + throw new Error("simlock accepted a request the test expected it to refuse"); +} + +export function refusal(message: string, code = "INVALID_ARGS") { + return { code: -32000, data: { code, message }, message }; +} + +export function runCommand( + rig: Rig, + name: string, + n: number | undefined, + fields: Record = {}, + options: Omit = {}, +): Promise { + const { meta, ...rest } = fields; + return command(rig, name, undefined, options, { + ...(n === undefined && meta === undefined + ? {} + : { meta: { ...(n === undefined ? {} : { leaseId: hex(n) }), ...(meta as object) } }), + ...rest, + }); +} + +// why: a refusal test starts from a request that is accepted, then changes one thing (testing rule 2). +export async function forwarded( + rig: Rig, + send: () => Promise, +): Promise> { + const before = rig.fake.requests.length; + const answer = await envelopeOf(await send()); + expect(answer.error).toBeUndefined(); + expect(answer.result).toBeDefined(); + // why: the front reads a leased device's name from agent-device's device list the first time a rule needs it, before it forwards the command. + const sent = rig.fake.requests.slice(before).filter((r) => r.params?.["command"] !== "devices"); + expect(sent.length).toBe(1); + return sent[0]?.params as Record; +} + +export async function refused( + rig: Rig, + send: () => Promise, + message: string, +): Promise { + const before = rig.fake.requests.length; + const answer = await envelopeOf(await send()); + expect(answer.error).toMatchObject(refusal(message)); + expect(answer.result).toBeUndefined(); + // why: a refusal can follow the front's one read of a leased device's name from agent-device's device list; no command reaches it. + expect( + rig.fake.requests.slice(before).filter((r) => r.params?.["command"] !== "devices"), + ).toEqual([]); +} diff --git a/website/src/content/docs/docs/using-devices/agent-device.mdx b/website/src/content/docs/docs/using-devices/agent-device.mdx index 9602c456f..68b9c5309 100644 --- a/website/src/content/docs/docs/using-devices/agent-device.mdx +++ b/website/src/content/docs/docs/using-devices/agent-device.mdx @@ -122,9 +122,10 @@ Each agent-device session holds one device. To use a second device, open a secon - `--target mobile`, `tv` or `desktop` asks for a phone, a TV or a desktop device. - `--os` names an OS version or a range: `26.0`, `>=18 <27`, `18 - 26`. A range gets the newest installed version inside it. - On Android, `--image-tag` names a system image tag, such as `google_apis_playstore`. +- `--device-baseline` (the `deviceBaseline` key of an allocate) leases a fresh copy of a saved Simlock baseline. It needs the agent-device release that adds the flag. `--target` is ignored beside it; Simlock refuses a baseline that is unknown, stale or doesn't match `--platform`, `--device` or `--os`, and `--physical` with one. - `--physical` leases an enrolled phone (see [Use a real phone](#use-a-real-phone)). -The reply to `open` names the model, OS and image tag you got. If every matching device is taken, `open` waits for up to 330 seconds, then fails with `timed out waiting for a device; nothing was leased`. +The reply to `open` names the model, OS and image tag you got, and the baseline name and version when you asked for one. If every matching device is taken, `open` waits for up to 330 seconds, then fails with `timed out waiting for a device; nothing was leased`. ### What to expect @@ -210,7 +211,7 @@ Restarting a worker's daemon ends every agent-device lease on that worker, even | `refused: lease is not one of yours on this gateway` | The command named another session's or token's lease, often for the same reason. Give each agent its own `AGENT_DEVICE_SESSION`, then `open` again. | | `refused: malformed physical` | `physical` wasn't true or false. | | `refused: unknown --target ; use mobile, tv or desktop` | `--target` named a kind of device Simlock doesn't know. | -| `refused: malformed osVersion`, `refused: malformed imageTag` | `--os` or `--image-tag` wasn't text. | +| `refused: malformed osVersion`, `refused: malformed imageTag`, `refused: malformed deviceBaseline` | `--os`, `--image-tag` or `deviceBaseline` wasn't text. | | `refused by simlock: ` | Simlock refused the lease, for example for a model it doesn't know, an OS range it can't read, or an image tag on iOS. | | `refused: this agent-device is too old to use through a gateway; update it` | Update the agent's agent-device. | | `agent-device is not available on this simlock: ` | agent-device is missing, too old, starting or crashed on the worker. |