diff --git a/e2e/event-history.test.ts b/e2e/event-history.test.ts index 3baca9569..8a3cf1bfb 100644 --- a/e2e/event-history.test.ts +++ b/e2e/event-history.test.ts @@ -76,6 +76,8 @@ describe("event history", () => { expect(stopped.code).toBe(0); expect(grantOf(parseLines(stopped.stdout), leaseId)).toEqual(before); expect(existsSync(env.socketPath)).toBe(false); + const status = await env.cli(["daemon", "status", "--json"]); + expect(status.json).toEqual({ status: "stopped" }); }); it("simlock events --since 1h after a daemon restart prints each event with the id it had before the restart", async () => { @@ -141,21 +143,6 @@ describe("event history", () => { expect(history.find((entry) => entry.event === "queue.changed")?.payload).toEqual({ depth: 0 }); }); - it("prints the history with the daemon stopped, and the daemon stays stopped", async () => { - const env = await withDaemon(); - await prepare(env); - const leaseId = await leaseDevice(env); - await stopDaemon(env); - - const history = await env.cli(["events", "--since", "1h"]); - - expect(history.code).toBe(0); - expect(grantOf(parseLines(history.stdout), leaseId)).toBeDefined(); - expect(existsSync(env.socketPath)).toBe(false); - const status = await env.cli(["daemon", "status", "--json"]); - expect(status.json).toEqual({ status: "stopped" }); - }); - it("writes history.db and no events.jsonl in a fresh data directory, and leaves an events.jsonl placed there before the start byte-identical", async () => { const fresh = await withDaemon(); const placed = await withDaemon({ mode: "auto" }); diff --git a/e2e/fake-driver/device-data.test.ts b/e2e/fake-driver/device-data.test.ts deleted file mode 100644 index ddcece644..000000000 --- a/e2e/fake-driver/device-data.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { DatabaseSync } from "node:sqlite"; -import { describe, expect, it } from "vitest"; -import { e2eFakeDeviceDataTable } from "./device-data.js"; - -function openTable(): DatabaseSync { - const database = new DatabaseSync(":memory:"); - for (const statement of e2eFakeDeviceDataTable.migrations) database.exec(statement); - return database; -} - -describe("e2e fake device data table", () => { - it("writes and reads back its one key", () => { - const database = openTable(); - - e2eFakeDeviceDataTable.write(database, "dev_1", { fakeDeviceId: "fk-1" }); - - expect(e2eFakeDeviceDataTable.read(database, "dev_1")).toEqual({ fakeDeviceId: "fk-1" }); - }); - - it("refuses data with a key besides fakeDeviceId, and stores nothing", () => { - const database = openTable(); - - expect(() => - e2eFakeDeviceDataTable.write(database, "dev_1", { extra: 1, fakeDeviceId: "fk-1" }), - ).toThrow("Invalid fake driver data for device dev_1"); - expect(() => e2eFakeDeviceDataTable.read(database, "dev_1")).toThrow( - "No fake driver data for device dev_1", - ); - }); -}); diff --git a/e2e/physical-enrollment.test.ts b/e2e/physical-enrollment.test.ts index 1b2dc20b3..3fc13cf6e 100644 --- a/e2e/physical-enrollment.test.ts +++ b/e2e/physical-enrollment.test.ts @@ -482,16 +482,6 @@ describe("simlock device remove", () => { } }); - it("from a non-interactive shell, with no --yes, unenrols the device", async () => { - const env = await startDaemon({ ios: { physicalDevices: [IPHONE] } }); - const enrolled = await add(env, "ios", UDID); - - const result = await env.cli(["device", "remove", UDID]); - - expect(result.code, result.stderr).toBe(0); - expect((await rows(env)).find((row) => row.id === enrolled.id)?.state).toBe("deleted"); - }); - it("then device add writes a new record with a new registry ID and reenrolled false, and the old record stays deleted", async () => { const env = await startDaemon({ ios: { physicalDevices: [IPHONE] } }); const first = await add(env, "ios", UDID); diff --git a/e2e/physical-leasing.test.ts b/e2e/physical-leasing.test.ts index 2806333a8..518deaf27 100644 --- a/e2e/physical-leasing.test.ts +++ b/e2e/physical-leasing.test.ts @@ -257,50 +257,70 @@ describe("a physical lease request: grant", () => { expect(grant.device.spec).toMatchObject({ model: "iPhone 15 Pro", osVersion: "18.4" }); }); - it('--os 18 with only an iPhone on 18.4.1 enrolled exits with UNKNOWN_MODEL at once, and its message names --os ">=18 <19"', async () => { - const env = await startWith({ ios: [IPHONE_1841] }); - const accepted = await granted(env, physical("agent-range", "--os", ">=18 <19")); - expect(accepted.device.driverDeviceId).toBe(UDID_1841); - await release(env, accepted); - - const refused = await env.cli(physical("agent-exact", "--os", "18", "--detach"), { - timeout: 15_000, - }); - - expect(refused.code, refused.stderr).toBe(12); - expect(refused.error?.code).toBe("UNKNOWN_MODEL"); - expect(refused.error?.message).toContain('--os ">=18 <19"'); - }); - - it('--os 18.4 with only an iPhone on 18.4.1 enrolled exits with UNKNOWN_MODEL at once, and its message names --os ">=18.4 <18.5"', async () => { - const env = await startWith({ ios: [IPHONE_1841] }); - const accepted = await granted(env, physical("agent-range", "--os", ">=18.4 <18.5")); - expect(accepted.device.driverDeviceId).toBe(UDID_1841); - await release(env, accepted); - - const refused = await env.cli(physical("agent-exact", "--os", "18.4", "--detach"), { - timeout: 15_000, - }); - - expect(refused.code, refused.stderr).toBe(12); - expect(refused.error?.code).toBe("UNKNOWN_MODEL"); - expect(refused.error?.message).toContain('--os ">=18.4 <18.5"'); - }); - - it("--os 18.4.1 with only an iPhone on 18.4 enrolled exits with UNKNOWN_MODEL at once, and its message names no range", async () => { - const env = await startWith({ ios: [IPHONE_A] }); - const accepted = await granted(env, physical("agent-exact", "--os", "18.4")); - expect(accepted.device.driverDeviceId).toBe(UDID_A); - await release(env, accepted); - - const refused = await env.cli(physical("agent-newer", "--os", "18.4.1", "--detach"), { - timeout: 15_000, - }); - - expect(refused.code, refused.stderr).toBe(12); - expect(refused.error?.code).toBe("UNKNOWN_MODEL"); - expect(refused.error?.message).not.toMatch(/>=|<\d/); - }); + it.each([ + { + platform: "ios", + enrolled: { ios: [IPHONE_1841] }, + driverDeviceId: UDID_1841, + accepted: ">=18 <19", + refused: "18", + range: ">=18 <19", + }, + { + platform: "ios", + enrolled: { ios: [IPHONE_1841] }, + driverDeviceId: UDID_1841, + accepted: ">=18.4 <18.5", + refused: "18.4", + range: ">=18.4 <18.5", + }, + { + platform: "ios", + enrolled: { ios: [IPHONE_A] }, + driverDeviceId: UDID_A, + accepted: "18.4", + refused: "18.4.1", + range: undefined, + }, + { + platform: "android", + enrolled: { android: [PIXEL] }, + driverDeviceId: SERIAL, + accepted: "34", + refused: "33", + range: undefined, + }, + ])( + "--os $refused on the only enrolled $platform device, which accepts --os $accepted, exits with UNKNOWN_MODEL at once, and its message names the --os range only for a partial iOS version", + async ({ platform, enrolled, driverDeviceId, accepted, refused, range }) => { + const env = await startWith(enrolled); + const leaseArgs = (agent: string, os: string): string[] => [ + "lease", + "--platform", + platform, + "--physical", + "--os", + os, + "--agent-id", + agent, + ]; + const first = await granted(env, leaseArgs("agent-accepted", accepted)); + expect(first.device.driverDeviceId).toBe(driverDeviceId); + await release(env, first); + + const result = await env.cli([...leaseArgs("agent-refused", refused), "--detach"], { + timeout: 15_000, + }); + + expect(result.code, result.stderr).toBe(12); + expect(result.error?.code).toBe("UNKNOWN_MODEL"); + if (range === undefined) { + expect(result.error?.message).not.toMatch(/>=|<\d/); + } else { + expect(result.error?.message).toContain(`--os "${range}"`); + } + }, + ); it("--platform android --physical --os 34 is granted the phone on API 34", async () => { const env = await startWith({ android: [PIXEL] }); @@ -321,41 +341,6 @@ describe("a physical lease request: grant", () => { expect(grant.device.spec.osVersion).toBe("34"); }); - it("--platform android --physical --os 33 with only a phone on API 34 enrolled exits with UNKNOWN_MODEL at once, and its message names no range", async () => { - const env = await startWith({ android: [PIXEL] }); - const accepted = await granted(env, [ - "lease", - "--platform", - "android", - "--physical", - "--os", - "34", - "--agent-id", - "agent-exact", - ]); - expect(accepted.device.driverDeviceId).toBe(SERIAL); - await release(env, accepted); - - const refused = await env.cli( - [ - "lease", - "--platform", - "android", - "--physical", - "--os", - "33", - "--agent-id", - "agent-older", - "--detach", - ], - { timeout: 15_000 }, - ); - - expect(refused.code, refused.stderr).toBe(12); - expect(refused.error?.code).toBe("UNKNOWN_MODEL"); - expect(refused.error?.message).not.toMatch(/>=|<\d/); - }); - it("the grant's environment is the fake driver's answer for that device: SIMLOCK_DEVICE_UDID on iOS, ANDROID_SERIAL and ANDROID_ADB_SERVER_PORT=5037 on Android", async () => { const env = await startWith({ android: [PIXEL], ios: [IPHONE_A] }); diff --git a/e2e/physical-presence-loss-recovery.test.ts b/e2e/physical-presence-loss-recovery.test.ts index d9b79f9f4..8869fe6ac 100644 --- a/e2e/physical-presence-loss-recovery.test.ts +++ b/e2e/physical-presence-loss-recovery.test.ts @@ -82,7 +82,7 @@ describe("a physical reclaim that fails while the device is gone makes it absent expect(row?.state).toBe("quarantined"); expect(await payloadsOf(env, "device.purge-failed")).toContainEqual( - expect.objectContaining({ deviceId: LEASED.id }), + expect.objectContaining({ attemptedStrategy: "uninstall", deviceId: LEASED.id }), ); expect(await payloadsOf(env, "device.quarantined")).toContainEqual( expect.objectContaining({ deviceId: LEASED.id }), diff --git a/e2e/physical-reclaim.test.ts b/e2e/physical-reclaim.test.ts index 91a28d703..0de15c3b7 100644 --- a/e2e/physical-reclaim.test.ts +++ b/e2e/physical-reclaim.test.ts @@ -219,23 +219,6 @@ describe("a released physical device is reclaimed by uninstalling the apps enrol }); describe("a physical reclaim that fails quarantines the device", () => { - const SLOW_RETRY = { warmPool: { quarantine: { retryBackoffMs: 60_000 } } }; - - it("a failed reclaim emits device.purge-failed with uninstall and leaves the device quarantined in simlock status", async () => { - const env = await startWith(LEASED, { - config: SLOW_RETRY, - leases: [HELD_LEASE(600_000)], - script: { failReclaim: true, installed: [...ENROLLED, ...AGENT_APPS] }, - }); - - const released = await env.cli(["release", "lse_pheld"]); - expect(released.code, released.stderr).toBe(0); - - const failed = await waitForEvent(env, "device.purge-failed"); - expect(failed).toMatchObject({ attemptedStrategy: "uninstall", deviceId: LEASED.id }); - await waitForState(env, LEASED.id, "quarantined"); - }); - it("a quarantine retry that succeeds makes the device ready with device.quarantine-recovered strategy uninstall and missingApps", async () => { const env = await startWith(LEASED, { config: { warmPool: { quarantine: { retryBackoffMs: 1_500 } } }, diff --git a/e2e/slow-agent-device-gateway.test.ts b/e2e/slow-agent-device-gateway.test.ts index fe8502ed6..a7d9d364c 100644 --- a/e2e/slow-agent-device-gateway.test.ts +++ b/e2e/slow-agent-device-gateway.test.ts @@ -233,25 +233,6 @@ function defineSuite(target: Target): void { }, ); - it( - "through the gateway, a screenshot saved as an artifact downloads to the agent's machine as a PNG", - { timeout: 600_000 }, - async () => { - const a = await agent("a"); - ok(await open(a)); - ok(await a.run(["install", "Appduct", target.app])); - ok(await a.run(["open", target.bundleId])); - const dir = await mkdtemp(join(tmpdir(), "simlock-ad-gw-artifact-")); - onTestFinished(() => rm(dir, { force: true, recursive: true })); - const png = join(dir, "artifact.png"); - await expect(readFile(png)).rejects.toThrow(); - ok(await a.run(["screenshot", png], FIRST_SNAPSHOT)); - const bytes = await readFile(png); - expect(bytes.length).toBeGreaterThan(8); - expect(bytes.subarray(0, 8).toString("hex")).toBe("89504e470d0a1a0a"); - }, - ); - it( "with capabilities.agent-device.enabled unset on the gateway, its /v1/agent-device/health answers 404 where it answered something else while enabled", { timeout: 600_000 }, diff --git a/e2e/slow-ios-physical.test.ts b/e2e/slow-ios-physical.test.ts index 000ecd4f8..da7e6e4a2 100644 --- a/e2e/slow-ios-physical.test.ts +++ b/e2e/slow-ios-physical.test.ts @@ -1,6 +1,6 @@ import { execFile, spawn } from "node:child_process"; import { existsSync } from "node:fs"; -import { access, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { mkdtemp, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; @@ -202,10 +202,6 @@ async function exitCodeOf(response: Response): Promise<{ code: number; body: str return { body, code: (JSON.parse(data) as { exitCode: number }).exitCode }; } -async function errorCodeOf(response: Response): Promise { - return ((await response.json()) as { error: { code: string } }).error.code; -} - describe.skipIf(process.platform !== "darwin" || missing !== undefined)( missing === undefined ? "iOS physical phone (real devicectl)" @@ -318,29 +314,6 @@ describe.skipIf(process.platform !== "darwin" || missing !== undefined)( }, ); - it( - "device.exec devicectl --json-output list devices is refused and no file appears at ", - { timeout: 5 * MINUTE }, - async () => { - const daemon = await rig(); - await enroll(daemon.env, udid); - const grant = await leasePhysical(daemon.env, "phone-lane-refuse"); - const target = join(await mkdtemp(join(tmpdir(), "simlock-physical-")), "refused.json"); - - const refused = await exec(daemon, grant.lease.id, "phone-lane-refuse", [ - "--json-output", - target, - "list", - "devices", - ]); - - expect(refused.status).toBe(422); - expect(await errorCodeOf(refused)).toBe("PASSTHROUGH_REFUSED"); - await expect(access(target)).rejects.toMatchObject({ code: "ENOENT" }); - await daemon.env.cli(["release", grant.lease.id]); - }, - ); - it( "device.exec devicectl device process launch -- -AppleLanguages (en) of the test app exits 0", { timeout: 10 * MINUTE }, @@ -378,20 +351,6 @@ describe.skipIf(process.platform !== "darwin" || missing !== undefined)( }, ); - it( - "the grant's environment carries SIMLOCK_DEVICE_UDID equal to the phone's UDID", - { timeout: 5 * MINUTE }, - async () => { - const { env } = await rig(); - await enroll(env, udid); - - const grant = await leasePhysical(env, "phone-lane-env"); - - expect(grant.environment["SIMLOCK_DEVICE_UDID"]).toBe(udid); - await env.cli(["release", grant.lease.id]); - }, - ); - it("ends with device remove, and removes the test app", { timeout: 5 * MINUTE }, async () => { const bundle = await bundleIdOf(app); const { env } = await rig(); diff --git a/e2e/startup-reconcile.test.ts b/e2e/startup-reconcile.test.ts index f4890764c..f72d9a615 100644 --- a/e2e/startup-reconcile.test.ts +++ b/e2e/startup-reconcile.test.ts @@ -101,35 +101,24 @@ async function deviceState(env: TestEnv, deviceId: string): Promise { - it("a daemon restarted after its leased device was scripted stopped answers a renew of that lease with UNKNOWN_LEASE, records lease.released with reason device-lost, and the device becomes ready after reclaim", async () => { - const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 120_000 } } }); - await prepare(env); - const held = await lease(env, "ios"); - - await script(env, "ios", [{ deviceId: held.driverDeviceId, runState: "stopped" }]); - await restart(env); - - expect(await renewError(env, held.leaseId)).toBe("UNKNOWN_LEASE"); - const ended = await leaseEvents(env, held.leaseId); - expect(ended.map((entry) => entry.event)).toEqual(["lease.released"]); - expect(ended[0]?.payload).toMatchObject({ leaseId: held.leaseId, reason: "device-lost" }); - await waitForDeviceState(env, held.driverDeviceId, "ready"); - expect(await reclaimCalls(env, held.driverDeviceId)).toHaveLength(1); - }); - - it("a daemon restarted after its leased device was scripted transitioning answers a renew with UNKNOWN_LEASE, records lease.released with reason device-lost, and the device becomes ready after reclaim", async () => { - const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 120_000 } } }); - await prepare(env); - const held = await lease(env, "ios"); - - await script(env, "ios", [{ deviceId: held.driverDeviceId, runState: "transitioning" }]); - await restart(env); - - expect(await renewError(env, held.leaseId)).toBe("UNKNOWN_LEASE"); - const ended = await leaseEvents(env, held.leaseId); - expect(ended[0]?.payload).toMatchObject({ leaseId: held.leaseId, reason: "device-lost" }); - await waitForDeviceState(env, held.driverDeviceId, "ready"); - }); + it.each(["stopped", "transitioning"] as const)( + "a daemon restarted after its leased device was scripted %s answers a renew of that lease with UNKNOWN_LEASE, records lease.released with reason device-lost, and the device becomes ready after reclaim", + async (runState) => { + const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 120_000 } } }); + await prepare(env); + const held = await lease(env, "ios"); + + await script(env, "ios", [{ deviceId: held.driverDeviceId, runState }]); + await restart(env); + + expect(await renewError(env, held.leaseId)).toBe("UNKNOWN_LEASE"); + const ended = await leaseEvents(env, held.leaseId); + expect(ended.map((entry) => entry.event)).toEqual(["lease.released"]); + expect(ended[0]?.payload).toMatchObject({ leaseId: held.leaseId, reason: "device-lost" }); + await waitForDeviceState(env, held.driverDeviceId, "ready"); + expect(await reclaimCalls(env, held.driverDeviceId)).toHaveLength(1); + }, + ); it("a daemon restarted after its leased device was removed from the scripted reality ends the lease, emits device.deleted with initiator doctor, and the fake driver log shows no reclaim call for it", async () => { const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 120_000 } } }); diff --git a/src/agent-device/definition.test.ts b/src/agent-device/definition.test.ts index d2d9d5015..a3674449c 100644 --- a/src/agent-device/definition.test.ts +++ b/src/agent-device/definition.test.ts @@ -32,10 +32,6 @@ function section(config: Config): Record | undefined { } describe("agent-device's definition: capabilities.agent-device config", () => { - it("is named agent-device", () => { - expect(agentDeviceModule.name).toBe("agent-device"); - }); - it("defaults capabilities.agent-device.enabled to false and command to agent-device, with leaseTtlCapMs unset", async () => { const config = await loadWith({}); diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 2a23bbb98..509f8504f 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -2941,17 +2941,6 @@ describe("the agent-device front's request rules", () => { expect(rig.fake.requests.length).toBe(before); }); - it("a route refusal answers 404 with `refused: unknown route POST /rpcx`", async () => { - const rig = await setUp(); - - const answer = await send(rig, "/rpcx", { body: "{}" }); - - expect(answer.status).toBe(404); - expect(((await bodyOf(answer)) as { error: string }).error).toBe( - "refused: unknown route POST /rpcx", - ); - }); - it("a route outside the list answers 401 without a token, and `agent-device is not available on this simlock` while agent-device is unavailable", async () => { const rig = await setUp(); expect((await send(rig, "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/admin/leases")).status).toBe(404); @@ -3726,15 +3715,6 @@ describe("a worker's capabilities in status.get, through the whole worker daemon expect(await capabilities(off)).toEqual([{ name: "agent-device", state: "off" }]); }); - it("a worker with agent-device running answers [{name: agent-device, state: available}], with no reason", async () => { - const rig = await setUp(); - - const [entry] = (await capabilities(rig)) ?? []; - - expect(entry).toEqual({ name: "agent-device", state: "available" }); - expect(entry).not.toHaveProperty("reason"); - }); - it("a worker whose agent-device is unavailable answers state unavailable with the same reason its front's notAvailable reply names", async () => { const rig = await setUp(); const reason = "found 0.20.1, need 0.21.28 or later"; @@ -3821,31 +3801,21 @@ describe( await expect.poll(() => rig.fake.artifactBodyCancelled).toBe(true); }); - it("an artifact download of exactly 2147483648 bytes with `content-length` arrives byte for byte", async () => { - const rig = await setUp(); - rig.fake.serveArtifact({ contentLength: "size", size: downloadLimit }); - - const response = await send(rig, "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/artifacts/a1"); - const received = await drainDownload(response); - - expect(response.status).toBe(200); - expect(received.ended).toBe(true); - expect(received.bytes).toBe(downloadLimit); - expect(received.digest).toBe(rig.fake.producedDigest()); - }); - - it("a download with no `content-length` of exactly 2147483648 bytes arrives byte for byte", async () => { - const rig = await setUp(); - rig.fake.serveArtifact({ contentLength: "none", size: downloadLimit }); + it.each(["size", "none"] as const)( + "a download of exactly 2147483648 bytes with `content-length` %s arrives byte for byte", + async (contentLength) => { + const rig = await setUp(); + rig.fake.serveArtifact({ contentLength, size: downloadLimit }); - const response = await send(rig, "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/artifacts/a1"); - const received = await drainDownload(response); + const response = await send(rig, "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/artifacts/a1"); + const received = await drainDownload(response); - expect(response.status).toBe(200); - expect(received.ended).toBe(true); - expect(received.bytes).toBe(downloadLimit); - expect(received.digest).toBe(rig.fake.producedDigest()); - }); + expect(response.status).toBe(200); + expect(received.ended).toBe(true); + expect(received.bytes).toBe(downloadLimit); + expect(received.digest).toBe(rig.fake.producedDigest()); + }, + ); it("a download with no `content-length` that passes 2147483648 bytes errors the agent's response, which never ends cleanly, and the fake's body is cancelled", async () => { const rig = await setUp(); diff --git a/src/agent-device/front/allocate.test.ts b/src/agent-device/front/allocate.test.ts index 82d88e717..77c7533fe 100644 --- a/src/agent-device/front/allocate.test.ts +++ b/src/agent-device/front/allocate.test.ts @@ -123,16 +123,6 @@ describe("the allocate front", () => { expect(rig.cancels()).toHaveLength(3); }); - it("refreshes the front map at each allocate", async () => { - const rig = setUp(); - const refresh = vi.spyOn(rig.map, "refresh"); - - await rig.run(); - await rig.run(); - - expect(refresh).toHaveBeenCalledTimes(2); - }); - it("gives up on a lease.list that does not answer within 5 s and goes on to the lease request", async () => { const rig = setUp(); rig.map.add("old", { address: "a", deadline: 500, identity: agent, ttlMs: 60_000 }); diff --git a/src/agent-device/front/context.test.ts b/src/agent-device/front/context.test.ts index 41ce3f784..0c494ea4b 100644 --- a/src/agent-device/front/context.test.ts +++ b/src/agent-device/front/context.test.ts @@ -31,15 +31,4 @@ describe("exchange", () => { expect(fields.body.startsWith("bad gateway xxx")).toBe(true); expect(fields.body.length).toBe(500); }); - - it("a usable success reply is not logged", async () => { - const { context, warnings } = rig(() => - Promise.resolve(Response.json({ id: 1, jsonrpc: "2.0", result: { ok: true } })), - ); - - const result = await exchange(context, request, identity); - - expect(result.reading.kind).toBe("success"); - expect(warnings).toEqual([]); - }); }); diff --git a/src/agent-device/front/relay-host-link.test.ts b/src/agent-device/front/relay-host-link.test.ts index adbe53444..4a8e637ff 100644 --- a/src/agent-device/front/relay-host-link.test.ts +++ b/src/agent-device/front/relay-host-link.test.ts @@ -21,7 +21,6 @@ function setUp() { let removed: ((lease: PlacedLease & { readonly leaseId: string }) => void) | undefined; const facts: FleetLeaseFacts[] = []; const reach = { connected: true, refreshed: true }; - let startedAt = -1_000_000; const relay = vi.fn((_worker: string, _request: Request, _tenant: string, _lease?: string) => Promise.resolve(new Response("relayed")), ); @@ -32,9 +31,7 @@ function setUp() { leaseOf: (leaseId) => index.get(leaseId), leasesOf: () => facts, reach: () => reach, - get startedAt() { - return startedAt; - }, + startedAt: -1_000_000, onLeaseRemoved: (listener) => { removed = listener; }, @@ -55,9 +52,6 @@ function setUp() { link, reach, relay, - startedAt: (at: number) => { - startedAt = at; - }, }; } @@ -98,15 +92,6 @@ describe("RelayHostLink", () => { expect(new Set(tenants).size).toBe(principals.length); }); - it("relays a lease the token holds to its worker under the tenant `gw..`", async () => { - const { index, link, relay } = setUp(); - index.set("L", { ownerId: "tok_a", workerId: "w1" }); - - await link.forward(request(), agent, "L"); - - expect(relay).toHaveBeenCalledWith("w1", expect.any(Request), "gw.gw1.tok_5f_a", "L"); - }); - it("answers the flat refusal shape for a request that is not an rpc call", async () => { const { link } = setUp(); @@ -119,22 +104,6 @@ describe("RelayHostLink", () => { }); }); - it("refuses a bare GET that is not /health, and relays nothing", async () => { - const { link, relay } = setUp(); - - const answer = await link.forward( - new Request("http://gateway.test/v1/agent-device/artifacts/a1"), - agent, - ); - - expect(await answer.json()).toEqual({ - code: "INVALID_ARGS", - error: "refused: this agent-device is too old to use through a gateway; update it", - ok: false, - }); - expect(relay).not.toHaveBeenCalled(); - }); - it("answers a body that is not JSON under a null id", async () => { const { link } = setUp(); const broken = new Request("http://gateway.test/v1/agent-device/rpc", { @@ -182,23 +151,6 @@ describe("RelayHostLink", () => { expect(await link.status()).not.toHaveProperty("leaseMaxTtlMs"); }); - it("keeps routing a lease the index dropped until the gateway's lease.maxTtlMs has passed, then forgets it, and its sweep stops with nothing kept", async () => { - const { clock, drop, index, link, relay } = setUp(); - index.set("L", { ownerId: "tok_a", workerId: "w1" }); - drop("L"); - expect(clock.pendingTimerCount).toBe(1); - - clock.advance(maxTtlMs); - await link.forward(request(), agent, "L"); - expect(relay).toHaveBeenCalledTimes(1); - - clock.advance(60_000); - expect(clock.pendingTimerCount).toBe(0); - const answer = await link.forward(request(), agent, "L"); - expect(answer.status).toBe(403); - expect(relay).toHaveBeenCalledTimes(1); - }); - it("cancels its sweep when disposed", () => { const { clock, drop, index, link } = setUp(); index.set("L", { ownerId: "tok_a", workerId: "w1" }); @@ -239,14 +191,6 @@ describe("RelayHostLink", () => { expect((await link.status("lease-1", agent)).state).toBe("running"); }); - it("answers unreachable for a lease it cannot place only in the first 60 s after the gateway started", async () => { - const { clock, link, startedAt } = setUp(); - startedAt(clock.now()); - expect((await link.status("lease-9", agent)).state).toBe("unreachable"); - clock.advance(60_000); - expect((await link.status("lease-9", agent)).state).toBe("running"); - }); - it("answers the unreachable reply when the relay fails with WORKER_UNREACHABLE, and rethrows any other failure", async () => { const { index, link, relay } = setUp(); index.set("lease-1", { ownerId: "tok_a", workerId: "w1" }); diff --git a/src/agent-device/front/renewals.test.ts b/src/agent-device/front/renewals.test.ts index 6874c1405..4363ff1c8 100644 --- a/src/agent-device/front/renewals.test.ts +++ b/src/agent-device/front/renewals.test.ts @@ -30,20 +30,4 @@ describe("the renewals", () => { expect(Math.max(...delays)).toBeLessThanOrEqual(longestTimerDelayMs); renewals.dispose(); }); - - it("stops the renewal timer of a lease that ended, leaving only the running call's own limit timer", () => { - const clock = new FakeClock(1_000); - const map = new FrontMap(clock); - map.add("lease-a", { address: "addr", deadline: 9e12, identity: agent, ttlMs: 60_000 }); - const renewals = new Renewals(clock); - const context = { map } as unknown as FrontContext; - renewals.begin(context, "lease-a", agent.principal, 1_800_000); - expect(clock.pendingTimerCount).toBe(2); - - map.markEnded("lease-a"); - renewals.cancelIfEnded(context, "lease-a"); - - expect(clock.pendingTimerCount).toBe(1); - renewals.dispose(); - }); }); diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index 12537f335..6b919f334 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -1,5 +1,4 @@ import { mkdtemp, rm } from "node:fs/promises"; -import { createHash } from "node:crypto"; import { createServer } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -2265,58 +2264,3 @@ describe( }); }, ); - -describe( - "the agent-device front, through a gateway: downloads over 2 GiB", - { timeout: 120_000 }, - () => { - const limit = 2_147_483_648; - - it("an artifact download whose `content-length` is 2147483649 gets the 413 reply; the worker's fake produced 0 bytes and its body was cancelled", async () => { - const rig = await setUp(); - await granted(rig, 1); - const worker = holderOf(rig, 1); - worker.fake.serveArtifact({ contentLength: "size", size: limit + 1 }); - - const response = await send(rig, "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/artifacts/a1", { headers: leased(1) }); - - expect(response.status).toBe(413); - expect(await response.json()).toEqual({ - code: "INVALID_ARGS", - error: `the download is ${String(limit + 1)} bytes; simlock carries downloads up to 2 GB (2147483648 bytes)`, - ok: false, - }); - expect(worker.fake.artifactBytesProduced).toBe(0); - await expect.poll(() => worker.fake.artifactBodyCancelled).toBe(true); - }); - - it("a download with no `content-length` that passes 2147483648 bytes errors the agent's response, which never ends cleanly", async () => { - const rig = await setUp(); - await granted(rig, 1); - const worker = holderOf(rig, 1); - worker.fake.serveArtifact({ contentLength: "none", size: limit + 1 }); - - const response = await send(rig, "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/artifacts/a1", { headers: leased(1) }); - const reader = (response.body as ReadableStream).getReader(); - const hash = createHash("sha256"); - let ended = false; - let delivered = 0; - try { - for (;;) { - const next = await reader.read(); - if (next.done) { - ended = true; - break; - } - hash.update(next.value); - delivered += next.value.length; - } - } catch { - ended = false; - } - - expect(ended).toBe(false); - expect(delivered).toBeGreaterThanOrEqual(limit); - }); - }, -); diff --git a/src/agent-device/gateway.test.ts b/src/agent-device/gateway.test.ts index 5fc6c526e..defde2b16 100644 --- a/src/agent-device/gateway.test.ts +++ b/src/agent-device/gateway.test.ts @@ -63,14 +63,4 @@ describe("agent-device's gateway side", () => { expect.stringContaining(noWorker), ]); }); - - it("agent-device's definition has a gateway side that creates a mount and a beforeDrain hook", async () => { - const { ctx } = await fakeGatewayContext("agent-device", agentDeviceModule.config.defaults); - const loaded = await agentDeviceModule.loadGateway?.(); - - const module = loaded?.createGateway(ctx); - - expect(module?.mount).toBeTypeOf("function"); - expect(module?.hooks?.beforeDrain).toBeTypeOf("function"); - }); }); diff --git a/src/agent-device/host/agent-device-supervisor.test.ts b/src/agent-device/host/agent-device-supervisor.test.ts index ba2c5e57d..4235d8c0b 100644 --- a/src/agent-device/host/agent-device-supervisor.test.ts +++ b/src/agent-device/host/agent-device-supervisor.test.ts @@ -1413,18 +1413,6 @@ describe("AgentDeviceSupervisor.stop", () => { expect(stateOf(harness)).toBe("off"); }); - it("logs no start-failed warning when stop() cancels a start", async () => { - const harness = await arrange({ daemonJson: () => "none" }); - harness.begin(); - await advanceBy(harness, 1_000); - - await advancing(harness, harness.agentDevice.stop()); - await advancing(harness, harness.started as Promise); - - expect(warnings(harness).filter((line) => line.includes("start failed"))).toEqual([]); - expect(stateOf(harness)).toBe("off"); - }); - it("leaves no unhandled rejection when a health read rejects after stop() was asked during the port check", async () => { const harness = await arrange(); harness.health.rejectWith(new Error("ECONNREFUSED")); diff --git a/src/agent-device/host/upstream.test.ts b/src/agent-device/host/upstream.test.ts index d98bd1099..b5c609b01 100644 --- a/src/agent-device/host/upstream.test.ts +++ b/src/agent-device/host/upstream.test.ts @@ -119,16 +119,6 @@ describe("the agent-device upstream adapter over the supervisor", () => { expect(availability.baseUrl).toContain(String(httpPort)); }); - it("reports unavailable with the supervisor's message", async () => { - const harness = await arrange("0.20.3"); - await started(harness); - - expect(harness.upstream.current()).toEqual({ - reason: "found 0.20.3, need 0.21.28 or later", - state: "unavailable", - }); - }); - it("reports unavailable with starting while the supervisor starts", async () => { const harness = await arrange("0.21.28"); const starting = harness.supervisor.start(); diff --git a/src/auth/admin-secret.test.ts b/src/auth/admin-secret.test.ts index bd7714039..cc9c36b01 100644 --- a/src/auth/admin-secret.test.ts +++ b/src/auth/admin-secret.test.ts @@ -25,41 +25,6 @@ describe("AdminSecretManager", () => { expect(stat.mode).toBe(0o600); }); - // why: spying on the raw call proves the call site passes `mode`, not that MemoryFilesystem happens to record one. - it("passes mode 0600 to writeFileAtomic itself, at the single call persist() makes", async () => { - const calls: Array<{ readonly path: string; readonly mode: number | undefined }> = []; - const filesystem: Filesystem = { - readFile: () => Promise.reject(new Error("unused by this test")), - readFileFrom: () => Promise.reject(new Error("unused by this test")), - writeFileAtomic: async (path, _contents, options) => { - calls.push({ path, mode: options?.mode }); - }, - mkdirp: () => Promise.reject(new Error("unused by this test")), - rm: () => Promise.reject(new Error("unused by this test")), - stat: () => Promise.reject(new Error("unused by this test")), - readdir: () => Promise.reject(new Error("unused by this test")), - exists: () => Promise.reject(new Error("unused by this test")), - diskFree: () => Promise.reject(new Error("unused by this test")), - diskSpace: () => Promise.reject(new Error("unused by this test")), - directorySize: () => Promise.reject(new Error("unused by this test")), - writeFileExclusive: () => Promise.reject(new Error("unused by this test")), - rename: () => Promise.reject(new Error("unused by this test")), - lstat: () => Promise.reject(new Error("unused by this test")), - mkdir: () => Promise.reject(new Error("unused by this test")), - chmod: () => Promise.reject(new Error("unused by this test")), - realpath: () => Promise.reject(new Error("unused by this test")), - }; - const manager = new AdminSecretManager({ - filesystem, - path: "/admin.token", - secrets: secrets(), - }); - - await manager.persist(); - - expect(calls).toEqual([{ path: "/admin.token", mode: 0o600 }]); - }); - it("remove() deletes admin.token", async () => { const filesystem = new MemoryFilesystem(); const manager = new AdminSecretManager({ diff --git a/src/auth/proxy.test.ts b/src/auth/proxy.test.ts index 6ff31d5d4..3bdb69b5e 100644 --- a/src/auth/proxy.test.ts +++ b/src/auth/proxy.test.ts @@ -229,33 +229,22 @@ describe("authenticateRequest with the proxy strategy", () => { } }); - it("sends a Bearer value to the token strategy when it starts slk_ and to the proxy check otherwise, with header authorization", async () => { - const { auth } = await harness({ proxyAuth: { ...proxyAuthConfig, header: "authorization" } }); - const { secret } = await auth.tokens.create("agent", "ci"); - const bearer = (value: string) => new Headers({ authorization: `Bearer ${value}` }); - - expect(await outcome(auth, bearer(secret))).toMatchObject({ identity: { via: "token" } }); - expect(await outcome(auth, bearer(await k1.sign(personClaims())))).toEqual(person()); - expect(await outcome(auth, bearer("abc"))).toEqual(refused("malformed")); - expect(await outcome(auth, bearer("slk_unknown"))).toEqual({ - status: 401, - message: "Unknown bearer token", - }); - }); - - it("takes header authorization written with capitals as authorization", async () => { - const { auth } = await harness({ proxyAuth: { ...proxyAuthConfig, header: "Authorization" } }); - const { secret } = await auth.tokens.create("agent", "ci"); - - expect(await outcome(auth, new Headers({ authorization: `Bearer ${secret}` }))).toMatchObject({ - identity: { via: "token" }, - }); - expect( - await outcome( - auth, - new Headers({ authorization: `Bearer ${await k1.sign(personClaims())}` }), - ), - ).toEqual(person()); + it("sends a Bearer value to the token strategy when it starts slk_ and to the proxy check otherwise, with header authorization written in lowercase or with capitals", async () => { + for (const header of ["authorization", "Authorization"]) { + const { auth } = await harness({ proxyAuth: { ...proxyAuthConfig, header } }); + const { secret } = await auth.tokens.create("agent", "ci"); + const bearer = (value: string) => new Headers({ authorization: `Bearer ${value}` }); + + expect(await outcome(auth, bearer(secret)), header).toMatchObject({ + identity: { via: "token" }, + }); + expect(await outcome(auth, bearer(await k1.sign(personClaims()))), header).toEqual(person()); + expect(await outcome(auth, bearer("abc")), header).toEqual(refused("malformed")); + expect(await outcome(auth, bearer("slk_unknown")), header).toEqual({ + status: 401, + message: "Unknown bearer token", + }); + } }); it("keeps answering Unknown bearer token for a Bearer value that is not a token when proxy sign-in is off", async () => { diff --git a/src/bus/index.test.ts b/src/bus/index.test.ts index 9db1383be..4b490d980 100644 --- a/src/bus/index.test.ts +++ b/src/bus/index.test.ts @@ -278,32 +278,14 @@ describe("EventBus", () => { }); it.each(["docs/internal/EVENTS.md"])( - "lists lease-engine among the device.deleted initiators in %s", + "lists lease-engine, cleanup-reaper and nuke among the device.deleted initiators in %s", (doc) => { const markdown = readFileSync(join(REPO_ROOT, doc), "utf8"); const row = markdown.split("\n").find((line) => line.startsWith("| `device.deleted` |")); expect(row).toBeDefined(); - expect(row).toContain("`lease-engine`"); - }, - ); - - it.each(["docs/internal/EVENTS.md"])( - "lists cleanup-reaper among the device.deleted initiators in %s", - (doc) => { - const markdown = readFileSync(join(REPO_ROOT, doc), "utf8"); - const row = markdown.split("\n").find((line) => line.startsWith("| `device.deleted` |")); - expect(row).toBeDefined(); - expect(row).toContain("`cleanup-reaper`"); - }, - ); - - it.each(["docs/internal/EVENTS.md"])( - "lists nuke among the device.deleted initiators in %s", - (doc) => { - const markdown = readFileSync(join(REPO_ROOT, doc), "utf8"); - const row = markdown.split("\n").find((line) => line.startsWith("| `device.deleted` |")); - expect(row).toBeDefined(); - expect(row).toContain("`nuke`"); + for (const initiator of ["lease-engine", "cleanup-reaper", "nuke"]) { + expect(row, initiator).toContain(`\`${initiator}\``); + } }, ); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 7aa25f37f..61e8bcae0 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2579,22 +2579,28 @@ describe("CLI: config set validates before writing (ADR 0003 §11)", () => { }); describe("CLI: config set validates with the real config loader (ADR 0003 §11, B9)", () => { - it("rejects an unknown config key instead of silently dropping it", async () => { - const output = outputCapture(realCliEnvironmentPorts()); - let wrote = false; - const exitCode = await runCli( - ["config", "set", "capacty.limits.ios.maxDevices", "2"], - output.environmentWith({ - readConfigFile: async () => ({}), - writeConfigFile: async () => { - wrote = true; - }, - }), - ); - expect(exitCode).toBe(2); - expect(wrote).toBe(false); - expect(JSON.parse(output.stderr).error.code).toBe("USAGE"); - }); + it.each([ + ["an unknown key", "capacty.limits.ios.maxDevices", "2"], + ["a key missing the Ms suffix", "lease.defaultTtl", "60000"], + ])( + "rejects %s instead of silently dropping it or validating clean", + async (_name, key, value) => { + const output = outputCapture(realCliEnvironmentPorts()); + let wrote = false; + const exitCode = await runCli( + ["config", "set", key, value], + output.environmentWith({ + readConfigFile: async () => ({}), + writeConfigFile: async () => { + wrote = true; + }, + }), + ); + expect(exitCode).toBe(2); + expect(wrote).toBe(false); + expect(JSON.parse(output.stderr).error.code).toBe("USAGE"); + }, + ); it("--gateway config set validates against the gateway's rules, not the worker's", async () => { const gatewayHome = { @@ -2640,22 +2646,6 @@ describe("CLI: config set validates with the real config loader (ADR 0003 §11, expect(output.stderr).toContain("http.enabled"); }); - it("rejects a mistyped key (missing the Ms suffix) instead of validating clean", async () => { - const output = outputCapture(realCliEnvironmentPorts()); - let wrote = false; - const exitCode = await runCli( - ["config", "set", "lease.defaultTtl", "60000"], - output.environmentWith({ - readConfigFile: async () => ({}), - writeConfigFile: async () => { - wrote = true; - }, - }), - ); - expect(exitCode).toBe(2); - expect(wrote).toBe(false); - }); - it("simlock config set eventLog.retention rejects a non-positive value, naming the key", async () => { for (const value of ["0", "1.5"]) { const output = outputCapture(realCliEnvironmentPorts()); @@ -3220,85 +3210,6 @@ describe("CLI: catalog", () => { ); }); - it("prints (custom) after a custom model and not after a built-in one", async () => { - const output = outputCapture(); - const environment = output.environmentWith({ - connectAdmin: async () => - fakeClient({ - getCatalog: () => - Promise.resolve({ - platforms: [ - { - customModels: ["My Tablet"], - defaultRuntime: "35", - modelAliases: {}, - classDefaults: {}, - modelClasses: {}, - modelRuntimes: { "My Tablet": ["35"], "Pixel 8": ["35"] }, - models: ["My Tablet", "Pixel 8"], - platform: "android", - runtimes: ["35"], - }, - ], - }), - }), - }); - - await expect(runCli(["catalog"], environment)).resolves.toBe(0); - - expect(output.stdout).toBe( - [ - "Platform: android", - " Runtimes: 35 (default: 35)", - " Models:", - " (no class):", - " My Tablet (custom): 35", - " Pixel 8: 35", - "", - ].join("\n"), - ); - }); -}); - -describe("CLI: component install (ADR 0010 §6)", () => { - it("prints each progress update on stderr and one result line on stdout, and exits 0", async () => { - const output = outputCapture(); - const asked: unknown[] = []; - const client = fakeClient({ - installComponent: async (input, options) => { - asked.push(input); - options?.onProgress?.({ stage: "waiting" }); - options?.onProgress?.({ fraction: 0.41, stage: "downloading" }); - return { component: "35", outcome: "installed", platform: "android", version: "35" }; - }, - }); - - await expect( - runCli( - ["component", "install", "android", "35"], - output.environmentWith({ connectAdmin: async () => client }), - ), - ).resolves.toBe(0); - - expect(asked).toEqual([{ platform: "android", version: "35" }]); - // why: The fake connection resolves no credential, so the agent-fallback notice comes first. - const stderrLines = output.stderr - .trim() - .split("\n") - .map((line) => JSON.parse(line) as unknown); - expect(stderrLines.filter((line) => !Object.hasOwn(line as object, "notice"))).toEqual([ - { stage: "waiting" }, - { fraction: 0.41, stage: "downloading" }, - ]); - expect(output.stdout.trim().split("\n")).toHaveLength(1); - expect(JSON.parse(output.stdout)).toEqual({ - component: "35", - outcome: "installed", - platform: "android", - version: "35", - }); - }); - it("exits 12 when the daemon refuses with DOWNLOADS_DISABLED", async () => { const output = outputCapture(); const client = fakeClient({ @@ -4781,15 +4692,6 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = expect(output.stdout).toContain("Install android 35 on wrk_1: waiting for 0s, 3 waiters\n"); }); - it("says worker on a worker", async () => { - const output = outputCapture(); - const environment = output.environmentWith({ connectAdmin: async () => fakeClient() }); - - await runCli(["status"], environment); - - expect(output.stdout).toContain("Daemon: running (worker)"); - }); - it("prints each device's mode and whether it serves a request naming no mode", async () => { const output = outputCapture(); const spec = { @@ -5242,103 +5144,74 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( expect(capturedInput?.noWait).toBe(true); }); - it("maps --image-tag onto the contract's imageTag input field, and sends none without it", async () => { - const inputs: Record[] = []; - const client = fakeClient({ - requestLease: (input) => { - inputs.push(input as unknown as Record); - return Promise.resolve({ - device: { - physical: false, - id: "dev_1", - driverDeviceId: "dev_1", - spec: { physical: false, platform: "android", model: "Pixel 8", osVersion: "34" }, - mode: "full", - }, - environment: {}, - lease: { - id: "lse_1", - deviceId: "dev_1", - requesterId: "test-requester", - ownerId: "test-requester", - grantedAt: 0, - lastRenewedAt: 0, - idChosenByRequester: false, - ttlMs: 60_000, - ttlDeadline: 60_000, - }, - timing: { - estimatedProvisionMs: 0, - estimatedBootMs: 0, - estimatedReclaimMs: 0, - estimatedReadyMs: 0, - }, - }); - }, - }); - const lease = ["lease", "--platform", "android", "--device", "Pixel 8", "--detach"]; - - await runCli( - [...lease, "--image-tag", "google_apis_playstore"], - outputCapture().environmentWith({ connectAdmin: async () => client }), - ); - await runCli(lease, outputCapture().environmentWith({ connectAdmin: async () => client })); - - expect(inputs[0]?.imageTag).toBe("google_apis_playstore"); - expect(inputs[1]).not.toHaveProperty("imageTag"); - }); - - it("sends physical: true for --physical, and no physical field without it", async () => { - const inputs: Record[] = []; - const client = fakeClient({ - requestLease: (input) => { - inputs.push(input as unknown as Record); - return Promise.resolve({ - device: { - class: "phone", - driverDeviceId: "00008110-001A2B3C4D5E", - id: "dev_1", - physical: true, - spec: { + it.each([ + { + flag: "--image-tag", + field: "imageTag", + value: "google_apis_playstore", + lease: ["lease", "--platform", "android", "--device", "Pixel 8", "--detach"], + flagArgs: ["--image-tag", "google_apis_playstore"], + }, + { + flag: "--physical", + field: "physical", + value: true, + lease: ["lease", "--platform", "ios", "--detach"], + flagArgs: ["--physical"], + }, + ])( + "maps $flag onto the contract's $field input field, and sends none without it", + async ({ field, value, lease, flagArgs }) => { + const inputs: Record[] = []; + const client = fakeClient({ + requestLease: (input) => { + inputs.push(input as unknown as Record); + return Promise.resolve({ + device: { class: "phone", - model: "iPhone 15 Pro", - osVersion: "18.4", + driverDeviceId: "00008110-001A2B3C4D5E", + id: "dev_1", physical: true, - platform: "ios", + spec: { + class: "phone", + model: "iPhone 15 Pro", + osVersion: "18.4", + physical: true, + platform: "ios", + }, }, - }, - environment: {}, - lease: { - id: "lse_1", - deviceId: "dev_1", - requesterId: "test-requester", - ownerId: "test-requester", - grantedAt: 0, - lastRenewedAt: 0, - idChosenByRequester: false, - ttlMs: 60_000, - ttlDeadline: 60_000, - }, - timing: { - estimatedProvisionMs: 0, - estimatedBootMs: 0, - estimatedReclaimMs: 0, - estimatedReadyMs: 0, - }, - }); - }, - }); - const lease = ["lease", "--platform", "ios", "--detach"]; + environment: {}, + lease: { + id: "lse_1", + deviceId: "dev_1", + requesterId: "test-requester", + ownerId: "test-requester", + grantedAt: 0, + lastRenewedAt: 0, + idChosenByRequester: false, + ttlMs: 60_000, + ttlDeadline: 60_000, + }, + timing: { + estimatedProvisionMs: 0, + estimatedBootMs: 0, + estimatedReclaimMs: 0, + estimatedReadyMs: 0, + }, + }); + }, + }); - await runCli( - [...lease, "--physical"], - outputCapture().environmentWith({ connectAdmin: async () => client }), - ); - await runCli(lease, outputCapture().environmentWith({ connectAdmin: async () => client })); + await runCli( + [...lease, ...flagArgs], + outputCapture().environmentWith({ connectAdmin: async () => client }), + ); + await runCli(lease, outputCapture().environmentWith({ connectAdmin: async () => client })); - expect(inputs[0]?.physical).toBe(true); - expect(inputs[1]).not.toHaveProperty("physical"); - }); + expect(inputs[0]?.[field]).toBe(value); + expect(inputs[1]).not.toHaveProperty(field); + }, + ); it("fails the removed full flag as an unknown option, before connecting", async () => { const output = outputCapture(); @@ -7752,25 +7625,30 @@ describe("simlock lease: a request names a model, a class, or nothing", () => { return sent; } - it("sends neither model nor class for a lease with only a platform", async () => { - const sent = await sentFor(["--platform", "ios"]); - - expect(sent).toMatchObject({ platform: "ios" }); - expect(sent).not.toHaveProperty("model"); - expect(sent).not.toHaveProperty("class"); - }); - - it("sends the class for --class, and no model", async () => { - const sent = await sentFor(["--platform", "ios", "--class", "phone"]); - - expect(sent).toMatchObject({ class: "phone", platform: "ios" }); - expect(sent).not.toHaveProperty("model"); - }); - - it("sends both fields for --class beside --device, leaving the refusal to the daemon", async () => { - const sent = await sentFor(["--platform", "ios", "--class", "phone", "--device", "iPhone 16"]); + it.each([ + { + name: "neither model nor class for a lease with only a platform", + args: ["--platform", "ios"], + present: { platform: "ios" }, + absent: ["model", "class"], + }, + { + name: "the class for --class, and no model", + args: ["--platform", "ios", "--class", "phone"], + present: { class: "phone", platform: "ios" }, + absent: ["model"], + }, + { + name: "both fields for --class beside --device, leaving the refusal to the daemon", + args: ["--platform", "ios", "--class", "phone", "--device", "iPhone 16"], + present: { class: "phone", model: "iPhone 16", platform: "ios" }, + absent: [], + }, + ])("sends $name", async ({ args, present, absent }) => { + const sent = await sentFor(args); - expect(sent).toMatchObject({ class: "phone", model: "iPhone 16", platform: "ios" }); + expect(sent).toMatchObject(present); + for (const key of absent) expect(sent).not.toHaveProperty(key); }); it("names --class in the lease usage text, with --device optional", async () => { @@ -8194,21 +8072,27 @@ describe("CLI: stats", () => { expect(lines).toContain("Totals"); }); - it("prints the HISTORY_NOT_KEPT message and exits with its code when the window ends before the history", async () => { - const { output, run } = statsRun(["--since", "30d"], async () => { - throw fromWireError( - "HISTORY_NOT_KEPT", - "The history does not reach back to the end of that window; its figures start at 2026-10-05T11:59:00.000Z.", - { oldestTs: NOW - 60_000 }, - ); - }); + it.each([ + ["", ["--since", "30d"]], + [" with --csv", ["--since", "30d", "--csv"]], + ])( + "prints the HISTORY_NOT_KEPT message on stderr, nothing on stdout, and exits with its code when the window ends before the history%s", + async (_name, args) => { + const { output, run } = statsRun(args, async () => { + throw fromWireError( + "HISTORY_NOT_KEPT", + "The history does not reach back to the end of that window; its figures start at 2026-10-05T11:59:00.000Z.", + { oldestTs: NOW - 60_000 }, + ); + }); - await expect(run).resolves.toBe(12); + await expect(run).resolves.toBe(12); - expect(output.stdout).toBe(""); - expect(output.stderr).toContain('"code":"HISTORY_NOT_KEPT"'); - expect(output.stderr).toContain("its figures start at 2026-10-05T11:59:00.000Z"); - }); + expect(output.stdout).toBe(""); + expect(output.stderr).toContain('"code":"HISTORY_NOT_KEPT"'); + expect(output.stderr).toContain("its figures start at 2026-10-05T11:59:00.000Z"); + }, + ); const LEDGER_HEADER = "requestId,requester,label,platform,model,workerId,source,requestedAt,grantedAt,rejectedAt,endedAt,waitMs,heldMs,turnaroundMs,outcome,probe,reason,endReason"; @@ -8273,19 +8157,6 @@ describe("CLI: stats", () => { expect(whole.output.stdout.startsWith(LEDGER_HEADER)).toBe(true); }); - it("simlock stats --csv on an error (HISTORY_NOT_KEPT) writes the error line on stderr, nothing on stdout, and exits 12", async () => { - const { output, run } = statsRun(["--since", "30d", "--csv"], async () => { - throw fromWireError("HISTORY_NOT_KEPT", "The history does not reach back.", { - oldestTs: NOW - 60_000, - }); - }); - - await expect(run).resolves.toBe(12); - - expect(output.stdout).toBe(""); - expect(output.stderr).toContain('"code":"HISTORY_NOT_KEPT"'); - }); - it("simlock stats refuses --csv with --json as a usage error, exit 2", async () => { const accepted = statsRun(["--csv"], async (window) => usageAnswer(window, { requests: [] })); const both = statsRun(["--csv", "--json"], async (window) => usageAnswer(window)); diff --git a/src/contract/errors.test.ts b/src/contract/errors.test.ts index 54c196733..3cd18b509 100644 --- a/src/contract/errors.test.ts +++ b/src/contract/errors.test.ts @@ -112,12 +112,6 @@ describe("SimlockError", () => { }); }); -describe("NO_CAPACITY", () => { - it("is among the codes whose details are declared", () => { - expect(CODES_WITH_DECLARED_DETAILS.has("NO_CAPACITY")).toBe(true); - }); -}); - describe("CAPABILITY_MISSING", () => { it("maps CAPABILITY_MISSING to HTTP 422 and CLI exit 12 as a domain error whose details name the capabilities", () => { const table: Record = ERROR_TABLE; diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index ed0e761cd..f5b17ef62 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -8,7 +8,6 @@ import { requestedDevice, } from "./operations.js"; import { PUSH_SCHEMAS } from "./pushes.js"; -import { relayChannelSchema } from "./relay.js"; import type { Role } from "./roles.js"; import { platformCatalogSchema } from "./schemas.js"; @@ -1587,13 +1586,6 @@ describe("relay.request on a byte channel", () => { expect(parse(request)).toBe(false); }); - it("relayChannelSchema holds the same bound the operation uses", () => { - expect(relayChannelSchema.safeParse("a".repeat(32)).success).toBe(true); - expect(relayChannelSchema.safeParse("a".repeat(33)).success).toBe(false); - expect(relayChannelSchema.safeParse("").success).toBe(false); - expect(relayChannelSchema.safeParse("a b").success).toBe(false); - }); - it("OPERATIONS has no relay.body and PUSH_SCHEMAS has no relay-chunk", () => { expect(Object.keys(OPERATIONS)).not.toContain("relay.body"); expect(Object.keys(PUSH_SCHEMAS)).not.toContain("relay-chunk"); diff --git a/src/contract/protocol.test.ts b/src/contract/protocol.test.ts index 5f06d3ed2..32b05af41 100644 --- a/src/contract/protocol.test.ts +++ b/src/contract/protocol.test.ts @@ -4,7 +4,6 @@ import { helloRequestSchema, negotiateProtocolVersion, normalizeProtocolVersion, - PROTOCOL_VERSION_RANGE, } from "./protocol.js"; describe("negotiateProtocolVersion", () => { @@ -45,9 +44,3 @@ describe("helloRequestSchema", () => { expect(() => helloRequestSchema.parse({ clientVersion: "1.0.0" })).toThrow(); }); }); - -describe("PROTOCOL_VERSION_RANGE", () => { - it("is one above the base branch's, for the alerts.test operation", () => { - expect(PROTOCOL_VERSION_RANGE).toEqual({ max: 52, min: 52 }); - }); -}); diff --git a/src/contract/schemas.test.ts b/src/contract/schemas.test.ts index 197bb820f..83e6323d5 100644 --- a/src/contract/schemas.test.ts +++ b/src/contract/schemas.test.ts @@ -670,32 +670,6 @@ describe("platformCatalogSchema classDefaults", () => { }); }); -describe("the status device entry's absent state (ADR 0022 §7)", () => { - const absent = { - class: "phone", - driverDeviceId: "00008110-001A2B3C4D5E", - id: "dev_7", - physical: true, - servesDefaultMode: false, - spec: { model: "iPhone 15 Pro", osVersion: "18.4", physical: true, platform: "ios" }, - state: "absent", - }; - - it("the status device entry and the worker view accept state absent and each absentReason, and refuse another reason", () => { - const parsed = (device: object) => statusDeviceSchema.safeParse(device); - - for (const absentReason of ["locked", "untrusted", "not-present"] as const) { - const result = parsed({ ...absent, absentReason }); - expect(result.success, `absent (${absentReason})`).toBe(true); - expect(result.success ? result.data : undefined).toMatchObject({ - absentReason, - state: "absent", - }); - } - expect(parsed({ ...absent, absentReason: "unplugged" }).success).toBe(false); - }); -}); - describe("doctorReportSchema's module-unavailable finding", () => { const finding = { kind: "module-unavailable", diff --git a/src/core/capacity/observer.test.ts b/src/core/capacity/observer.test.ts index 6504ca348..e4b9c13cf 100644 --- a/src/core/capacity/observer.test.ts +++ b/src/core/capacity/observer.test.ts @@ -1,9 +1,7 @@ import { describe, expect, it } from "vitest"; -import { EventBus } from "../../bus/index.js"; -import { FakeClock } from "../../ports/index.js"; import type { CapacityFigures } from "./figures.js"; -import { CapacityObserver, capacityChangedPayload } from "./observer.js"; +import { capacityChangedPayload } from "./observer.js"; function figures(running: number, options: { ramBudget?: boolean } = {}): CapacityFigures { const entry = { maxRunning: 2, overLimit: false, reserved: 0, running }; @@ -17,42 +15,7 @@ function figures(running: number, options: { ramBudget?: boolean } = {}): Capaci }; } -function observer(current: () => CapacityFigures) { - const bus = new EventBus(new FakeClock(1_000)); - const emitted = () => - bus - .replay() - .filter((event) => event.event === "capacity.changed") - .map((event) => event.payload); - return { emitted, observer: new CapacityObserver({ eventBus: bus, figures: current }) }; -} - describe("CapacityObserver", () => { - it("emits nothing until it is started, then once", () => { - const { emitted, observer: subject } = observer(() => figures(1)); - - subject.changed(); - expect(emitted()).toEqual([]); - - subject.start(); - expect(emitted()).toHaveLength(1); - }); - - it("emits again only when the figures differ from the last emitted", () => { - let running = 1; - const { emitted, observer: subject } = observer(() => figures(running)); - subject.start(); - - subject.changed(); - running = 2; - subject.changed(); - subject.changed(); - - expect( - emitted().map((payload) => (payload as { ios: { running: number } }).ios.running), - ).toEqual([1, 2]); - }); - it("carries only running, maxRunning, reserved and warm per platform, and the budget's used and limit bytes", () => { expect(capacityChangedPayload(figures(1, { ramBudget: true }))).toEqual({ android: { maxRunning: 2, reserved: 0, running: 0, warm: 0 }, diff --git a/src/core/component-installer.test.ts b/src/core/component-installer.test.ts index 65f5e9ee5..5d640261c 100644 --- a/src/core/component-installer.test.ts +++ b/src/core/component-installer.test.ts @@ -411,32 +411,40 @@ describe("ComponentInstaller", () => { return heard; } - it("reports 100 before it settles as installed when the driver last reported 99.3", async () => { - await expect(heardUntilSettled("27.0", [12, 99.3])).resolves.toEqual([ - { stage: "downloading" }, - { percent: 12, stage: "downloading" }, - { percent: 99.3, stage: "downloading" }, - { percent: 100, stage: "downloading" }, - "settled: installed", - ]); - }); - - it("reports 100 before it settles as installed when the driver reported nothing", async () => { - await expect(heardUntilSettled("27.0", [])).resolves.toEqual([ - { stage: "downloading" }, - { percent: 100, stage: "downloading" }, - "settled: installed", - ]); - }); - - it("does not report 100 twice when the driver already reported 100", async () => { - await expect(heardUntilSettled("27.0", [50, 100])).resolves.toEqual([ - { stage: "downloading" }, - { percent: 50, stage: "downloading" }, - { percent: 100, stage: "downloading" }, - "settled: installed", - ]); - }); + it.each([ + { + reported: [12, 99.3], + heard: [ + { stage: "downloading" }, + { percent: 12, stage: "downloading" }, + { percent: 99.3, stage: "downloading" }, + { percent: 100, stage: "downloading" }, + "settled: installed", + ], + }, + { + reported: [], + heard: [ + { stage: "downloading" }, + { percent: 100, stage: "downloading" }, + "settled: installed", + ], + }, + { + reported: [50, 100], + heard: [ + { stage: "downloading" }, + { percent: 50, stage: "downloading" }, + { percent: 100, stage: "downloading" }, + "settled: installed", + ], + }, + ])( + "ends with exactly one 100 before it settles as installed, whatever the driver reported ($reported)", + async ({ reported, heard }) => { + await expect(heardUntilSettled("27.0", reported)).resolves.toEqual(heard); + }, + ); it("reports no final 100 for a failed install", async () => { await expect(heardUntilSettled("27.0", [40], {}, true)).resolves.toEqual([ @@ -1476,22 +1484,6 @@ describe("ComponentInstaller.remove", () => { expect(await harness.installer.list()).toMatchObject([{ version: "26.5" }]); }); - it("refuses a record whose receipt no longer matches what is installed with ComponentNotOwnedError and never calls removeComponent", async () => { - const harness = await createHarness(); - await harness.registry.recordComponent({ - installedAt: 1_000, - platform: "ios", - receipt: { install: "1", version: "26.5" }, - version: "26.5", - }); - - await expect(harness.installer.remove(removeIos("26.5"))).rejects.toBeInstanceOf( - ComponentNotOwnedError, - ); - expect(removals(harness.ios)).toEqual([]); - expect(harness.registry.snapshot.components).toHaveLength(1); - }); - it("refuses a record whose version is no longer installed saying none is installed, and a record whose version was installed again saying that one is not Simlock's, in a removal and a dry run alike", async () => { // 26.5 is on the machine with another receipt; 25.0 is not on the machine at all. const harness = await createHarness(); @@ -1516,6 +1508,9 @@ describe("ComponentInstaller.remove", () => { }); } expect(removals(harness.ios)).toEqual([]); + expect(harness.registry.snapshot.components).toContainEqual( + expect.objectContaining({ platform: "ios", version: "26.5" }), + ); }); it("removes a component whose receipt matches the record even when the listing names its version differently", async () => { @@ -1647,6 +1642,9 @@ describe("ComponentInstaller.remove", () => { devices: 1, foreignDevices: 0, }); + await expect( + harness.installer.remove(removeIos("27.0", { dryRun: true })), + ).rejects.toMatchObject({ devices: 1, foreignDevices: 0, name: "ComponentInUseError" }); expect(removals(harness.ios)).toEqual([]); release(); @@ -1861,15 +1859,6 @@ describe("ComponentInstaller.remove", () => { expect(await harness.installer.list()).toMatchObject([{ devices: 1, version: "27.0" }]); }); - it("refuses a dry run with ComponentInUseError when a Simlock device uses the component", async () => { - const harness = await withSimlockInstall(); - harness.installer.claimProvision({ osVersion: "27.0", platform: "ios" }); - - await expect( - harness.installer.remove(removeIos("27.0", { dryRun: true })), - ).rejects.toMatchObject({ devices: 1, foreignDevices: 0, name: "ComponentInUseError" }); - }); - it("refuses with ComponentInstallerClosedError once the daemon has stopped, without reading the listing", async () => { const harness = await withSimlockInstall(); await harness.installer.close(); diff --git a/src/core/config.test.ts b/src/core/config.test.ts index ca295a1e3..fe4fd8e7f 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -137,6 +137,7 @@ describe("loadConfig", () => { }); expect(Object.isFrozen(config)).toBe(true); expect(Object.isFrozen(resourceOptions(config).limits)).toBe(true); + expect(configSchema.shape.eventLog.parse(config.eventLog)).toEqual(config.eventLog); }); it("defaults exec.timeoutMs to ten minutes and rejects a non-positive one", async () => { @@ -208,19 +209,6 @@ describe("loadConfig", () => { }); }); - it("reports eventLog.retention and eventLog.maxBytes at their defaults", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - - const config = await loadConfig({ configPath, filesystem, systemStats: createStats() }); - - expect(config.eventLog).toEqual({ - retention: 7 * 24 * 60 * 60 * 1000, - maxBytes: 256 * 1024 * 1024, - }); - expect(configSchema.shape.eventLog.parse(config.eventLog)).toEqual(config.eventLog); - }); - it("rejects a non-positive or fractional eventLog.retention and eventLog.maxBytes, naming the key", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); @@ -456,12 +444,6 @@ describe("loadConfig", () => { ]); }); - it("rejects a target with a count of 0 naming warmPool.targets[0].count", async () => { - await expect( - load({ targets: [{ count: 0, model: "iPhone 17", platform: "ios" }] }), - ).rejects.toThrow("warmPool.targets[0].count"); - }); - it("rejects a target that names a class naming warmPool.targets[1].class", async () => { await expect( load({ @@ -473,12 +455,6 @@ describe("loadConfig", () => { ).rejects.toThrow("warmPool.targets[1].class"); }); - it("rejects a target of an unknown platform naming warmPool.targets[0].platform", async () => { - await expect( - load({ targets: [{ count: 1, model: "iPhone 17", platform: "tvos" }] }), - ).rejects.toThrow("warmPool.targets[0].platform"); - }); - it.each([ [ "a missing model", @@ -495,6 +471,16 @@ describe("loadConfig", () => { { count: 1, model: "iPhone 17" }, 'Invalid config value for "warmPool.targets[0].platform"', ], + [ + "a count of 0", + { count: 0, model: "iPhone 17", platform: "ios" }, + 'Invalid config value for "warmPool.targets[0].count": expected a positive integer', + ], + [ + "an unknown platform", + { count: 1, model: "iPhone 17", platform: "tvos" }, + 'Invalid config value for "warmPool.targets[0].platform"', + ], [ "a missing count", { model: "iPhone 17", platform: "ios" }, @@ -886,17 +872,24 @@ describe("loadConfig", () => { }, ); - it("warns about unknown keys without rejecting the file", async () => { - const filesystem = new MemoryFilesystem(); - const warn = vi.fn(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic(configPath, JSON.stringify({ limits: { web: {} } })); + it.each([ + [{ limits: { web: {} } }, "limits.web"], + [{ health: { maxBoltCount: 7 } }, "health.maxBoltCount"], + [{ ios: { slim: { turboMode: true } } }, "ios.slim.turboMode"], + ])( + "warns about an unknown key, nested or not, without rejecting the file: %j", + async (contents, key) => { + const filesystem = new MemoryFilesystem(); + const warn = vi.fn(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic(configPath, JSON.stringify(contents)); - await expect( - loadConfig({ configPath, filesystem, systemStats: createStats(), warn }), - ).resolves.toBeDefined(); - expect(warn).toHaveBeenCalledWith('Unknown config key: "limits.web"'); - }); + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats(), warn }), + ).resolves.toBeDefined(); + expect(warn).toHaveBeenCalledWith(`Unknown config key: "${key}"`); + }, + ); it("applies a file-level health override", async () => { const filesystem = new MemoryFilesystem(); @@ -953,18 +946,6 @@ describe("loadConfig", () => { ).rejects.toThrow(path); }); - it("warns about an unknown key nested under health without rejecting the file", async () => { - const filesystem = new MemoryFilesystem(); - const warn = vi.fn(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic(configPath, JSON.stringify({ health: { maxBoltCount: 7 } })); - - await expect( - loadConfig({ configPath, filesystem, systemStats: createStats(), warn }), - ).resolves.toBeDefined(); - expect(warn).toHaveBeenCalledWith('Unknown config key: "health.maxBoltCount"'); - }); - it("applies a file-level downloads override", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); @@ -1192,21 +1173,6 @@ describe("loadConfig", () => { ).rejects.toThrow("ios.slim.categories"); }); - it("warns about an unknown key nested under ios.slim without rejecting the file", async () => { - const filesystem = new MemoryFilesystem(); - const warn = vi.fn(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - configPath, - JSON.stringify({ ios: { slim: { turboMode: true } } }), - ); - - await expect( - loadConfig({ configPath, filesystem, systemStats: createStats(), warn }), - ).resolves.toBeDefined(); - expect(warn).toHaveBeenCalledWith('Unknown config key: "ios.slim.turboMode"'); - }); - it("defaults android.emulator to a windowed launch with the emulator's GPU, audio, and boot animation", async () => { const config = await loadConfig({ configPath, @@ -1321,38 +1287,27 @@ describe("loadConfig", () => { const config = await loadConfig({ configPath, filesystem, systemStats: createStats() }); - expect(config[platform].defaultModels[deviceClass]).toEqual( - typeof value === "string" ? [value] : value, - ); + expect(config[platform].defaultModels).toStrictEqual({ + [deviceClass]: typeof value === "string" ? [value] : value, + }); }, ); - it("stores a string ios.defaultModels value as a one-element list", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - configPath, - JSON.stringify({ ios: { defaultModels: { phone: "iPhone 15" } } }), - ); - - const config = await loadConfig({ configPath, filesystem, systemStats: createStats() }); - - expect(config.ios.defaultModels).toStrictEqual({ phone: ["iPhone 15"] }); - }); - it.each([ - [{ phone: "" }, "ios.defaultModels.phone"], - [{ phone: [] }, "ios.defaultModels.phone"], - [{ phone: ["iPhone 15", ""] }, "ios.defaultModels.phone"], - [{ phone: 15 }, "ios.defaultModels.phone"], - [{ phone: [15] }, "ios.defaultModels.phone"], - [{ phone: [["iPhone 15"]] }, "ios.defaultModels.phone"], - [{ mobile: "iPhone 15" }, "ios.defaultModels.mobile"], - [{ constructor: "iPhone 15" }, "ios.defaultModels.constructor"], - ])("refuses ios.defaultModels %j, naming the key", async (defaultModels, path) => { + ["ios", { phone: "" }, "ios.defaultModels.phone"], + ["ios", { phone: [] }, "ios.defaultModels.phone"], + ["ios", { phone: ["iPhone 15", ""] }, "ios.defaultModels.phone"], + ["ios", { phone: 15 }, "ios.defaultModels.phone"], + ["ios", { phone: [15] }, "ios.defaultModels.phone"], + ["ios", { phone: [["iPhone 15"]] }, "ios.defaultModels.phone"], + ["ios", { mobile: "iPhone 15" }, "ios.defaultModels.mobile"], + ["ios", { constructor: "iPhone 15" }, "ios.defaultModels.constructor"], + ["android", { phone: [] }, "android.defaultModels.phone"], + ["android", { fridge: "Pixel 8" }, "android.defaultModels.fridge"], + ])("refuses %s.defaultModels %j, naming the key", async (platform, defaultModels, path) => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic(configPath, JSON.stringify({ ios: { defaultModels } })); + await filesystem.writeFileAtomic(configPath, JSON.stringify({ [platform]: { defaultModels } })); await expect( loadConfig({ configPath, filesystem, systemStats: createStats() }), @@ -1375,26 +1330,6 @@ describe("loadConfig", () => { ); }); - it("refuses an empty android.defaultModels list and a key that is not a class, naming the key", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/home/agent/.simlock"); - await filesystem.writeFileAtomic( - configPath, - JSON.stringify({ android: { defaultModels: { phone: [] } } }), - ); - await expect( - loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).rejects.toThrow('Invalid config value for "android.defaultModels.phone"'); - - await filesystem.writeFileAtomic( - configPath, - JSON.stringify({ android: { defaultModels: { fridge: "Pixel 8" } } }), - ); - await expect( - loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).rejects.toThrow('Invalid config value for "android.defaultModels.fridge"'); - }); - it("applies a file-level stalledTransition override", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); @@ -1532,12 +1467,6 @@ describe("loadConfig capacity strategies", () => { }); } - it("selects the resource strategy when nothing names one", async () => { - const config = await load({}); - - expect(config.capacity.strategy).toBe("resource"); - }); - it("defaults the fixed strategy to a machine-independent pin", async () => { const config = await load({ capacity: { strategy: "fixed" } }); @@ -1891,14 +1820,6 @@ describe("loadConfig modes (ADR 0005)", () => { await expect(load({ gateway: { token: "join-secret" } })).rejects.toThrow("gateway.url"); }); - it("does not pair those keys on a gateway, which reads neither", async () => { - const warn = vi.fn(); - await expect( - load({ gateway: { url: "ws://fleet.example" } }, { role: "gateway", warn }), - ).resolves.toBeDefined(); - expect(warn).toHaveBeenCalledWith(expect.stringContaining('Ignoring "gateway.url"')); - }); - it.each(["http://fleet.example/v1/uplink", "fleet.example", "not a url"])( "rejects a gateway.url that is not a WebSocket URL: %s", async (url) => { diff --git a/src/core/device-operation-claims.test.ts b/src/core/device-operation-claims.test.ts index c549c3c85..6ecde8bb6 100644 --- a/src/core/device-operation-claims.test.ts +++ b/src/core/device-operation-claims.test.ts @@ -3,16 +3,6 @@ import { describe, expect, it } from "vitest"; import { DeviceOperationClaims } from "./device-operation-claims.js"; describe("DeviceOperationClaims", () => { - it("grants only one operation claim per device", () => { - const claims = new DeviceOperationClaims(); - const boot = claims.tryClaim("device-1", "boot"); - - expect(boot).toBeDefined(); - expect(claims.tryClaim("device-1", "cleanup")).toBeUndefined(); - expect(claims.operationFor("device-1")).toBe("boot"); - expect(claims.isClaimed("device-1")).toBe(true); - }); - it("releases claims idempotently and permits the next operation", () => { const claims = new DeviceOperationClaims(); const cleanup = claims.tryClaim("device-1", "cleanup"); diff --git a/src/core/device-provisioner.test.ts b/src/core/device-provisioner.test.ts index 0ef89b87a..ae3f83c0a 100644 --- a/src/core/device-provisioner.test.ts +++ b/src/core/device-provisioner.test.ts @@ -362,87 +362,59 @@ describe("DeviceProvisioner and a component removal (ADR 0010 §8)", () => { return harness.driver.calls.filter((call) => call.operation === operation).length; } - it("refuses a device on a version being removed before the driver creates it, registers nothing and releases the reservation", async () => { - const harness = await withSimlockRuntime(); - harness.driver.holdRemovals(); - const removing = harness.components.remove(removal); - await vi.waitFor(() => expect(driverCalls(harness, "removeComponent")).toBe(1)); - const reserved = reservation(); - - await expect(harness.provisioner.provision(spec, { reservation: reserved })).rejects.toThrow( - ComponentBeingRemovedError, - ); - - expect(driverCalls(harness, "provision")).toBe(0); - expect(harness.registry.snapshot.devices).toEqual([]); - expect(reserved.releaseCount()).toBe(1); - harness.driver.releaseRemovals(); - await expect(removing).resolves.toMatchObject({ outcome: "removed" }); - }); - - it("counts a device the driver is still creating as in use, so a removal started meanwhile is refused", async () => { - const harness = await withSimlockRuntime({ provision: 50 }); - const provisioning = harness.provisioner.provision(spec, { reservation: reservation() }); - await vi.waitFor(() => expect(driverCalls(harness, "provision")).toBe(1)); - expect(harness.registry.snapshot.devices).toEqual([]); - - await expect(harness.components.remove(removal)).rejects.toMatchObject({ - devices: 1, - foreignDevices: 0, - name: "ComponentInUseError", - }); - expect(driverCalls(harness, "removeComponent")).toBe(0); - - harness.clock.advance(50); - await provisioning; - // Once registered the device is counted by the registry alone, not twice. - const listed = await harness.components.list("ios"); - expect(listed.find((component) => component.version === "26.5")).toMatchObject({ - devices: 1, - }); - }); - - describe("for a spec with an image tag, which is still a device of its platform and version", () => { - const tagged = { ...spec, imageTag: "google_apis_playstore" }; - - it("refuses it while that version is being removed", async () => { + const tagged = { ...spec, imageTag: "google_apis_playstore" }; + + it.each([ + ["a spec", spec], + ["a spec with an image tag", tagged], + ])( + "refuses %s on a version being removed before the driver creates it, registers nothing and releases the reservation", + async (_name, candidate) => { const harness = await withSimlockRuntime(); harness.driver.holdRemovals(); const removing = harness.components.remove(removal); await vi.waitFor(() => expect(driverCalls(harness, "removeComponent")).toBe(1)); + const reserved = reservation(); await expect( - harness.provisioner.provision(tagged, { reservation: reservation() }), + harness.provisioner.provision(candidate, { reservation: reserved }), ).rejects.toThrow(ComponentBeingRemovedError); expect(driverCalls(harness, "provision")).toBe(0); + expect(harness.registry.snapshot.devices).toEqual([]); + expect(reserved.releaseCount()).toBe(1); harness.driver.releaseRemovals(); await expect(removing).resolves.toMatchObject({ outcome: "removed" }); - }); + }, + ); - it("counts it as in use while it is created and once it is registered", async () => { + it.each([ + ["a spec", spec], + ["a spec with an image tag", tagged], + ])( + "counts a device of %s the driver is still creating as in use, so a removal started meanwhile is refused", + async (_name, candidate) => { const harness = await withSimlockRuntime({ provision: 50 }); - const provisioning = harness.provisioner.provision(tagged, { reservation: reservation() }); + const provisioning = harness.provisioner.provision(candidate, { reservation: reservation() }); await vi.waitFor(() => expect(driverCalls(harness, "provision")).toBe(1)); + expect(harness.registry.snapshot.devices).toEqual([]); await expect(harness.components.remove(removal)).rejects.toMatchObject({ devices: 1, + foreignDevices: 0, name: "ComponentInUseError", }); + expect(driverCalls(harness, "removeComponent")).toBe(0); harness.clock.advance(50); await provisioning; - expect(harness.registry.snapshot.devices.map((device) => device.spec)).toEqual([tagged]); + expect(harness.registry.snapshot.devices.map((device) => device.spec)).toEqual([candidate]); const listed = await harness.components.list("ios"); expect(listed.find((component) => component.version === "26.5")).toMatchObject({ devices: 1, }); - await expect(harness.components.remove(removal)).rejects.toMatchObject({ - devices: 1, - name: "ComponentInUseError", - }); - }); - }); + }, + ); it("is the only code in src that asks a driver to provision or registers a device", () => { const sources = sourceFilesRecursive(srcDir); diff --git a/src/core/doctor.test.ts b/src/core/doctor.test.ts index 48affb235..13264ed21 100644 --- a/src/core/doctor.test.ts +++ b/src/core/doctor.test.ts @@ -833,31 +833,16 @@ describe("Doctor", () => { }); describe("stalled transitions", () => { - it("isStalledTransition holds for a provisioning device past its threshold with no claim", async () => { + it("isStalledTransition does not hold for a provisioning device whose platform has no driver", async () => { const clock = new FakeClock(10_000); const registry = await loadRegistry(clock, new EventBus(clock)); - const driver = new FakeDriver({ - clock, - estimateMs: { boot: 2_000, provision: 1_000 }, - platform: "ios", - }); const device = await registry.registerDevice({ driverData: { fakeDeviceId: "simlock-stuck" }, driverDeviceId: "simlock-stuck", provisionDuration: 0, spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, }); - const stalled = (now: number) => - isStalledTransition({ - claims: new DeviceOperationClaims(), - config: config().stalledTransition, - device, - driver, - now, - }); - expect(stalled(10_000 + 9_000)).toBe(false); - expect(stalled(10_000 + 9_001)).toBe(true); // No driver for the platform: nothing to measure against, so no stall. expect( isStalledTransition({ @@ -870,39 +855,6 @@ describe("Doctor", () => { ).toBe(false); }); - it("isStalledTransition does not hold for a device with a live operation claim", async () => { - const clock = new FakeClock(10_000); - const registry = await loadRegistry(clock, new EventBus(clock)); - const driver = new FakeDriver({ clock, estimateMs: { reclaim: 2_000 }, platform: "ios" }); - const device = await readyDevice(registry, "simlock-erasing", "ios"); - const lease = await registry.createLease({ - deviceId: device.id, - requesterId: "agent", - ownerId: "agent", - ttlMs: 60_000, - ttlDeadline: 999_999, - }); - await registry.beginRelease(lease.id); - const reclaiming = registry.snapshot.devices.find((entry) => entry.id === device.id); - expect(reclaiming?.state).toBe("reclaiming"); - const claims = new DeviceOperationClaims(); - const claim = claims.tryClaim(device.id, "reclaim"); - const stalled = () => - isStalledTransition({ - claims, - config: config().stalledTransition, - device: reclaiming ?? device, - driver, - // Far past the reclaim threshold (2_000 * 3). - now: clock.now() + 600_000, - }); - - expect(stalled()).toBe(false); - // The same device, the same age, is a stall once no live operation accounts for it. - claim?.release(); - expect(stalled()).toBe(true); - }); - it("the doctor's stalled-transition finding is unchanged", async () => { // The finding a stalled provisioning device and a stalled reclaiming device produced // before the stall test became `isStalledTransition`, field for field, and none a moment @@ -972,47 +924,6 @@ describe("Doctor", () => { ]); }); - it("reports a stalled-transition finding for a provisioning device past its driver-derived threshold", async () => { - const clock = new FakeClock(10_000); - const eventBus = new EventBus(clock); - const registry = await loadTestRegistry({ - clock, - eventBus, - idGenerator: sequence(), - }); - const driver = new FakeDriver({ - clock, - estimateMs: { boot: 2_000, provision: 1_000 }, - platform: "ios", - }); - const device = await registry.registerDevice({ - driverData: { fakeDeviceId: "simlock-stuck" }, - driverDeviceId: "simlock-stuck", - provisionDuration: 0, - spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, - }); - clock.advance(9_001); - - const report = await new Doctor({ - decisions: new SerializedDecision(), - clock, - config: config(), - drivers: [driver], - eventBus, - registry, - }).reconcile(); - - expect(report.findings).toContainEqual({ - ageMs: 9_001, - deviceId: device.id, - enteredAt: 10_000, - kind: "stalled-transition", - platform: "ios", - state: "provisioning", - thresholdMs: 9_000, - }); - }); - it("does not report a stall for a device this daemon holds an operation claim on", async () => { // A backgrounded reclaim keeps its device in `reclaiming` for a full erase, which can // outlast the threshold. The claim, not the clock, says work is in progress; without it a @@ -1071,41 +982,6 @@ describe("Doctor", () => { ); }); - it("does not report a stalled-transition finding for a device still legitimately in-flight", async () => { - const clock = new FakeClock(10_000); - const eventBus = new EventBus(clock); - const registry = await loadTestRegistry({ - clock, - eventBus, - idGenerator: sequence(), - }); - const driver = new FakeDriver({ - clock, - estimateMs: { boot: 2_000, provision: 1_000 }, - platform: "ios", - }); - await registry.registerDevice({ - driverData: { fakeDeviceId: "simlock-slow" }, - driverDeviceId: "simlock-slow", - provisionDuration: 0, - spec: { physical: false, model: "Phone", osVersion: "1", platform: "ios" }, - }); - clock.advance(8_000); - - const report = await new Doctor({ - decisions: new SerializedDecision(), - clock, - config: config(), - drivers: [driver], - eventBus, - registry, - }).reconcile(); - - expect(report.findings.filter((finding) => finding.kind === "stalled-transition")).toEqual( - [], - ); - }); - it("reports a stalled-transition finding for a reclaiming device whose emulator was killed out from under the daemon", async () => { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); @@ -1741,14 +1617,6 @@ describe("Doctor", () => { expect(driver.calls.map((call) => call.operation)).not.toContain("listManaged"); expect(report.findings).toEqual([]); }); - - it("is not required: without one, each driver is listed", async () => { - const { doctor, driver } = await setup(); - - await doctor.reconcile(); - - expect(driver.calls.map((call) => call.operation)).toContain("listManaged"); - }); }); it("reports a platform whose driver refused to start, with the reason it refused", async () => { @@ -2609,14 +2477,6 @@ describe("Doctor: optional module findings", () => { ); }); - it("returns the finding with prerequisites false too", async () => { - const { doctor } = await setup({ optionalModules: () => [unavailable] }); - - const report = await doctor.reconcile({ prerequisites: false }); - - expect(report.findings).toStrictEqual([unavailable]); - }); - it("logs a warning naming the error when optionalModules throws, contributes nothing, and still returns the other findings", async () => { const sink = new MemoryLogSink(); const { doctor } = await setup({ diff --git a/src/core/domain.test.ts b/src/core/domain.test.ts index be9cecf31..0b48b6631 100644 --- a/src/core/domain.test.ts +++ b/src/core/domain.test.ts @@ -324,22 +324,10 @@ describe("a physical device's state machine (ADR 0022 §2)", () => { }, ); - it("refuses ready -> shutdown, reclaiming -> shutdown, shutdown -> ready and any move into provisioning, which the virtual table still allows or has", () => { - expect(() => transition({ ...physicalDevice, state: "ready" }, "shutdown")).toThrow( - IllegalTransition, - ); - expect(() => transition({ ...physicalDevice, state: "reclaiming" }, "shutdown")).toThrow( - IllegalTransition, - ); - expect(() => transition({ ...physicalDevice, state: "ready" }, "provisioning")).toThrow( - IllegalTransition, - ); + it("refuses a physical record in shutdown any move to ready", () => { expect(() => transition({ ...physicalDevice, state: "shutdown" as unknown as "ready" }, "ready"), ).toThrow(IllegalTransition); - expect(transition({ ...baseDevice, state: "ready" }, "shutdown").state).toBe("shutdown"); - expect(transition({ ...baseDevice, state: "reclaiming" }, "shutdown").state).toBe("shutdown"); - expect(transition({ ...baseDevice, state: "shutdown" }, "ready").state).toBe("ready"); }); it("gives a transition into ready no driver-reported mode, whatever the update carries", () => { @@ -562,7 +550,7 @@ describe("a physical device's absent state (ADR 0022 §2, §8)", () => { } }; - it("a physical record may move ready, leased or reclaiming to absent, and absent to reclaiming, ready or deleted; quarantined -> absent and any virtual move to absent throw IllegalTransition", () => { + it("a physical record may move ready, leased or reclaiming to absent, and absent to reclaiming, ready or deleted; any virtual move to absent throws IllegalTransition", () => { for (const from of ["ready", "leased", "reclaiming"]) { expect(settle(physicalDevice, from, absent), `${from} -> absent`).toBe("absent"); } @@ -570,12 +558,6 @@ describe("a physical device's absent state (ADR 0022 §2, §8)", () => { expect(settle(physicalDevice, absent, to), `absent -> ${to}`).toBe(to); } - expect(() => - transition( - { ...physicalDevice, state: "quarantined" } as unknown as VirtualDevice, - absent as unknown as "ready", - ), - ).toThrow(IllegalTransition); for (const from of [ "provisioning", "ready", diff --git a/src/core/driver-catalog.test.ts b/src/core/driver-catalog.test.ts index 83272bc51..a5ec5f1c9 100644 --- a/src/core/driver-catalog.test.ts +++ b/src/core/driver-catalog.test.ts @@ -384,36 +384,41 @@ describe("DriverCatalog", () => { ).resolves.toEqual({ phone: "iPhone 17" }); }); - it("skips a configured name of another class and falls to the next name that counts", async () => { - await expect( - defaultsOf({ + it.each([ + { + case: "a configured name of another class", + options: { classes: { "iPad (A16)": "tablet", "iPhone 17": "phone", "iPhone 16": "phone" }, models: ["iPad (A16)", "iPhone 17", "iPhone 16"], - // The merged list: the configured iPad first, the built-in phones after it. preferences: ["iPad (A16)", "iPhone 17", "iPhone 16"], - }), - ).resolves.toEqual({ phone: "iPhone 17" }); - }); - - it("skips a name whose model has no class", async () => { - await expect( - defaultsOf({ + }, + expected: { phone: "iPhone 17" }, + }, + { + case: "a name whose model has no class", + options: { classes: { "iPhone 16": "phone" }, models: ["Mystery", "iPhone 16"], preferences: ["Mystery", "iPhone 16"], - }), - ).resolves.toEqual({ phone: "iPhone 16" }); - }); - - it("skips a name with no paired runtime for a later one that pairs", async () => { - await expect( - defaultsOf({ + }, + expected: { phone: "iPhone 16" }, + }, + { + case: "a name with no paired runtime", + options: { classes: { "iPhone 16": "phone", "iPhone 17": "phone" }, modelRuntimes: { "iPhone 16": ["18.4"], "iPhone 17": [] }, models: ["iPhone 17", "iPhone 16"], preferences: ["iPhone 17", "iPhone 16"], - }), - ).resolves.toEqual({ phone: "iPhone 16" }); + }, + expected: { phone: "iPhone 16" }, + }, + ] satisfies readonly { + readonly case: string; + readonly options: Parameters[0]; + readonly expected: Readonly>; + }[])("skips $case and falls to the next name that counts", async ({ options, expected }) => { + await expect(defaultsOf(options)).resolves.toEqual(expected); }); it("shows the first name of the class when none of them pairs with a runtime", async () => { diff --git a/src/core/driver.test.ts b/src/core/driver.test.ts index bccc9c929..93307be52 100644 --- a/src/core/driver.test.ts +++ b/src/core/driver.test.ts @@ -20,15 +20,6 @@ import type { ManagedDeviceLifecycle } from "./managed-device-lifecycle.js"; const gibibyte = 1024 ** 3; describe("DiskSpaceGuard", () => { - it("lets a single reservation through when it fits free space", async () => { - const filesystem = new MemoryFilesystem(10 * gibibyte); - const guard = new DiskSpaceGuard(); - - await expect(guard.reserve(filesystem, "ios", 6 * gibibyte, "/volume")).resolves.toBeInstanceOf( - Function, - ); - }); - it("rejects a reservation that alone exceeds free space with InsufficientDiskSpaceError naming required and available bytes", async () => { const filesystem = new MemoryFilesystem(4 * gibibyte); const guard = new DiskSpaceGuard(); @@ -319,19 +310,26 @@ describe("toDriverDevice", () => { }); describe("uninstallPlan", () => { - it("returns the listed-now apps not on the enrollment list, and the enrollment apps not listed now", () => { - expect( - uninstallPlan( - ["com.example.kept", "com.example.stray", "com.example.another"], - ["com.example.kept", "com.example.gone"], - ), - ).toEqual({ - missing: ["com.example.gone"], - uninstall: ["com.example.stray", "com.example.another"], - }); - }); - - it("returns nothing to uninstall and nothing missing when the two lists name the same apps", () => { - expect(uninstallPlan(["a", "b"], ["b", "a"])).toEqual({ missing: [], uninstall: [] }); - }); + it.each([ + { + case: "differing lists", + listed: ["com.example.kept", "com.example.stray", "com.example.another"], + enrolled: ["com.example.kept", "com.example.gone"], + expected: { + missing: ["com.example.gone"], + uninstall: ["com.example.stray", "com.example.another"], + }, + }, + { + case: "the same apps in another order", + listed: ["a", "b"], + enrolled: ["b", "a"], + expected: { missing: [], uninstall: [] }, + }, + ])( + "returns the listed-now apps not on the enrollment list, and the enrollment apps not listed now, for $case", + ({ listed, enrolled, expected }) => { + expect(uninstallPlan(listed, enrolled)).toEqual(expected); + }, + ); }); diff --git a/src/core/fake-driver.test.ts b/src/core/fake-driver.test.ts index 86c51721c..14722fda1 100644 --- a/src/core/fake-driver.test.ts +++ b/src/core/fake-driver.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest"; import { DriverCrashError, - type Driver, type PhysicalDriverDevice, PassthroughRefusedError, UnknownModelError, @@ -26,12 +25,6 @@ function passthroughFake(options: Partial): FakeDriver { } describe("FakeDriver", () => { - it("claims the tool names its options give in passthroughTools", () => { - const driver = passthroughFake({ passthroughTools: ["simctl", "devicectl"] }); - - expect(driver.passthroughTools).toEqual(["simctl", "devicectl"]); - }); - it("resolves the scripted passthrough command, handing it the tool, device, args and context", async () => { const seen: unknown[] = []; const driver = passthroughFake({ @@ -232,55 +225,6 @@ describe("FakeDriver", () => { ]); }); - it("implements the platform-agnostic Driver contract", () => { - const driver: Driver = new FakeDriver({ clock: new FakeClock(), platform: "ios" }); - - expect(driver.platform).toBe("ios"); - expect(driver.deviceRoot).toBe("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/fake/ios"); - expect(driver.leaseEnvironment(VIRTUAL_DEVICE)).toEqual({}); - }); - - it("carries the root and lease environment a test gives it", () => { - const driver = new FakeDriver({ - clock: new FakeClock(), - deviceRoot: "/tmp/devices/ios", - leaseEnvironment: { SIMLOCK_IOS_DEVICE_SET: "/tmp/devices/ios" }, - platform: "ios", - }); - - expect(driver.deviceRoot).toBe("/tmp/devices/ios"); - expect(driver.leaseEnvironment(VIRTUAL_DEVICE)).toEqual({ - SIMLOCK_IOS_DEVICE_SET: "/tmp/devices/ios", - }); - }); - - it("answers virtualLeaseEnvironment with its configured lease environment, and leaseEnvironment for a virtual device equals it", () => { - const driver = new FakeDriver({ - clock: new FakeClock(), - leaseEnvironment: { SIMLOCK_IOS_DEVICE_SET: "/tmp/devices/ios" }, - platform: "ios", - }); - - expect(driver.virtualLeaseEnvironment()).toEqual({ - SIMLOCK_IOS_DEVICE_SET: "/tmp/devices/ios", - }); - expect(driver.leaseEnvironment(VIRTUAL_DEVICE)).toEqual(driver.virtualLeaseEnvironment()); - }); - - it("reports a staged reality entry whatever it is named, the way a root does", () => { - const driver = new FakeDriver({ clock: new FakeClock(), platform: "ios" }); - driver.setManagedReality({ - devices: [ - { address: "addr", deviceId: "not-a-simlock-name", driverData: {}, runState: "running" }, - ], - processes: [], - }); - - return expect(driver.listManaged()).resolves.toMatchObject({ - devices: [{ deviceId: "not-a-simlock-name" }], - }); - }); - it.each([ ["a prepare boot of a slim-spec device", { mode: "slim", purpose: "prepare" }, "slim"], ["a recover boot of a slim-spec device", { mode: "slim", purpose: "recover" }, "full"], @@ -402,23 +346,6 @@ describe("FakeDriver", () => { expect(await new FakeDriver(options).listCatalog()).not.toHaveProperty("images"); }); - it("reports the model classes its options name, and none without them", async () => { - const options = { - availableOsVersions: ["35"], - clock: new FakeClock(), - knownModels: ["Pixel 8", "Television (1080p)"], - platform: "android" as const, - }; - - await expect( - new FakeDriver({ - ...options, - modelClasses: { "Pixel 8": "phone", "Television (1080p)": "tv" }, - }).listCatalog(), - ).resolves.toMatchObject({ modelClasses: { "Pixel 8": "phone", "Television (1080p)": "tv" } }); - expect((await new FakeDriver(options).listCatalog()).modelClasses).toEqual({}); - }); - it("reports the built-in preference lists its options name, and none without them", () => { const options = { clock: new FakeClock(), platform: "ios" as const }; @@ -428,20 +355,6 @@ describe("FakeDriver", () => { expect(new FakeDriver(options).defaultModels).toEqual({}); }); - it("reports the custom models its options name, and no customModels field without them", async () => { - const options = { - availableOsVersions: ["35"], - clock: new FakeClock(), - knownModels: ["Pixel 8", "My Tablet"], - platform: "android" as const, - }; - - await expect( - new FakeDriver({ ...options, customModels: ["My Tablet"] }).listCatalog(), - ).resolves.toMatchObject({ customModels: ["My Tablet"] }); - expect(await new FakeDriver(options).listCatalog()).not.toHaveProperty("customModels"); - }); - it("reads a scripted physical device by any of its IDs, answering with the first as canonical and defaults for what is unset", async () => { const driver = new FakeDriver({ clock: new FakeClock(), diff --git a/src/core/physical-enrollment.test.ts b/src/core/physical-enrollment.test.ts index 2765ff08b..101e7d32d 100644 --- a/src/core/physical-enrollment.test.ts +++ b/src/core/physical-enrollment.test.ts @@ -268,6 +268,9 @@ describe("PhysicalEnrollment", () => { }); held.release(); await expect(waiting).resolves.toMatchObject({ reenrolled: true }); + await expect(harness.core.enrollment.remove(UDID)).resolves.toMatchObject({ + state: "deleted", + }); }); it.each([ @@ -531,20 +534,6 @@ describe("PhysicalEnrollment", () => { ); }); - it("takes the enrollment claim of the device while its second inspection runs, and frees it after", async () => { - const harness = await build(); - const { device } = await harness.core.enrollment.add("ios", UDID); - const held = holdInspection(harness.driver, 2); - const waiting = harness.core.enrollment.add("ios", UDID); - await vi.waitFor(() => expect(held.reached).toHaveBeenCalled()); - - expect(harness.core.claims.claim(device.id)?.kind).toBe("enrollment"); - held.release(); - await waiting; - - expect(harness.core.claims.claim(device.id)).toBeUndefined(); - }); - it("answers UNKNOWN_DEVICE, naming the ID, to a remove of an ID with no record and of a deleted one", async () => { const harness = await build(); diff --git a/src/core/quarantine-coordinator.test.ts b/src/core/quarantine-coordinator.test.ts index 8f06fcdb0..862455557 100644 --- a/src/core/quarantine-coordinator.test.ts +++ b/src/core/quarantine-coordinator.test.ts @@ -519,43 +519,6 @@ describe("QuarantineCoordinator", () => { ]); }); - it("a quarantine retry that itself throws logs at error with the device id", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ clock, platform: "ios" }); - driver.failOn("reclaim", 1, new Error("erase still stuck")); - const sink = new MemoryLogSink(); - const harness = await createHarness({ - clock, - driver, - logger: new JsonLinesLogger({ clock, sink }), - }); - await harness.coordinator.enter({ - attemptedStrategy: "wipe", - kind: "purge-failed", - deviceId: harness.target.id, - duration: 0, - error: "boom", - leaseId: "lease-1", - }); - vi.spyOn(harness.registry, "recordQuarantineRetryFailure").mockRejectedValue( - new Error("state unwritable"), - ); - - harness.clock.advance(retryConfig.retryBackoffMs); - await flush(); - - expect(sink.records.filter((record) => record.level === "error")).toEqual([ - expect.objectContaining({ - module: "daemon.quarantine-coordinator", - fields: { - deviceId: harness.target.id, - error: "Error: state unwritable", - step: "retry", - }, - }), - ]); - }); - it("A failed quarantine delete retry logs the error and the attempt number.", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ clock, platform: "ios" }); @@ -1181,7 +1144,7 @@ describe("QuarantineCoordinator retry of a physical device that is not present ( { apps: [], ids: [FIRST], model: "iPhone 15 Pro", osVersion: "18.4" }, ]; - async function build(logger?: Logger) { + async function build() { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); const driver = new FakeDriver({ clock, physicalDevices: DEVICES, platform: "ios" }); @@ -1203,7 +1166,6 @@ describe("QuarantineCoordinator retry of a physical device that is not present ( config, drivers: [driver], eventBus, - ...(logger === undefined ? {} : { logger }), registry, state: testStateOf(registry), systemStats, @@ -1307,23 +1269,6 @@ describe("QuarantineCoordinator retry of a physical device that is not present ( expect(record(harness, id)).toMatchObject({ quarantineAttempts: 1, state: "quarantined" }); }); - it("a physical retry whose presence read rejects logs a warning naming the device, the presence step and the error", async () => { - const sink = new MemoryLogSink(); - const harness = await build(new JsonLinesLogger({ clock: new FakeClock(1_000), sink })); - const id = await enrollQuarantined(harness); - harness.driver.setPhysicalPresence(FIRST, true); - vi.spyOn(harness.driver, "listPresentPhysical").mockRejectedValueOnce(new Error("link down")); - - await advance(harness, harness.config.warmPool.quarantine.retryBackoffMs); - - expect(sink.records.filter((entry) => entry.level === "warn")).toEqual([ - expect.objectContaining({ - message: "quarantine presence read failed", - fields: { deviceId: id, error: "Error: link down", step: "presence" }, - }), - ]); - }); - it("a physical retry whose presence read rejects makes no reclaim or destroy call, keeps quarantineAttempts, and re-arms after health.probeIntervalMs", async () => { const harness = await build(); const id = await enrollQuarantined(harness); diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index 40e90342d..da6813e2a 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -501,28 +501,6 @@ describe("CleanupReaper", () => { harness.reaper.dispose(); }); - it("a cleanup run that throws is logged once, however many triggers joined it", async () => { - const sink = new MemoryLogSink(); - const rule: CleanupRule = { - evaluate: () => { - throw new Error("rule exploded"); - }, - name: "exploding-rule", - }; - const harness = await createHarness( - [rule], - {}, - { logger: new JsonLinesLogger({ clock: new FakeClock(1_000), sink }), tickMs: 10_000 }, - ); - - harness.eventBus.emit("daemon.started", { configSnapshot: {}, version: "test" }, "test"); - harness.eventBus.emit("daemon.started", { configSnapshot: {}, version: "test" }, "test"); - await flush(); - - expect(sink.records.map((record) => record.message)).toEqual(["scheduled cleanup run failed"]); - harness.reaper.dispose(); - }); - it("shuts down after T1 and destroys after T2 on periodic ticks following a release", async () => { const harness = await createHarness(automaticCleanupRules, {}, { tickMs: 10_000 }); const grant = await harness.engine.request(spec, { diff --git a/src/core/reclaim-coordinator.test.ts b/src/core/reclaim-coordinator.test.ts index f922d7cf6..a482cb280 100644 --- a/src/core/reclaim-coordinator.test.ts +++ b/src/core/reclaim-coordinator.test.ts @@ -841,20 +841,6 @@ describe("ReclaimCoordinator for a physical device the platform no longer lists }); }); - it("logs a presence read that rejects after a failed reclaim as a warning naming the device and the error", async () => { - const logger = recordingLogger(); - const harness = await physicalHarness("reclaiming", { logger }); - harness.driver.failOn("reclaim", 1, new Error("uninstall exploded")); - harness.driver.failOn("listPresentPhysical", 1, new Error("link down")); - - await harness.coordinator.reclaim(releasedPhysical(harness.device())); - - expect(logger.warn).toHaveBeenCalledWith("presence read after a failed reclaim failed", { - deviceId: "dev_physical", - error: "Error: link down", - }); - }); - it("a returned device's reclaim whose caller no longer proceeds when the decision runs writes nothing, starts no wipe and leaves no claim", async () => { const harness = await physicalHarness("absent"); harness.driver.setPhysicalPresence(PHYSICAL_ID, true, { osVersion: "18.5" }); diff --git a/src/core/startup-converger.test.ts b/src/core/startup-converger.test.ts index 196551191..e172de32d 100644 --- a/src/core/startup-converger.test.ts +++ b/src/core/startup-converger.test.ts @@ -96,19 +96,6 @@ function createHarness( } describe("StartupConverger", () => { - it("restores quarantine timers before recovering interrupted reclaims", async () => { - const harness = createHarness( - [device("reclaiming", "ios", "reclaiming", 1), device("ready", "ios", "ready", 2)], - [], - ); - - await harness.converger.converge(harness.read); - - expect(harness.order).toEqual(["quarantine-restore", "recover:reclaiming"]); - expect(harness.quarantineRestore.restore).toHaveBeenCalledOnce(); - expect(harness.recovery.recoverInterruptedReclaim).toHaveBeenCalledOnce(); - }); - it("leaves every ready device ready at startup", async () => { const older = device("older", "ios", "ready", 1); const newer = device("newer", "android", "ready", 2); diff --git a/src/core/startup-read.test.ts b/src/core/startup-read.test.ts index 6ccbf0604..a6a24e359 100644 --- a/src/core/startup-read.test.ts +++ b/src/core/startup-read.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; -import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; +import { FakeClock } from "../ports/index.js"; import type { Driver, DriverReality, ObservedDevice } from "./driver.js"; import type { Platform } from "./domain.js"; import { readStartup, STARTUP_READ_LIMIT_MS } from "./startup-read.js"; @@ -95,43 +95,4 @@ describe("readStartup", () => { expect(read.reality("ios")).toEqual(reality("a")); expect(clock.pendingTimerCount).toBe(0); }); - - it("logs a platform whose listManaged throws, naming the platform and the error", async () => { - const sink = new MemoryLogSink(); - const clock = new FakeClock(0); - const logger = new JsonLinesLogger({ clock, level: "debug", sink }); - const ios = driver("ios", async () => { - throw new Error("simctl broke"); - }); - - await readStartup({ clock, drivers: [ios.driver], logger }); - - expect(sink.records).toMatchObject([ - { - fields: { error: "Error: simctl broke", platform: "ios" }, - level: "warn", - message: "startup read failed; the platform is unreadable", - }, - ]); - }); - - it("logs a platform that passed the 60-second limit, naming the platform and the limit", async () => { - const sink = new MemoryLogSink(); - const clock = new FakeClock(0); - const logger = new JsonLinesLogger({ clock, level: "debug", sink }); - const ios = driver("ios", () => new Promise(() => undefined)); - - const pending = readStartup({ clock, drivers: [ios.driver], logger }); - await vi.waitFor(() => expect(ios.list).toHaveBeenCalledTimes(1)); - clock.advance(STARTUP_READ_LIMIT_MS); - await pending; - - expect(sink.records).toMatchObject([ - { - fields: { limitMs: 60_000, platform: "ios" }, - level: "warn", - message: "startup read passed its limit; the platform is unreadable", - }, - ]); - }); }); diff --git a/src/core/warm-pool/boundary.test.ts b/src/core/warm-pool/boundary.test.ts deleted file mode 100644 index b5b197d05..000000000 --- a/src/core/warm-pool/boundary.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { readdirSync, readFileSync } from "node:fs"; -import { join, posix } from "node:path"; - -import { describe, expect, it } from "vitest"; - -import { - importSpecifiers, - isUnder, - normalizeSpecifier, - srcDir, - stripComments, -} from "../../test-support/imports.js"; - -const warmPoolDir = "core/warm-pool"; - -describe("warm pool module boundary", () => { - it("has no file outside src/core/warm-pool/ importing a file inside it other than index.ts", () => { - const files = readdirSync(srcDir, { recursive: true, withFileTypes: true }) - .filter((entry) => entry.isFile() && entry.name.endsWith(".ts")) - .map((entry) => join(entry.parentPath, entry.name)); - expect(files.length).toBeGreaterThan(100); - - const leaks = files - .filter((file) => !isUnder(posix.relative(srcDir, file), warmPoolDir)) - .flatMap((file) => - importSpecifiers(stripComments(readFileSync(file, "utf8"))) - .map((specifier) => ({ - file: posix.relative(srcDir, file), - normalized: normalizeSpecifier(posix.dirname(file), specifier), - specifier, - })) - .filter( - ({ normalized }) => - isUnder(normalized, warmPoolDir) && normalized !== `${warmPoolDir}/index.js`, - ), - ); - - expect(leaks.map(({ file, specifier }) => `${file} imports "${specifier}"`)).toEqual([]); - }); -}); diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index fc576876d..3f231eae3 100644 --- a/src/core/warm-pool/converger.test.ts +++ b/src/core/warm-pool/converger.test.ts @@ -1313,7 +1313,7 @@ describe("warm pool targets", () => { expect(rig.provisionCalls).toHaveLength(5); }); - it("reports a target naming a runtime that is not installed as runtime-missing, creates nothing and logs the reason", async () => { + it("reports a target naming a runtime that is not installed as runtime-missing and creates nothing", async () => { const rig = harness([], { resolve: () => ({ message: "iOS 27.0 is not installed", refusal: "runtime-missing" }), targets: [{ ...iphone17, osVersion: "27.0" }], @@ -1341,17 +1341,6 @@ describe("warm pool targets", () => { target: "ios iPhone 17 27.0", }, ]); - const shortLines = rig.sink.records.filter( - (record) => record.message === "a warm pool target is short", - ); - expect(shortLines).toHaveLength(1); - expect(shortLines[0]?.fields).toMatchObject({ - count: 1, - message: "iOS 27.0 is not installed", - ready: 0, - short: "runtime-missing", - target: "ios iPhone 17 27.0", - }); }); it.each([ @@ -1830,29 +1819,6 @@ describe("warm pool targets", () => { expect(rig.provisionCalls).toHaveLength(2); }); - it("logs a target again when the reason it is short changes, and logs two targets short for the same reason once each", async () => { - let refusal: "runtime-missing" | "unresolvable" = "runtime-missing"; - const rig = harness([], { - resolve: () => ({ message: "why", refusal }), - targets: [iphone17, { ...iphone17, model: "iPhone 16" }], - }); - - await rig.pool.pass(); - await rig.pool.pass(); - refusal = "unresolvable"; - await rig.pool.pass(); - - const lines = rig.sink.records - .filter((record) => record.message === "a warm pool target is short") - .map((record) => `${String(record.fields?.["target"])}:${String(record.fields?.["short"])}`); - expect(lines).toEqual([ - "ios iPhone 17 26.0:runtime-missing", - "ios iPhone 16 26.0:runtime-missing", - "ios iPhone 17 26.0:unresolvable", - "ios iPhone 16 26.0:unresolvable", - ]); - }); - describe("figures", () => { const wanted = { mode: "full", diff --git a/src/daemon/connection-host.test.ts b/src/daemon/connection-host.test.ts index d4960d162..3c0996252 100644 --- a/src/daemon/connection-host.test.ts +++ b/src/daemon/connection-host.test.ts @@ -30,17 +30,6 @@ describe("DaemonEndpointHost", () => { await expect(ipc.connect(endpoint)).rejects.toMatchObject({ code: "endpoint-not-found" }); }); - it("removes a stale endpoint before binding", async () => { - const filesystem = new MemoryFilesystem(); - await filesystem.mkdirp("/simlock"); - await filesystem.writeFileAtomic(endpoint, "stale"); - const ipc = new MemoryIpcTransport(); - const host = hostFor(filesystem, ipc, ipc); - await host.start(() => undefined); - await expect(ipc.connect(endpoint)).resolves.toBeDefined(); - await host.stop(); - }); - it("rejects a live endpoint before binding", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/simlock"); @@ -95,31 +84,6 @@ describe("DaemonEndpointHost", () => { ); }); - it("logs claiming a fresh endpoint", async () => { - const filesystem = new MemoryFilesystem(); - const ipc = new MemoryIpcTransport(); - const sink = new MemoryLogSink(); - const logger = new JsonLinesLogger({ clock: new FakeClock(), level: "debug", sink }); - const host = new DaemonEndpointHost({ - connector: ipc, - endpoint, - filesystem, - listenerFactory: ipc, - logger, - }); - - await host.start(() => undefined); - - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "Claimed daemon socket", - fields: { endpoint }, - }), - ); - await host.stop(); - }); - it("logs recovering a stale endpoint before claiming it", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/simlock"); diff --git a/src/daemon/dispatch.test.ts b/src/daemon/dispatch.test.ts index d03be1f99..9440bc2d8 100644 --- a/src/daemon/dispatch.test.ts +++ b/src/daemon/dispatch.test.ts @@ -6,7 +6,6 @@ import { runDispatch, type DispatchPipeline, type DispatchSession, - type ErasedHandler, } from "./dispatch.js"; function harness(handlers: DispatchPipeline["handlers"], level: LogLevel = "debug") { @@ -34,39 +33,7 @@ function session(overrides: Partial = {}): DispatchSession { }; } -/** A handler that takes `ms` of fake time and then answers `output`. */ -function slow(clock: FakeClock, ms: number, output: unknown): ErasedHandler { - return () => { - clock.advance(ms); - return output; - }; -} - describe("runDispatch's operation line", () => { - it("a write that succeeds logs one info line with the operation, principal, role and duration", async () => { - const handlers: DispatchPipeline["handlers"] = {}; - const { clock, pipeline, sink } = harness(handlers); - handlers["lease.release"] = slow(clock, 40, { leaseId: "lse_1" }); - - await runDispatch("lease.release", { leaseId: "lse_1" }, session(), pipeline); - - expect(sink.records).toEqual([ - { - timestamp: 1_040, - level: "info", - module: "dispatch", - message: "operation", - fields: { - operation: "lease.release", - principal: "agent-7", - role: "agent", - durationMs: 40, - leaseId: "lse_1", - }, - }, - ]); - }); - it("a read that succeeds logs at debug and nothing at info", async () => { const handlers: DispatchPipeline["handlers"] = { "lease.list": () => ({ leases: [] }) }; const debug = harness(handlers, "debug"); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index c7e458017..54e586397 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -988,23 +988,6 @@ describe("Dispatcher: ownership", () => { return (grant as { lease: { id: string } }).lease.id; } - it("lease.request: rejects a non-admin session naming owner with FORBIDDEN, never silently ignoring it (ADR §27a, H7)", async () => { - const { dispatcher } = await buildDispatcher(); - - await expect( - dispatcher.dispatch( - "lease.request", - { - model: "iPhone 17 Pro", - osVersion: "26.5", - owner: "someone-else", - platform: "ios", - }, - session({ principal: "tok_agent", role: "agent" }), - ), - ).rejects.toMatchObject({ code: "FORBIDDEN" }); - }); - // H3 (round 3 review): §27a's gate used to be `role !== "admin"`, which an HTTP `operator` // bearer token satisfies just as well as the gateway's own uplink -- on a plain worker with no // gateway anywhere, any operator token could name someone else as owner. `isGatewayUplink` is @@ -1012,22 +995,31 @@ describe("Dispatcher: ownership", () => { // `acceptUplink` (this worker dialled its own configured `gateway.url`); a session merely // carrying `role: "admin"` from anywhere else -- an operator token's HTTP session included -- // no longer suffices. - it("lease.request: rejects a plain admin session (not the gateway's uplink) naming owner with FORBIDDEN (ADR §27a, H3)", async () => { - const { dispatcher } = await buildDispatcher(); + it.each([ + ["a non-admin session", { principal: "tok_agent", role: "agent" }], + [ + "a plain admin session (not the gateway's uplink)", + { principal: "tok_operator", role: "admin" }, + ], + ] as const)( + "lease.request: rejects %s naming owner with FORBIDDEN, never silently ignoring it (ADR §27a, H7, H3)", + async (_name, who) => { + const { dispatcher } = await buildDispatcher(); - await expect( - dispatcher.dispatch( - "lease.request", - { - model: "iPhone 17 Pro", - osVersion: "26.5", - owner: "someone-else", - platform: "ios", - }, - session({ principal: "tok_operator", role: "admin" }), - ), - ).rejects.toMatchObject({ code: "FORBIDDEN" }); - }); + await expect( + dispatcher.dispatch( + "lease.request", + { + model: "iPhone 17 Pro", + osVersion: "26.5", + owner: "someone-else", + platform: "ios", + }, + session({ ...who }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }, + ); it("lease.request: the gateway's own uplink session may set owner, and the granted lease ends up owned by that, not the uplink's own principal (ADR §27a, H3)", async () => { const { dispatcher } = await buildDispatcher(); @@ -1442,29 +1434,6 @@ describe("Dispatcher: events.replay paging", () => { }); }); -describe("Dispatcher: config.get eventLog", () => { - it("config.get reports eventLog.retention and maxBytes and no rotateBytes", async () => { - const { dispatcher } = await buildDispatcher(); - - const { eventLog } = await dispatcher.dispatch("config.get", {}, session({ role: "admin" })); - - expect(eventLog).toStrictEqual({ - maxBytes: 256 * 1024 * 1024, - retention: 7 * 24 * 60 * 60 * 1000, - }); - }); -}); - -describe("Dispatcher: config.get metrics", () => { - it("config.get reports metrics.retention", async () => { - const { dispatcher } = await buildDispatcher(); - - const { metrics } = await dispatcher.dispatch("config.get", {}, session({ role: "admin" })); - - expect(metrics).toStrictEqual({ retention: 90 * 24 * 60 * 60 * 1000 }); - }); -}); - describe("Dispatcher: status.get history", () => { it.each([ { @@ -3310,27 +3279,6 @@ describe("Dispatcher: device.exec", () => { await expect(pending).rejects.toMatchObject({ code: "EXEC_TIMEOUT" }); }); - it("refuses a verb the driver refuses with PASSTHROUGH_REFUSED and spawns nothing", async () => { - const runner = new ScriptedProcessRunner([]); - const { dispatcher, leaseId } = await withLease({ processRunner: runner }); - - const error = await dispatcher - .dispatch( - "device.exec", - { args: ["delete", "ABCD"], leaseId, tool: "simctl" }, - session({ principal: "tok_agent" }), - ) - .then( - () => undefined, - (rejected: unknown) => rejected, - ); - - expect(classifyError(error)).toBe("PASSTHROUGH_REFUSED"); - // Refused before anything was spawned -- the point of the refusal list is that the command - // never runs, not that its output is discarded. - expect(runner.calls).toEqual([]); - }); - /** * The four combinations of the operation's own hook (ADR 0005 §19b/§27), which is * `ownsLease` for an agent and something stricter for an admin. The lease under test was diff --git a/src/daemon/error-code.test.ts b/src/daemon/error-code.test.ts index 9976a4214..35e0e58eb 100644 --- a/src/daemon/error-code.test.ts +++ b/src/daemon/error-code.test.ts @@ -1,9 +1,7 @@ import { describe, expect, it } from "vitest"; -import { AdminAuthenticationFailedError } from "../auth/index.js"; import { ComponentInstallerClosedError, UnsupportedRequestOptionError } from "../core/index.js"; import { - LeaseIdTakenError, NoCapacityError, ProvisionFailedError, ReplayedLeaseRequestError, @@ -61,15 +59,3 @@ describe("classifyError on a request option the driver does not have", () => { }); }); }); - -describe("classifyError on a lease ID that is in use", () => { - it("answers LEASE_ID_TAKEN for LeaseIdTakenError", () => { - expect(classifyError(new LeaseIdTakenError("ad-7f3a"))).toBe("LEASE_ID_TAKEN"); - }); -}); - -describe("classifyError on a rejected admin credential", () => { - it("answers ADMIN_AUTHENTICATION_FAILED for the error src/auth throws", () => { - expect(classifyError(new AdminAuthenticationFailedError())).toBe("ADMIN_AUTHENTICATION_FAILED"); - }); -}); diff --git a/src/daemon/gateway-uplink.test.ts b/src/daemon/gateway-uplink.test.ts index 15a484654..145b7ef14 100644 --- a/src/daemon/gateway-uplink.test.ts +++ b/src/daemon/gateway-uplink.test.ts @@ -3,7 +3,6 @@ import { describe, expect, it, vi } from "vitest"; import { createConnectionPair, FakeClock, - MemoryUplinkTransport, UplinkError, type IpcConnection, type UplinkConnector, @@ -276,19 +275,4 @@ describe("GatewayUplink", () => { expect(accepted).toEqual([]); }); - - it("works against the in-memory transport end to end", async () => { - const transport = new MemoryUplinkTransport(); - const accepted: string[] = []; - await transport.listen({ - accept: (uplinkConnection) => accepted.push(uplinkConnection.workerId), - authenticate: async (token) => (token === "join-secret" ? "accept" : "unauthenticated"), - }); - const { link } = uplink(transport); - - link.start(); - await vi.waitFor(() => expect(accepted).toEqual(["wrk_1"])); - - await link.stop(); - }); }); diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index a3a7184a5..a16eaaf47 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -452,24 +452,6 @@ async function freeLoopbackPort(): Promise { return address.port; } describe("startDaemon", () => { - it("writes a structured start record with version, protocol version, socket path, and effective config", async () => { - const { daemon, sink } = await start(); - - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "Daemon started", - fields: expect.objectContaining({ - version: "1.2.3", - protocolVersion: DAEMON_PROTOCOL_VERSION, - socketPath: daemon.socketPath, - }), - }), - ); - const record = sink.records.find((entry) => entry.message === "Daemon started"); - expect(record?.fields?.config).toMatchObject({ log: { level: "info" } }); - }); - it("keeps gateway.token out of the daemon log, the events.replay answer, and history.db, while config.get still returns it", async () => { const secret = "secret-join-token-170"; const { daemon, directory, sink } = await start({ @@ -1877,21 +1859,6 @@ describe("discoverDrivers", () => { }); }); - it("logs the refused root, so the reason survives even if nobody runs doctor", async () => { - const sink = new MemoryLogSink(); - - await discoverIos({ filesystem: await foreignOwnedRoot(), sink }); - - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "error", - message: "Skipped iOS driver: device root rejected", - module: "daemon.driver-discovery", - fields: expect.objectContaining({ reason: "wrong-instance", root: IOS_ROOT }), - }), - ); - }); - it("still fails startup when the iOS driver fails for a reason that is not a refusal", async () => { // Anything that is not an `OwnedRootError` is a bug rather than a fail-closed // decision, and swallowing it would hide it behind a silently missing platform. @@ -3013,14 +2980,18 @@ describe("startDaemon with the agent-device edge", () => { expect(processSupervisor.signals).toEqual([]); }); - it('a worker with no capabilities["agent-device"] section, and one with enabled false, answer status.get with { name: agent-device, state: off }', async () => { + it('a worker with no capabilities["agent-device"] section, one with enabled false, and one with only the old agentDevice key answer status.get with { name: agent-device, state: off }', async () => { const admin = { manageEventSubscription: () => undefined, via: "socket", principal: "op", role: "admin", } as const; - for (const config of [{}, { capabilities: { "agent-device": { enabled: false } } }]) { + for (const config of [ + {}, + { capabilities: { "agent-device": { enabled: false } } }, + { agentDevice: { command, enabled: true } }, + ]) { const setup = await setUp(config); const { daemon } = await startEdge(setup, { processRunner: new ScriptedProcessRunner([]), @@ -3061,25 +3032,6 @@ describe("startDaemon with the agent-device edge", () => { expect(loads).toBe(1); }); - it("a worker whose config has only the old agentDevice key reports agent-device off", async () => { - const admin = { - manageEventSubscription: () => undefined, - via: "socket", - principal: "op", - role: "admin", - } as const; - const setup = await setUp({ agentDevice: { command, enabled: true } }); - - const { daemon } = await startEdge(setup, { - processRunner: new ScriptedProcessRunner([]), - processSupervisor: new FakeProcessSupervisor(), - }); - - expect((await daemon.dispatch("status.get", {}, admin)).capabilities).toEqual([ - { name: "agent-device", state: "off" }, - ]); - }); - it("a worker with agent-device off starts no supervisor: no ps runs and no signal is sent, even with a recorded daemon on disk", async () => { const setup = await setUp( { capabilities: { "agent-device": { command, enabled: false } } }, diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index e718ea6fd..286191065 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -682,25 +682,6 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(response.headers.get("connection")).toBeNull(); }); - it("with 63 relays to one worker held in their targets, a 64th starts at once", async () => { - const release = gate(); - behavior = async () => { - await release.promise; - return new Response("ok"); - }; - const { opened, relay } = await startPair(); - - const calls = Array.from({ length: 64 }, () => - settleWithin(relay.relay(WORKER_ID, buildCall({})), 20_000), - ); - await poll(() => targetCalls.length, 10_000).toBe(64); - const channels = opened(); - release.open(); - await Promise.all(calls); - - expect(channels).toBe(64); - }, 60_000); - it("a 65th relay to one worker starts once one of 64 ends, and not before", async () => { const releases: (() => void)[] = []; behavior = async () => { diff --git a/src/daemon/relay-worker.e2e.test.ts b/src/daemon/relay-worker.e2e.test.ts index 27a6de1e4..0cd557f6e 100644 --- a/src/daemon/relay-worker.e2e.test.ts +++ b/src/daemon/relay-worker.e2e.test.ts @@ -487,34 +487,6 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => }, ); - it("fails the call with INTERNAL and logs the bound when a target answers 101 headers", async () => { - behavior = () => - Promise.resolve( - new Response("ok", { - headers: Array.from( - { length: 101 }, - (_unused, index) => [`x-h-${String(index)}`, "v"] as [string, string], - ), - }), - ); - await start(); - - const outcome = await settleWithin((await openRelay(uplink, relayInput())).result); - - expect(outcome).toMatchObject({ code: "INTERNAL", state: "rejected" }); - expect(fixture.logger.problems()).toContain("at most 100 headers, got"); - }); - - it("fails the call with INTERNAL and logs the message when a target throws", async () => { - behavior = () => Promise.reject(new Error("target exploded: reason-4471")); - await start(); - - const outcome = await settleWithin((await openRelay(uplink, relayInput())).result); - - expect(outcome).toMatchObject({ code: "INTERNAL", state: "rejected" }); - expect(fixture.logger.problems()).toContain("target exploded: reason-4471"); - }); - it("stops the request direction when the target answers without reading its 20 MiB upload, so the gateway's writer errors stopped", async () => { behavior = () => Promise.resolve(new Response("nope", { status: 401 })); await start(); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 0d7f3f493..5cb7a0077 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -205,6 +205,7 @@ describe("DaemonServer", () => { }); it.each([ + [1, "speaks a wire this daemon cannot serve"], [17, "cannot parse a starting status.get answer"], [18, "cannot parse config.get's warmPool.targets"], [20, "cannot send lease.request's leaseId or read a lease's idChosenByRequester"], @@ -247,18 +248,6 @@ describe("DaemonServer", () => { }, ); - it("rejects a protocol v1 client outright rather than serving it a wire it cannot speak", async () => { - const harness = await createHarness(); - const legacy = await createClient(harness.socketPath); - - await expect( - legacy.request("hello", { clientVersion: "test", protocolVersion: 1 }), - ).resolves.toMatchObject({ - error: { code: "PROTOCOL_VERSION_UNSUPPORTED" }, - ok: false, - }); - }); - it("grants the queued client when the holder's lease expires, not when it disconnects", async () => { // A log sink rather than a sleep: "the waiter stays queued" is a negative assertion, and // the only honest way to make one is to wait for the daemon to have actually processed @@ -1161,24 +1150,57 @@ describe("DaemonServer", () => { } }); - it("ignores lease-lost facts for leases with no currently connected holder without breaking the daemon", async () => { - const harness = await createHarness(); - harness.eventBus.emit( - "lease.expired", - { deviceId: "device-x", leaseId: "lease-x", ownerId: "test-process" }, - "test", - ); - harness.eventBus.emit( - "lease.released", - { deviceId: "device-y", leaseId: "lease-y", ownerId: "test-process", reason: "killed" }, - "test", - ); + type EventBus = Awaited>["eventBus"]; - const client = await createClient(harness.socketPath); - await hello(client); - await expect(client.request("status.get", {})).resolves.toMatchObject({ ok: true }); - await client.close(); - }); + it.each([ + [ + "lease-lost", + (eventBus: EventBus) => { + eventBus.emit( + "lease.expired", + { deviceId: "device-x", leaseId: "lease-x", ownerId: "test-process" }, + "test", + ); + eventBus.emit( + "lease.released", + { deviceId: "device-y", leaseId: "lease-y", ownerId: "test-process", reason: "killed" }, + "test", + ); + }, + ], + [ + "device-unhealthy/device-recovered", + (eventBus: EventBus) => { + eventBus.emit( + "device.crash-detected", + { deviceId: "device-x", leaseId: "lease-x", observed: "stopped", platform: "ios" }, + "test", + ); + eventBus.emit( + "device.recovered", + { + attempts: 1, + deviceId: "device-x", + duration: 1_000, + leaseId: "lease-x", + platform: "ios", + }, + "test", + ); + }, + ], + ])( + "ignores %s facts for leases with no currently connected holder without breaking the daemon", + async (_name, emitFacts) => { + const harness = await createHarness(); + emitFacts(harness.eventBus); + + const client = await createClient(harness.socketPath); + await hello(client); + await expect(client.request("status.get", {})).resolves.toMatchObject({ ok: true }); + await client.close(); + }, + ); it("pushes a device-unhealthy notification on device.crash-detected without releasing the lease", async () => { const harness = await createHarness(); @@ -1255,31 +1277,6 @@ describe("DaemonServer", () => { await holder.close(); }); - it("ignores device-unhealthy/device-recovered facts for leases with no currently connected holder", async () => { - const harness = await createHarness(); - harness.eventBus.emit( - "device.crash-detected", - { deviceId: "device-x", leaseId: "lease-x", observed: "stopped", platform: "ios" }, - "test", - ); - harness.eventBus.emit( - "device.recovered", - { - attempts: 1, - deviceId: "device-x", - duration: 1_000, - leaseId: "lease-x", - platform: "ios", - }, - "test", - ); - - const client = await createClient(harness.socketPath); - await hello(client); - await expect(client.request("status.get", {})).resolves.toMatchObject({ ok: true }); - await client.close(); - }); - it("pushes a lease-lost notification carrying reason device-lost when a leased device could not be recovered", async () => { const harness = await createHarness(); const holder = await createClient(harness.socketPath); @@ -2212,29 +2209,6 @@ describe("DaemonServer lease liveness (ADR 0004)", () => { }); await holder.close(); }); - - it("leaves leases alone on a daemon stop", async () => { - const harness = await createHarness({ lease: { defaultTtlMs: 40 } }); - const holder = await createClient(harness.socketPath); - await hello(holder); - const grant = await holder.request("lease.request", { - requesterId: "agent-1", - model: "iPhone 16", - osVersion: "26.5", - platform: "ios", - }); - const leaseId = leaseIdOf(grant); - await holder.close(); - - await harness.daemon.stop("test"); - - // ADR 0004 §3: a stop ends connections, not leases. The record persists with its - // deadline for the next daemon to restore a timer from. - expect(harness.registry.snapshot.leases).toMatchObject([{ id: leaseId }]); - expect(harness.eventBus.replay().filter((event) => event.event === "lease.released")).toEqual( - [], - ); - }); }); describe("DaemonServer decorations", () => { @@ -2262,61 +2236,6 @@ describe("DaemonServer decorations", () => { }); describe("operational logging", () => { - function logger(): { logger: Logger; sink: MemoryLogSink } { - const sink = new MemoryLogSink(); - return { - logger: new JsonLinesLogger({ clock: new FakeClock(1_000), level: "debug", sink }), - sink, - }; - } - - it("logs the daemon start with version, protocol version, socket path, and effective config", async () => { - const { logger: log, sink } = logger(); - const harness = await createHarness({ logger: log, start: false }); - - await harness.daemon.start(); - - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "Daemon started", - fields: expect.objectContaining({ - version: "test", - protocolVersion: DAEMON_PROTOCOL_VERSION, - socketPath: harness.socketPath, - config: harness.config, - }), - }), - ); - }); - - it("logs a connection opening with its principal and role, and closing afterward", async () => { - const { logger: log, sink } = logger(); - const harness = await createHarness({ logger: log }); - const client = await createClient(harness.socketPath); - - await helloAs(client, "agent-7"); - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "Connection opened", - fields: expect.objectContaining({ principal: "agent-7", role: "admin" }), - }), - ); - - await client.close(); - // ADR 0004 §3: there is no held-lease count to log any more, because there is no - // per-connection lease state to count. - await expect - .poll(() => - sink.records.some( - (record) => - record.message === "Connection closed" && record.fields?.principal === "agent-7", - ), - ) - .toBe(true); - }); - it("drains the backgrounded reclaims before disposing, on a graceful stop", async () => { const order: string[] = []; let finishSettle!: () => void; @@ -2460,75 +2379,6 @@ describe("DaemonServer decorations", () => { await harness.daemon.stop("test-health"); expect(harness.daemon.health).toBe("running"); }); - - it("logs a clean shutdown", async () => { - const { logger: log, sink } = logger(); - const harness = await createHarness({ logger: log }); - - await harness.daemon.stop("test-shutdown"); - - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "Daemon stopping", - fields: { reason: "test-shutdown" }, - }), - ); - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "Daemon stopped", - fields: { reason: "test-shutdown" }, - }), - ); - }); - - // `doctor.run`/`nuke.run` used to surface an unconfigured collaborator as a plain `Error`, - // which `errorCode()` had no choice but to map to `INTERNAL` -- logged at error level - // indistinguishably from a real bug. `DoctorUnavailableError`/`NukeUnavailableError` (ADR - // 0003 §7: "one error class, closed codes") give this its own typed code, so it is now a - // handled error like any other expected domain refusal: an info-level `operation` line. - it("logs an unconfigured doctor as a handled DOCTOR_UNAVAILABLE, not an unhandled error", async () => { - const { logger: log, sink } = logger(); - const harness = await createHarness({ logger: log }); - const client = await createClient(harness.socketPath); - await hello(client); - - await client.request("doctor.run", {}); - - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "operation", - fields: expect.objectContaining({ code: "DOCTOR_UNAVAILABLE", operation: "doctor.run" }), - }), - ); - expect(sink.records).not.toContainEqual( - expect.objectContaining({ level: "error", message: "Unhandled request error" }), - ); - await client.close(); - }); - - it("logs a handled/expected request error below error level", async () => { - const { logger: log, sink } = logger(); - const harness = await createHarness({ logger: log }); - const client = await createClient(harness.socketPath); - await hello(client); - - await client.request("lease.release", { leaseId: "not-a-lease" }); - - expect(sink.records).toContainEqual( - expect.objectContaining({ - level: "info", - message: "operation", - fields: expect.objectContaining({ code: "UNKNOWN_LEASE", operation: "lease.release" }), - }), - ); - expect(sink.records).not.toContainEqual( - expect.objectContaining({ level: "error", message: "Unhandled request error" }), - ); - await client.close(); - }); }); }); @@ -2595,27 +2445,36 @@ describe("DaemonServer download policy", () => { await client.close(); }); - it("withholds download permission under the never policy even when the request asks for it", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - const harness = await createHarness({ clock, downloads: { policy: "never" }, driver }); - const client = await createClient(harness.socketPath); - await hello(client); + it.each([ + ["asks for it", { allowDownload: true }], + ["never asked for a download", {}], + ])( + "attaches the download-policy suffix and withholds download permission under the never policy even when the request %s", + async (_name, extra) => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + const harness = await createHarness({ clock, downloads: { policy: "never" }, driver }); + const client = await createClient(harness.socketPath); + await hello(client); - const response = await client.request("lease.request", { - allowDownload: true, - requesterId: "agent-1", - model: "iPhone 16", - osVersion: "26.5", - platform: "ios", - }); + // why: when the request never asked, the driver's own message still suggests `--allow-download`, + // which under the never policy can never help, so the suffix must still attach as the + // correction. + const response = await client.request("lease.request", { + ...extra, + requesterId: "agent-1", + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", + }); - expect(response.ok).toBe(false); - expect(response.error).toMatchObject({ code: "RUNTIME_MISSING" }); - expect(response.error?.message).toContain("downloads.policy"); - expect(driver.calls.map((call) => call.operation)).not.toContain("installComponent"); - await client.close(); - }); + expect(response.ok).toBe(false); + expect(response.error).toMatchObject({ code: "RUNTIME_MISSING" }); + expect(response.error?.message).toContain("downloads.policy"); + expect(driver.calls.map((call) => call.operation)).not.toContain("installComponent"); + await client.close(); + }, + ); it("defers to the request's own flag under the default on-request policy", async () => { const clock = new FakeClock(1_000); @@ -2640,29 +2499,6 @@ describe("DaemonServer download policy", () => { await client.close(); }); - it("attaches the download-policy suffix under the never policy even when the request itself never asked for a download", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - const harness = await createHarness({ clock, downloads: { policy: "never" }, driver }); - const client = await createClient(harness.socketPath); - await hello(client); - - // No allowDownload on this request at all -- the driver's own message still suggests - // `--allow-download`, which under the never policy can never help, so the suffix must - // still attach as the correction. - const response = await client.request("lease.request", { - requesterId: "agent-1", - model: "iPhone 16", - osVersion: "26.5", - platform: "ios", - }); - - expect(response.ok).toBe(false); - expect(response.error).toMatchObject({ code: "RUNTIME_MISSING" }); - expect(response.error?.message).toContain("downloads.policy"); - await client.close(); - }); - it("never attaches the download-policy suffix to an undownloadable RuntimeMissingError, even under the never policy", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); diff --git a/src/drivers/android/adb-server.test.ts b/src/drivers/android/adb-server.test.ts index bbe0250e0..d9874e819 100644 --- a/src/drivers/android/adb-server.test.ts +++ b/src/drivers/android/adb-server.test.ts @@ -32,16 +32,6 @@ describe("AdbServerSupervisor.start", () => { await expect(harness.filesystem.readFile(recordPath)).resolves.toContain('"startedAt":17'); }); - it("refuses a port something else is already listening on", async () => { - const harness = await start({ listening: true }); - - await expect(harness.started).rejects.toMatchObject({ - name: "AdbServerUnavailableError", - port, - reason: "occupied", - }); - }); - it("refuses a port whose recorded server is dead even though something answers there", async () => { // The listener cannot be Simlock's -- the pid that would prove it is gone -- so this is // somebody else's adb server, and attaching to it is what failing closed prevents. diff --git a/src/drivers/android/device-profile-source.test.ts b/src/drivers/android/device-profile-source.test.ts index 273874a75..0d60b9e3b 100644 --- a/src/drivers/android/device-profile-source.test.ts +++ b/src/drivers/android/device-profile-source.test.ts @@ -294,7 +294,6 @@ describe("parseDevicesXml", () => { ["a fractional value", '1.5'], ["an empty value", ''], ["a zero value", '0'], - ["a value under half a MiB", '511'], ["a value too large to count exactly in MiB", '1000000000000000'], ])("leaves hw.ramSize unset for ram with %s instead of guessing", (_case, ram) => { expect(parseDevicesXml(devicesXmlWithRam(ram))).toEqual([ @@ -542,18 +541,6 @@ describe("DeviceProfileRegistry", () => { await expect(registry.resolve("Nope")).rejects.toMatchObject({ name: "UnknownModelError" }); }); - it("dedupes the catalog's models by name, earliest source winning", async () => { - const runner = new ScriptedProcessRunner([processResult(pixelDevices)]); - const builtin = new BuiltinDeviceProfileSource(avdmanager, runner); - const filesystem = await filesystemWithDevicesXml( - devicesXml().replace("My Custom Phone", "pixel 8"), - ); - const user = new UserDeviceProfileSource(devicesXmlPath, filesystem); - const registry = new DeviceProfileRegistry([builtin, user]); - - await expect(registry.catalog()).resolves.toMatchObject({ models: ["Pixel 8"] }); - }); - it("lists a model's other names, only for models that have one", async () => { const runner = new ScriptedProcessRunner([processResult(pixelDevices)]); const builtin = new BuiltinDeviceProfileSource(avdmanager, runner); @@ -592,20 +579,6 @@ describe("DeviceProfileRegistry", () => { }); }); - it("lists a model that comes only from devices.xml in customModels", async () => { - const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource( - avdmanager, - new ScriptedProcessRunner([processResult(pixelDevices)]), - ), - new UserDeviceProfileSource(devicesXmlPath, await filesystemWithDevicesXml(devicesXml())), - ]); - - await expect(registry.catalog()).resolves.toMatchObject({ - customModels: ["My Custom Phone"], - }); - }); - it("lists a devices.xml model in customModels when avdmanager also lists it as a User profile", async () => { // `avdmanager list device` reads devices.xml itself and prints each of its profiles with // `OEM : User` (seen on a real SDK, issue #236), so the built-in source returns the name too. @@ -628,20 +601,6 @@ describe("DeviceProfileRegistry", () => { }); }); - it("does not list a built-in model in customModels", async () => { - const registry = new DeviceProfileRegistry([ - new BuiltinDeviceProfileSource( - avdmanager, - new ScriptedProcessRunner([processResult(pixelDevices)]), - ), - new UserDeviceProfileSource(devicesXmlPath, await filesystemWithDevicesXml(devicesXml())), - ]); - - const catalog = await registry.catalog(); - expect(catalog.models).toContain("Pixel 8"); - expect(catalog.customModels).not.toContain("Pixel 8"); - }); - it("resolves a name avdmanager lists as both an SDK and a User profile to the SDK one, whatever the order", async () => { const user = `id: 68 or "My Pixel"\n Name: Pixel 8\n OEM : User\n`; const sdk = `id: 0 or "pixel_8"\n Name: Pixel 8\n OEM : Google\n`; @@ -865,12 +824,6 @@ describe("device classes", () => { }); }); - it("classes an untagged avdmanager profile and a devices.xml profile as phone", async () => { - const classes = await modelClasses(entry("pixel_8", "Pixel 8"), devicesXml()); - - expect(classes).toEqual({ "My Custom Phone": "phone", "Pixel 8": "phone" }); - }); - it("classes a listed model by the profile its name resolves to, not the one it was listed from", async () => { // why: the three devices.xml profiles are named after profile ids the library or the SDK // ships -- `tv_1080p` and `wearos_large_round` resolve to the library's TV and Wear OS diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index bdf5512c3..1e36c8253 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -4877,19 +4877,6 @@ describe("AndroidDriver defaultModels", () => { watch: ["Wear OS Large Round", "Wear OS Small Round"], }); }); - - it("has no Android list for vision", async () => { - const driver = await createDriver(await androidFilesystem(), new ScriptedProcessRunner([])); - - expect(Object.keys(driver.defaultModels).sort()).toEqual([ - "auto", - "desktop", - "phone", - "tablet", - "tv", - "watch", - ]); - }); }); describe("AndroidDriver library catalog", () => { @@ -5510,21 +5497,19 @@ describe("AndroidDriver image fit", () => { ); }); - it("says the model does not take Play Store images", async () => { - const { refusal } = await fitHarness([["36", "google_apis_playstore", "arm64-v8a"]]); - - expect((await refusal("Pixel 6", "36")).message).toBe( - "No installed system image fits Pixel 6 at Android 36: Pixel 6 does not take Play Store images", - ); - }); - - it("says the model does not take tablet images", async () => { - const { refusal } = await fitHarness([["35", "tablet", "arm64-v8a"]]); + it.each([ + ["Pixel 6", "36", "google_apis_playstore", "Play Store"], + ["Pixel 5", "35", "tablet", "tablet"], + ])( + "says the model does not take the kind of image it was given (%s)", + async (model, osVersion, imageTag, noun) => { + const { refusal } = await fitHarness([[osVersion, imageTag, "arm64-v8a"]]); - expect((await refusal("Pixel 5", "35")).message).toBe( - "No installed system image fits Pixel 5 at Android 35: Pixel 5 does not take tablet images", - ); - }); + expect((await refusal(model, osVersion)).message).toBe( + `No installed system image fits ${model} at Android ${osVersion}: ${model} does not take ${noun} images`, + ); + }, + ); it("says none of the installed images fit it when no single check rules out every image", async () => { const { refusal } = await fitHarness([ diff --git a/src/drivers/android/physical-handler.test.ts b/src/drivers/android/physical-handler.test.ts index 4904e8c10..285ef173b 100644 --- a/src/drivers/android/physical-handler.test.ts +++ b/src/drivers/android/physical-handler.test.ts @@ -778,7 +778,7 @@ describe("Android physical handler: the gate on a failing adb version", () => { describe("Android physical handler: advisories", () => { it("returns adb-protocol-mismatch naming both protocol numbers on a mismatch", async () => { - const { driver } = await world({ serverReply: VERSION_REPLY_40 }); + const { driver, runner } = await world({ serverReply: VERSION_REPLY_40 }); const advisories = await advisoriesOf(driver); @@ -786,6 +786,7 @@ describe("Android physical handler: advisories", () => { expect(advisories[0]?.code).toBe("adb-protocol-mismatch"); expect(advisories[0]?.message).toMatch(/40/); expect(advisories[0]?.message).toMatch(/41/); + expect(runner.commands).toEqual([]); }); it.each([ @@ -831,15 +832,6 @@ describe("Android physical handler: advisories", () => { expect(await advisoriesOf(driver)).toEqual([]); }); - - it("reports the mismatch on a driver that has never been asked about a physical device", async () => { - const { driver, runner } = await world({ serverReply: VERSION_REPLY_40 }); - - const advisories = await advisoriesOf(driver); - - expect(advisories.map((advisory) => advisory.code)).toEqual(["adb-protocol-mismatch"]); - expect(runner.commands).toEqual([]); - }); }); describe("Android physical handler: scope", () => { @@ -1189,7 +1181,6 @@ describe("Android physical handler: reclaim", () => { it.each([ ["fails", FAILED], ["passes 30 s", TIMED_OUT], - ["has a bad line", OK("package:com.example.kept\npackage:bad name;rm\n")], ])( "rejects, runs no uninstall and never resolves with an empty list when the first pm list packages %s", async (_name, result) => { diff --git a/src/drivers/android/prerequisites.test.ts b/src/drivers/android/prerequisites.test.ts index ab8059f6a..6eeabe28d 100644 --- a/src/drivers/android/prerequisites.test.ts +++ b/src/drivers/android/prerequisites.test.ts @@ -58,18 +58,24 @@ describe("androidPrerequisites", () => { expect(runner.calls[0]?.options.timeoutMs).toBe(30_000); }); - it("reports android-emulator with the `sdkmanager --install emulator` remedy when only the emulator binary is missing", async () => { - const runner = new ScriptedProcessRunner([SDKMANAGER_RUNS]); - - const missing = await check(await sdkFilesystem(["emulator"]), runner).check(); - - expect(missing).toEqual([ - expect.objectContaining({ - prerequisite: "android-emulator", - remedy: expect.stringContaining("sdkmanager --install emulator") as unknown, - }), - ]); - }); + it.each([ + ["emulator", "android-emulator", "sdkmanager --install emulator"], + ["platform-tools", "android-platform-tools", "sdkmanager --install platform-tools"], + ] as const)( + "reports the package with its `sdkmanager --install` remedy when only %s is missing", + async (without, prerequisite, remedy) => { + const runner = new ScriptedProcessRunner([SDKMANAGER_RUNS]); + + const missing = await check(await sdkFilesystem([without]), runner).check(); + + expect(missing).toEqual([ + expect.objectContaining({ + prerequisite, + remedy: expect.stringContaining(remedy) as unknown, + }), + ]); + }, + ); it("stops reporting a package on the next check once it is installed", async () => { const filesystem = await sdkFilesystem(["emulator"]); @@ -86,19 +92,6 @@ describe("androidPrerequisites", () => { await expect(prerequisites.check()).resolves.toEqual([]); }); - it("reports android-platform-tools when only adb is missing", async () => { - const runner = new ScriptedProcessRunner([SDKMANAGER_RUNS]); - - const missing = await check(await sdkFilesystem(["platform-tools"]), runner).check(); - - expect(missing).toEqual([ - expect.objectContaining({ - prerequisite: "android-platform-tools", - remedy: expect.stringContaining("sdkmanager --install platform-tools") as unknown, - }), - ]); - }); - it("reports android-cmdline-tools when no tool bin is complete, and does not run sdkmanager", async () => { const filesystem = await sdkFilesystem(["cmdline-tools"]); // A bin with only one of the two tools is not complete. diff --git a/src/drivers/android/screen/session.test.ts b/src/drivers/android/screen/session.test.ts index 58b6efcce..f70d276bb 100644 --- a/src/drivers/android/screen/session.test.ts +++ b/src/drivers/android/screen/session.test.ts @@ -452,10 +452,11 @@ describe("Android screen capture: open", () => { expect(phoneOptions.filter((o) => o !== "stay_awake=true")).toEqual(emulatorOptions); }); - it("reads no screen state for an emulator", async () => { - const world = await setup(); + it("reads no screen state and sends no wake for an emulator, even when the screen would read asleep", async () => { + const world = await setup({ power: { code: 0, stdout: " mWakefulness=Asleep\n" } }); await opened(world); expect(world.target.powerReads).toEqual([]); + expect(world.target.wakes).toEqual([]); expect(world.target.log).not.toContainEqual(expect.stringContaining("dumpsys")); }); @@ -717,21 +718,6 @@ describe("Android screen capture: a phone's screen state", () => { } }); - it("sends no wake to a phone whose screen is on, and none to an emulator", async () => { - const world = await setup({ device: PHONE }); - await drive( - world.clock, - waitThenStart( - world.target, - world.capture.open(PHONE, SETTINGS, new AbortController().signal), - ), - ); - expect(world.target.wakes).toEqual([]); - const emulator = await setup({ power: { code: 0, stdout: " mWakefulness=Asleep\n" } }); - await opened(emulator); - expect(emulator.target.wakes).toEqual([]); - }); - it.each([ { name: "Awake", power: { code: 0, stdout: " mWakefulness=Awake\n" } }, { name: "Dreaming", power: { code: 0, stdout: " mWakefulness=Dreaming\n" } }, diff --git a/src/drivers/installer-process.test.ts b/src/drivers/installer-process.test.ts index e3244214a..82588ef4b 100644 --- a/src/drivers/installer-process.test.ts +++ b/src/drivers/installer-process.test.ts @@ -43,21 +43,6 @@ describe("runInstallerProcess", () => { ]); }); - it("reports each percentage of a progress bar redrawn with carriage returns", async () => { - const runner = new ScriptedProcessRunner([ - { - match: { args: ["install"], command }, - stdoutLines: ["[= ] 10% a\r[== ] 20% b\r[===] 30% c"], - }, - ]); - const clock = new FakeClock(); - - const { outcome, progress } = run(runner, clock); - await outcome; - - expect(progress.map((report) => report.percent)).toEqual([10, 20, 30]); - }); - it("reads a percentage written with a decimal comma, as xcodebuild prints it in a region that uses one", async () => { // Byte for byte as `xcodebuild -downloadPlatform iOS -buildVersion 18.4` wrote it under // language English, region Poland: one `\n`, then `\r`-separated redraws, a line with only diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index aafcdbbf9..ae831dd00 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -428,20 +428,6 @@ describe("IosSimctlDriver", () => { ).rejects.toMatchObject({ component: "latest", downloadable: true, osVersion: "default" }); }); - it("gives a clean RuntimeMissingError, not a parse-time DriverCrashError, when no runtime is installed", async () => { - const runner = new ScriptedProcessRunner([ - { match: listInvocation, result: { code: 0, stderr: "", stdout: emptyRuntimesCatalog } }, - ]); - const driver = await createDriver(runner); - - const result = await driver - .resolveSpec({ model: "iPhone 16", platform: "ios" }) - .catch((error: unknown) => error); - - expect(result).toBeInstanceOf(RuntimeMissingError); - expect(result).not.toBeInstanceOf(DriverCrashError); - }); - it("lists an empty runtimes catalog with defaultRuntime undefined instead of throwing", async () => { const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: emptyRuntimesCatalog } }, @@ -1265,15 +1251,6 @@ describe("IosSimctlDriver", () => { }); }); - it("lists a model no installed runtime pairs with, with an empty list", async () => { - const driver = await createDriver(pairingRunner()); - - const catalog = await driver.listCatalog(); - - expect(catalog.models).toContain("iPhone 8"); - expect(catalog.modelRuntimes["iPhone 8"]).toEqual([]); - }); - it("resolveSpec accepts every listed pair and refuses every unlisted pair of a listed model and an installed runtime", async () => { const models = ["iPhone 16", "iPhone XS", "iPad Pro", "iPad mini", "iPhone 8"]; const installed = ["18.4", "26.0"]; @@ -1311,23 +1288,6 @@ describe("IosSimctlDriver", () => { expect({ accepted, refused }).toEqual({ accepted: 5, refused: 5 }); }); - it("resolves an exact version when any installed build of that version pairs with the model", async () => { - const driver = await createDriver(pairingRunner()); - - await expect( - driver.resolveSpec({ - model: "iPad mini", - osVersion: "26.0", - platform: "ios", - }), - ).resolves.toEqual({ - physical: false, - model: "iPad mini", - osVersion: "26.0", - platform: "ios", - }); - }); - it("pairs two device types that differ only in letter case through the first, as resolveSpec matches them", async () => { const fixture = JSON.stringify({ devicetypes: [ @@ -1678,12 +1638,6 @@ describe("IosSimctlDriver", () => { ]); }); - it("hands a lease holder the device set its simulator cannot be addressed without", async () => { - const driver = await createDriver(new ScriptedProcessRunner([])); - - expect(driver.leaseEnvironment(VIRTUAL_DEVICE)).toEqual({ SIMLOCK_IOS_DEVICE_SET: deviceRoot }); - }); - it("answers virtualLeaseEnvironment with the device set, and leaseEnvironment for a virtual device equals it", async () => { const driver = await createDriver(new ScriptedProcessRunner([])); @@ -1700,10 +1654,9 @@ describe("IosSimctlDriver", () => { }); }); - it("answers uninstall for the reclaim strategy of a physical device, and erase for a simulator's", async () => { + it("answers uninstall for the reclaim strategy of a physical device", async () => { const driver = await createDriver(new ScriptedProcessRunner([])); - expect(driver.reclaimStrategy(VIRTUAL_DEVICE, { clean: "standard" })).toBe("erase"); expect(driver.reclaimStrategy(PHYSICAL_DEVICE, { clean: "standard" })).toBe("uninstall"); expect(driver.reclaimStrategy(PHYSICAL_DEVICE, { clean: "full" })).toBe("uninstall"); }); @@ -2385,63 +2338,44 @@ describe("IosSimctlDriver", () => { ); }); - it("skips slim with reason runtime-too-old on iOS 18.4 (single boot, no spawns)", async () => { - const runner = new ScriptedProcessRunner([ - { match: { command: "xcrun", args: simctlArgs("boot", slim18_4.udid) } }, - { match: { command: "xcrun", args: simctlArgs("bootstatus", slim18_4.udid, "-b") } }, - { match: simctl("listapps", slim18_4.udid) }, - ]); - const onSlimSkipped = vi.fn(); - const driver = await createSlimDriver( - runner, - new MemoryFilesystem(), - slimOptions(), - undefined, - onSlimSkipped, - ); - - const result = await driver.makeReady( - { address: slim18_4.udid, deviceId: slim18_4.udid, driverData: slim18_4 }, - prepareSlim, - ); - - expect(result).toEqual({ - address: slim18_4.udid, - deviceId: slim18_4.udid, - driverData: slim18_4, - mode: "full", - }); - expect(runner.calls).toHaveLength(3); - expect(onSlimSkipped).toHaveBeenCalledWith( - expect.objectContaining({ deviceId: slim18_4.udid, reason: "runtime-too-old" }), - ); - expect(runner.calls[1]?.options).toEqual({ timeoutMs: 120_000 }); - }); - - it("skips slim with reason runtime-too-old on iOS 17.5", async () => { - const runner = new ScriptedProcessRunner([ - { match: { command: "xcrun", args: simctlArgs("boot", slim17_5.udid) } }, - { match: { command: "xcrun", args: simctlArgs("bootstatus", slim17_5.udid, "-b") } }, - { match: simctl("listapps", slim17_5.udid) }, - ]); - const onSlimSkipped = vi.fn(); - const driver = await createSlimDriver( - runner, - new MemoryFilesystem(), - slimOptions(), - undefined, - onSlimSkipped, - ); + it.each([ + ["18.4", slim18_4], + ["17.5", slim17_5], + ])( + "skips slim with reason runtime-too-old on iOS %s (single boot, no spawns)", + async (_version, data) => { + const runner = new ScriptedProcessRunner([ + { match: { command: "xcrun", args: simctlArgs("boot", data.udid) } }, + { match: { command: "xcrun", args: simctlArgs("bootstatus", data.udid, "-b") } }, + { match: simctl("listapps", data.udid) }, + ]); + const onSlimSkipped = vi.fn(); + const driver = await createSlimDriver( + runner, + new MemoryFilesystem(), + slimOptions(), + undefined, + onSlimSkipped, + ); - await driver.makeReady( - { address: slim17_5.udid, deviceId: slim17_5.udid, driverData: slim17_5 }, - prepareSlim, - ); + const result = await driver.makeReady( + { address: data.udid, deviceId: data.udid, driverData: data }, + prepareSlim, + ); - expect(onSlimSkipped).toHaveBeenCalledWith( - expect.objectContaining({ reason: "runtime-too-old" }), - ); - }); + expect(result).toEqual({ + address: data.udid, + deviceId: data.udid, + driverData: data, + mode: "full", + }); + expect(runner.calls).toHaveLength(3); + expect(onSlimSkipped).toHaveBeenCalledWith( + expect.objectContaining({ deviceId: data.udid, reason: "runtime-too-old" }), + ); + expect(runner.calls[1]?.options).toEqual({ timeoutMs: 120_000 }); + }, + ); it("skips slim with reason unknown-runtime on an unparseable runtimeId", async () => { const runner = new ScriptedProcessRunner([ @@ -2587,46 +2521,6 @@ describe("IosSimctlDriver", () => { expect(onSlimSkipped).not.toHaveBeenCalled(); }); - it("a device already marked slim with a rejected-label history skips the whole pass on the next boot (second-review finding #3, issue #87)", async () => { - const filesystem = new MemoryFilesystem(); - await plantManagedDevice(filesystem); - await filesystem.writeFileAtomic(erasableMarkPath, JSON.stringify({ token: "tok-1" })); - const alreadySlimmedData = { - ...slim18_5, - slimMarkToken: "tok-1", - slimSignature: widgetsSignature, - }; - const runner = new ScriptedProcessRunner([ - { match: { command: "xcrun", args: simctlArgs("boot", slim18_5.udid) } }, - { match: { command: "xcrun", args: simctlArgs("bootstatus", slim18_5.udid, "-b") } }, - { match: simctl("listapps", slim18_5.udid) }, - ]); - const onSlimmed = vi.fn(); - const driver = await createSlimDriver(runner, filesystem, slimOptions(), onSlimmed); - - const result = await driver.makeReady( - { - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: alreadySlimmedData, - }, - prepareSlim, - ); - - expect(result).toEqual({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: alreadySlimmedData, - mode: "slim", - }); - expect(runner.calls.map((call) => call.args)).toEqual([ - simctlArgs("boot", slim18_5.udid), - simctlArgs("bootstatus", slim18_5.udid, "-b"), - simctlArgs("listapps", slim18_5.udid), - ]); - expect(onSlimmed).not.toHaveBeenCalled(); - }); - it("4 chunks, one times out: reboots, writes no marker, and a later boot re-applies (finding #2, issue #87 review; second-review finding #3)", async () => { // why: The full, unfiltered label set (~170 labels, per the SLIM_CHUNK_SIZE=50 comment in // index.ts) chunks into 4 `simctl spawn` calls. If the last one times out under load, the @@ -3914,42 +3808,35 @@ describe("IosSimctlDriver listComponents()", () => { expect(runner.calls[2]?.args).toEqual(deleteInvocation.args); }); - it("reports three unused default-set devices as unavailable in residue, naming xcrun simctl delete unavailable (#241)", async () => { - const runner = new ScriptedProcessRunner([ - imagesListed([target]), - defaultSetListed({ [target.runtime]: { unused: 3 } }), - deleted, - imagesListed([]), - imagesListed([]), - defaultSetListed({ [target.runtime]: { unused: 3 } }), - ]); - const driver = await createDriver(runner, new FakeClock(), await assetStore([])); - - const removal = await driver.removeComponent(receipt, { signal: signal() }); - - expect(removal.residue).toBe( + it.each([ + [ + 3, "3 never-used simulators in the default device set are now unavailable; Simlock does " + "not delete simulators there -- `xcrun simctl delete unavailable` clears them", - ); - }); - - it("names a single unused default-set device in the singular in residue (#241)", async () => { - const runner = new ScriptedProcessRunner([ - imagesListed([target]), - defaultSetListed({ [target.runtime]: { unused: 1 } }), - deleted, - imagesListed([]), - imagesListed([]), - defaultSetListed({ [target.runtime]: { unused: 1 } }), - ]); - const driver = await createDriver(runner, new FakeClock(), await assetStore([])); + ], + [ + 1, + "1 never-used simulator in the default device set is now unavailable; Simlock does " + + "not delete simulators there -- `xcrun simctl delete unavailable` clears them", + ], + ])( + "reports %s unused default-set devices as unavailable in residue, naming xcrun simctl delete unavailable, in the singular for one (#241)", + async (unused, residue) => { + const runner = new ScriptedProcessRunner([ + imagesListed([target]), + defaultSetListed({ [target.runtime]: { unused } }), + deleted, + imagesListed([]), + imagesListed([]), + defaultSetListed({ [target.runtime]: { unused } }), + ]); + const driver = await createDriver(runner, new FakeClock(), await assetStore([])); - const removal = await driver.removeComponent(receipt, { signal: signal() }); + const removal = await driver.removeComponent(receipt, { signal: signal() }); - expect(removal.residue).toMatch( - /^1 never-used simulator in the default device set is now unavailable;/, - ); - }); + expect(removal.residue).toBe(residue); + }, + ); it("carries both the unavailable devices and the download left in the asset store in residue (#241)", async () => { const runner = new ScriptedProcessRunner([ @@ -4510,18 +4397,6 @@ describe("IosSimctlDriver defaultModels", () => { ], }); }); - - it("has no iOS list for auto or desktop", async () => { - const driver = await createDriver(new ScriptedProcessRunner([])); - - expect(Object.keys(driver.defaultModels).sort()).toEqual([ - "phone", - "tablet", - "tv", - "vision", - "watch", - ]); - }); }); describe("IosSimctlDriver toolVersions()", () => { diff --git a/src/drivers/ios/physical.test.ts b/src/drivers/ios/physical.test.ts index 7e87409f1..10148c793 100644 --- a/src/drivers/ios/physical.test.ts +++ b/src/drivers/ios/physical.test.ts @@ -953,21 +953,6 @@ describe("IosSimctlDriver physical handler: enrollment", () => { }, ); - it("inspectPhysical runs only list devices, device info lockState and device info apps", async () => { - const lab = enrollableLab(); - - const result = await inspect(lab, PHONE_UDID); - - expect(result).toMatchObject({ enrollable: true }); - const verbs = lab.calls().map((argv) => argv.slice(0, 4).join(" ")); - expect(verbs).toEqual([ - "xcrun devicectl list devices", - "xcrun devicectl device info", - "xcrun devicectl device info", - ]); - expect(lab.calls().map((argv) => argv[4])).toEqual(["--json-output", "lockState", "apps"]); - }); - it.each([ { change: {}, @@ -1299,20 +1284,6 @@ describe("IosSimctlDriver physical handler: presence", () => { { driverDeviceId: UDID_A, present: false, reason: "not-present" }, ]); }); - - it("a wired, paired, physical entry with tunnelState disconnected and a lock read that answers passcodeRequired false reads present; the same entry whose lock read fails reads not present not-present", async () => { - const entry = listed(UDID_A, { tunnelState: "disconnected" }); - const answering = new Lab().list([entry]).lock(UDID_A); - const failing = new Lab().list([entry]).lock(UDID_A, { exit: 1 }); - - const present = await (await answering.driver()).listPresentPhysical([UDID_A]); - const absent = await (await failing.driver()).listPresentPhysical([UDID_A]); - - expect(present).toMatchObject([{ driverDeviceId: UDID_A, present: true }]); - expect(absent).toMatchObject([ - { driverDeviceId: UDID_A, present: false, reason: "not-present" }, - ]); - }); }); describe("IosSimctlDriver physical handler: reclaim", () => { diff --git a/src/drivers/ios/screen-capture.test.ts b/src/drivers/ios/screen-capture.test.ts index bb5c18c5a..3cac215fb 100644 --- a/src/drivers/ios/screen-capture.test.ts +++ b/src/drivers/ios/screen-capture.test.ts @@ -238,14 +238,10 @@ describe("iOS screen capture", () => { expect(await capture.unavailable()).toBeUndefined(); }); - it("reports streaming available when only the device program is missing, and the simulator program's reason when that one is", async () => { + it("reports streaming available when only the device program is missing", async () => { const { capture, filesystem } = await setup({ deviceCommand: DEVICE_COMMAND }); await filesystem.rm(DEVICE_COMMAND); expect(await capture.unavailable()).toBeUndefined(); - - await filesystem.writeFileAtomic(DEVICE_COMMAND, ""); - await filesystem.rm(COMMAND); - expect(await capture.unavailable()).toBe(`No screen capture program at ${COMMAND}`); }); it("refuses as unavailable, and says why, when the capture program is not installed", async () => { diff --git a/src/drivers/ios/slim-labels.test.ts b/src/drivers/ios/slim-labels.test.ts index 052ae1257..25e2da71f 100644 --- a/src/drivers/ios/slim-labels.test.ts +++ b/src/drivers/ios/slim-labels.test.ts @@ -73,16 +73,6 @@ describe("slimSignature", () => { expect(forward).toBe(reversed); }); - it("is prefixed with a schema version", () => { - expect(slimSignature(SLIM_CATEGORIES)).toMatch(/^v1:[0-9a-f]{16}$/); - }); - - it("changes when the set of categories changes", () => { - const all = slimSignature(SLIM_CATEGORIES); - const subset = slimSignature(SLIM_CATEGORIES.slice(0, -1)); - expect(all).not.toBe(subset); - }); - it("changes when a category's labels change", () => { const original = SLIM_CATEGORIES[0]!; const mutated = { ...original, labels: [...original.labels, "com.apple.made-up-daemon"] }; diff --git a/src/gateway/aggregate.test.ts b/src/gateway/aggregate.test.ts index a4267f0a8..6eacf618f 100644 --- a/src/gateway/aggregate.test.ts +++ b/src/gateway/aggregate.test.ts @@ -86,16 +86,6 @@ describe("aggregateStatus", () => { expect(status.workers?.map((worker) => worker.warmPool)).toEqual([block, block, undefined]); }); - it("reports the gateway's own host with no tools, not any worker's", () => { - const status = aggregateStatus( - [view({ host: hostFixture({ os: "macOS", osVersion: "15.5" }), id: "wrk_a" })], - { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, - ); - - expect(status.host).toEqual({ arch: "x64", os: "Linux", osVersion: "6.8.0", tools: [] }); - expect(status.workers?.[0]?.host?.os).toBe("macOS"); - }); - // Round 6 review: `aggregateStatus`'s whole `leaseIndex` branch was deletable with a green // suite -- replacing it with the pre-#118 `{...lease, workerId}` passthrough broke nothing, // because every case here omitted the optional `leaseIndex` and so exercised only the @@ -861,9 +851,6 @@ describe("aggregateCatalog", () => { expect(aliasedModels).toHaveLength(4096); expect(aliasedModels.filter((model) => model.startsWith("bm"))).toEqual([]); expect(platform?.modelAliases["Pixel 8"]).toEqual(names("a", 32).sort()); - const classedModels = Object.keys(platform?.modelClasses ?? {}); - expect(classedModels).toHaveLength(4096); - expect(classedModels.filter((model) => model.startsWith("bm"))).toEqual([]); expect(platform?.customModels).toHaveLength(4096); expect(platform?.customModels?.filter((model) => model.startsWith("bm"))).toEqual([]); }); diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 1c3ba6433..c7de7879f 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -1656,72 +1656,35 @@ describe("GatewayDispatcher", () => { expect(started).toBe(true); }); - it("lease.request: rejects a non-admin session naming owner with FORBIDDEN, never silently ignoring it (ADR §27a, H7)", async () => { - const { directory, dispatcher, workers } = harness(); - const client = new ScriptedWorkerClient(); - directory.add("wrk_1", client); - workers.connected("wrk_1", undefined, "0.3.0"); - workers.refresh("wrk_1", { - capacity: statusFixture().capacity, - health: "running", - queueDepth: 0, - catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) - .platforms, - downloads: { policy: "on-request" }, - }); - // Round 6 review: this harness used to connect `wrk_1` to the registry without adding a - // client for it, so removing the gate under test made the request route to an unreachable - // target, get re-queued by `#staleView`, and fail the test by *timing out* -- an outcome a - // gateway with no gate at all produces just as well. Its H3 sibling below already had the - // fix and said why; this one had been left behind. A worker able and willing to grant, - // plus `noWait`, means an ungated `owner` is caught by the lease actually being issued - // (testing rule 2: fail on a named assertion, not a schedule). - client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); - - await expect( - dispatcher.dispatch( - "lease.request", - { model: "iPhone 17", noWait: true, owner: "someone-else", platform: "ios" }, - session({ principal: "agent-1", role: "agent" }), - ), - ).rejects.toMatchObject({ code: "FORBIDDEN" }); - }); - - // H3 (round 3 review): §27a's gate here used to be `role !== "admin"`, admitting any HTTP - // `operator` bearer token connected directly to this gateway -- the same over-wide check - // `daemon/dispatcher.ts`'s own `#leaseRequest` shared. `isGatewayUplink` is narrower: it is - // stamped only on a *worker's* connection to its own configured gateway - // (`DaemonServer#acceptUplink`), and nothing forwards into a gateway's own front door the - // way a gateway forwards into a worker -- there is no "gateway of gateways" in ADR 0005. So - // no session this handler is ever called with can carry it, and `owner` is unconditionally - // `FORBIDDEN` here now, admin included: this test pins that a plain admin session (still - // `role: "admin"`, still what an operator token maps to) is refused exactly like an agent's. - it("lease.request: rejects a plain admin session (not the gateway's uplink) naming owner with FORBIDDEN -- no session ever reaching this handler is (ADR §27a, H3)", async () => { - const { directory, dispatcher, workers } = harness(); - const client = new ScriptedWorkerClient(); - directory.add("wrk_1", client); - workers.connected("wrk_1", undefined, "0.3.0"); - workers.refresh("wrk_1", { - capacity: statusFixture().capacity, - health: "running", - queueDepth: 0, - catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) - .platforms, - downloads: { policy: "on-request" }, - }); - // A worker able and willing to grant it -- so a gate that let this session's `owner` - // through would be caught by the lease actually being issued, not by an unrelated - // `NO_CAPACITY`/timeout that would pass just as well with no gate at all. - client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + it.each([ + { owner: "someone-else", principal: "agent-1", role: "agent" as const }, + { owner: "agent-7", principal: "operator-1", role: "admin" as const }, + ])( + "lease.request: rejects a $role session naming owner with FORBIDDEN, never silently ignoring it (ADR §27a, H3, H7)", + async ({ owner, principal, role }) => { + const { directory, dispatcher, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_1", client); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { + capacity: statusFixture().capacity, + health: "running", + queueDepth: 0, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "on-request" }, + }); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); - await expect( - dispatcher.dispatch( - "lease.request", - { model: "iPhone 17", noWait: true, owner: "agent-7", platform: "ios" }, - session({ principal: "operator-1", role: "admin" }), - ), - ).rejects.toMatchObject({ code: "FORBIDDEN" }); - }); + await expect( + dispatcher.dispatch( + "lease.request", + { model: "iPhone 17", noWait: true, owner, platform: "ios" }, + session({ principal, role }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }, + ); it("lease.request: forwards owner as `ownerId` end to end when the session is the gateway's own uplink (ADR §27a, H3) -- exercising the same field the worker's own dispatcher gates, on this dispatcher's shared handler shape", async () => { const { directory, dispatcher, leaseIndex, workers } = harness(); diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 00e108f10..806257c18 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -4396,26 +4396,6 @@ describe("FleetLeaseCoordinator: a requester may hold up to lease.maxPerRequeste }); }); -describe("FleetLeaseCoordinator reads a lost uplink in one place (#514)", () => { - it("reads DAEMON_STOPPING from a worker as a lost uplink: lease.request fails WORKER_UNREACHABLE", async () => { - const { coordinator, directory, workers } = harness(); - const client = new ScriptedWorkerClient(); - directory.add("wrk_a", client); - connectWorker(workers, "wrk_a"); - client.requestLeaseQueue.push({ - error: new SimlockError("DAEMON_STOPPING", "transport", "The daemon is stopping", {}), - kind: "error", - }); - - const rejection = await coordinator - .request(REQUEST, requestOptions()) - .catch((error: unknown) => error); - - expect(rejection).toBeInstanceOf(DispatchError); - expect((rejection as DispatchError).code).toBe("WORKER_UNREACHABLE"); - }); -}); - describe("FleetLeaseCoordinator lists why each worker cannot take a waiting request (#637)", () => { type Reasons = readonly { workerId: string; reason: string; capacityReason?: string }[]; @@ -4481,9 +4461,14 @@ describe("FleetLeaseCoordinator lists why each worker cannot take a waiting requ const saturatedExcept = (free: string) => (id: string) => id === free ? {} : { capacity: saturatedIos() }; - it("lists, in worker id order, drained for a drained worker and full with platform-running-limit for one with no free iOS slot", async () => { - const { coordinator, workers } = fleet(["wrk_b", "wrk_a"], (id) => - id === "wrk_b" ? { capacity: saturatedIos() } : {}, + it("lists, in worker id order, drained for a drained worker and full with platform-running-limit for one with no free iOS slot, also when it has no free global slot either", async () => { + const capacity = statusFixture().capacity; + const bothFull = { + ...saturatedIos(), + global: { ...capacity.global, maxRunning: 0 }, + }; + const { coordinator, workers } = fleet(["wrk_c", "wrk_b", "wrk_a"], (id) => + id === "wrk_b" ? { capacity: saturatedIos() } : id === "wrk_c" ? { capacity: bothFull } : {}, ); await workers.setDrained("wrk_a", true); @@ -4492,6 +4477,7 @@ describe("FleetLeaseCoordinator lists why each worker cannot take a waiting requ expect(listed(coordinator)).toEqual([ { reason: "drained", workerId: "wrk_a" }, { capacityReason: "platform-running-limit", reason: "full", workerId: "wrk_b" }, + { capacityReason: "platform-running-limit", reason: "full", workerId: "wrk_c" }, ]); }); diff --git a/src/gateway/lease-index.test.ts b/src/gateway/lease-index.test.ts index fb5223c77..0bb7d162f 100644 --- a/src/gateway/lease-index.test.ts +++ b/src/gateway/lease-index.test.ts @@ -299,15 +299,6 @@ describe("FleetLeaseIndex", () => { ), ).toBe(true); }); - - it("does not warn for an ordinary addition that was never removed by a relayed event", () => { - const logger = new RecordingLogger(); - const index = new FleetLeaseIndex(PREFIX, logger); - - index.rebuildFromWorker("wrk_1", [reported("lse_1")]); - - expect(logger.warnings).toEqual([]); - }); }); describe("forgetWorker", () => { @@ -414,15 +405,13 @@ describe("FleetLeaseIndex", () => { ]); }); - it("logs a flagged lease with an invalid ID once, not on every snapshot that repeats it", () => { - const logger = new RecordingLogger(); - const index = new FleetLeaseIndex(PREFIX, logger); + it("keeps one entry for a flagged lease with an invalid ID repeated across snapshots", () => { + const index = new FleetLeaseIndex(PREFIX); index.rebuildFromWorker("wrk_1", [chosen("not.a-valid id")]); index.rebuildFromWorker("wrk_1", [chosen("not.a-valid id")]); index.rebuildFromWorker("wrk_1", [chosen("not.a-valid id")]); - expect(logger.warnings).toHaveLength(1); expect(index.all()).toHaveLength(1); }); diff --git a/src/gateway/routing.test.ts b/src/gateway/routing.test.ts index dd2981b2f..dc530bc88 100644 --- a/src/gateway/routing.test.ts +++ b/src/gateway/routing.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from "vitest"; import { createRoutingPolicy } from "./routing.js"; -import * as routingModule from "./routing/index.js"; import { canServe, freeCapacity, @@ -411,14 +410,6 @@ describe("the warm-then-free policy for a physical request", () => { expect(skipped).toEqual(["freeCapacity", "freeSlot", "idleQueue", "ramBudget"]); }); - it("lists no physical-interim stage in any policy", () => { - const sole = view("wrk_a", { devices: [iphone()] }); - - expect(Object.keys(routingModule)).not.toContain("physicalInterim"); - expect(policy.select(PHYSICAL, [sole])?.stage).toBe("warm-hit"); - expect(policy.select(PHYSICAL, [view("wrk_b")])?.stage).not.toBe("physical-interim"); - }); - it("gives a virtual request the same pick, reason and stage with and without a ready physical device of its model in the views", () => { const sim = view("wrk_b", { capacity: withIos({ maxRunning: 3 }), diff --git a/src/gateway/routing/stages/free-slot.test.ts b/src/gateway/routing/stages/free-slot.test.ts deleted file mode 100644 index 3f64e0591..000000000 --- a/src/gateway/routing/stages/free-slot.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { catalogFixture, statusFixture } from "../../test-support.js"; -import type { WorkerView } from "../../worker-registry.js"; -import { freeSlot } from "./free-slot.js"; - -const REQUEST = { model: "iPhone 17", platform: "ios" as const }; - -function view(capacity: WorkerView["capacity"]): WorkerView { - return { - catalog: catalogFixture([]).platforms, - connection: "connected", - devices: [], - drained: false, - id: "wrk_a", - lastSeenAt: 1, - leases: [], - ...(capacity === undefined ? {} : { capacity }), - }; -} - -describe("free-slot", () => { - it("keeps a worker with a free slot for the platform and overall, and drops one whose capacity has not been read", () => { - expect(freeSlot.check(view(statusFixture().capacity), REQUEST)).toBeUndefined(); - expect(freeSlot.check(view(undefined), REQUEST)).toBeDefined(); - }); -}); - -describe("free-slot's reason", () => { - const base = statusFixture().capacity; - const full = { maxRunning: 1, running: 1, reserved: 0, warm: 0 }; - const ios = (entry: object) => ({ ...base, ios: { ...base.ios, ...entry } }); - const global = (entry: object) => ({ ...base, global: { ...base.global, ...entry } }); - - it("names full with platform-running-limit when the platform has no free or evictable slot, also when global has none", () => { - const platformFull = { reason: "full", capacityReason: "platform-running-limit" }; - - expect(freeSlot.check(view(statusFixture().capacity), REQUEST)).toBeUndefined(); - expect(freeSlot.check(view(ios(full)), REQUEST)).toEqual(platformFull); - expect( - freeSlot.check(view({ ...ios(full), global: { ...base.global, ...full } }), REQUEST), - ).toEqual(platformFull); - }); - - it("names full with global-running-limit when only global has no free or evictable slot, and counts an unleased running device as free", () => { - expect(freeSlot.check(view(global(full)), REQUEST)).toEqual({ - capacityReason: "global-running-limit", - reason: "full", - }); - expect(freeSlot.check(view(global({ ...full, warm: 1 })), REQUEST)).toBeUndefined(); - expect(freeSlot.check(view(ios({ ...full, warm: 1 })), REQUEST)).toBeUndefined(); - }); -}); diff --git a/src/gateway/routing/stages/ram-budget.test.ts b/src/gateway/routing/stages/ram-budget.test.ts deleted file mode 100644 index b2c186b0e..000000000 --- a/src/gateway/routing/stages/ram-budget.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { catalogFixture, statusFixture } from "../../test-support.js"; -import type { WorkerView } from "../../worker-registry.js"; -import { runStages } from "../pipeline.js"; -import { ramBudget } from "./ram-budget.js"; - -const REQUEST = { model: "iPhone 17", platform: "ios" as const }; - -function view(capacity: WorkerView["capacity"]): WorkerView { - return { - catalog: catalogFixture([]).platforms, - connection: "connected", - devices: [], - drained: false, - id: "wrk_a", - lastSeenAt: 1, - leases: [], - ...(capacity === undefined ? {} : { capacity }), - }; -} - -describe("ram-budget", () => { - it("scores a worker at its budget for the platform zero, and one under it, or not reporting, above zero", () => { - const capacity = statusFixture().capacity; - const atBudget = { ...capacity, ios: { ...capacity.ios, atRamBudget: true } }; - - expect(ramBudget.score(view(atBudget), REQUEST)).toBe(0); - expect(ramBudget.score(view(capacity), REQUEST)).toBeGreaterThan(0); - expect(ramBudget.score(view(undefined), REQUEST)).toBeGreaterThan(0); - }); - - it("is named ram-budget when it is the stage that removed the worker at its budget", () => { - const capacity = statusFixture().capacity; - const atBudget = { ...capacity, ios: { ...capacity.ios, atRamBudget: true } }; - const under = { ...view(capacity), id: "wrk_b" }; - - expect(runStages([ramBudget], REQUEST, [view(atBudget), under])).toEqual({ - stage: "ram-budget", - workerId: "wrk_b", - }); - }); -}); - -describe("ram-budget's zero reason", () => { - it("gives full with ram-budget for a worker it scores zero, and nothing for one under its budget", () => { - const capacity = statusFixture().capacity; - const atBudget = { ...capacity, ios: { ...capacity.ios, atRamBudget: true } }; - - expect(ramBudget.zeroReason?.(view(atBudget), REQUEST)).toEqual({ - capacityReason: "ram-budget", - reason: "full", - }); - expect(ramBudget.zeroReason?.(view(capacity), REQUEST)).toBeUndefined(); - }); -}); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 22ddb4105..ce883c3a0 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -581,56 +581,6 @@ describe("GatewayService", () => { await harness.service.stop(); }); - it("republishes a worker's events with its workerId, into its own ring buffer", async () => { - const harness = fleet(); - await harness.service.start(); - const worker = new ScriptedWorkerClient(); - await harness.join("wrk_1", worker); - await vi.waitFor(() => expect(worker.subscribed).toBe(true)); - - worker.pushEvent({ - event: "lease.granted", - module: "lease-engine", - payload: { deviceId: "dev_1", leaseId: "lease_1", requester: "agent-1" }, - }); - - const republished = harness.events.find((event) => event.event === "lease.granted"); - expect(republished).toMatchObject({ - // The name and the emitting module travel unchanged -- the fact happened in that - // worker's leasing module, and `workerId` is what says which machine. - module: "lease-engine", - payload: { deviceId: "dev_1", leaseId: "lease_1", workerId: "wrk_1" }, - }); - - await harness.service.stop(); - }); - - it("a worker's event relayed by the gateway keeps the worker's id and timestamp and gains workerId", async () => { - const harness = fleet(); - await harness.service.start(); - const worker = new ScriptedWorkerClient(); - await harness.join("wrk_1", worker); - await vi.waitFor(() => expect(worker.subscribed).toBe(true)); - harness.clock.advance(5_000); - - worker.pushEvent({ - event: "lease.granted", - id: "evt_worker-made", - module: "lease-engine", - payload: { deviceId: "dev_1", leaseId: "lease_1", requester: "agent-1" }, - timestamp: 777, - }); - - const relayed = harness.events.find((event) => event.event === "lease.granted"); - expect(relayed).toMatchObject({ - id: "evt_worker-made", - timestamp: 777, - payload: { workerId: "wrk_1" }, - }); - - await harness.service.stop(); - }); - it("a relayed event differs from the worker's only in seq and payload.workerId", async () => { const harness = fleet(); await harness.service.start(); @@ -685,60 +635,43 @@ describe("GatewayService", () => { // worker's own -- `workerId` is merged in last so it cannot be spoofed, but a worker (or // anything speaking its protocol) could otherwise forge a fact only a gateway authors, such as // `worker.drain-ended`, straight into the operator's audit trail. - it("refuses to republish a worker's event under a name reserved for the gateway itself", async () => { - const harness = fleet(); - await harness.service.start(); - const worker = new ScriptedWorkerClient(); - await harness.join("wrk_1", worker); - await vi.waitFor(() => expect(worker.subscribed).toBe(true)); - - worker.pushEvent({ + it.each([ + { event: "worker.drain-ended", module: "gateway", payload: { workerId: "wrk_forged", label: "not-this-worker" }, - }); - worker.pushEvent({ - event: "lease.granted", - module: "lease-engine", - payload: { deviceId: "dev_1", leaseId: "lease_1", requester: "agent-1" }, - }); - await vi.waitFor(() => - expect(harness.events.some((event) => event.event === "lease.granted")).toBe(true), - ); - - const forged = harness.events.filter((event) => event.event === "worker.drain-ended"); - // Never forwarded, and never with the forged `workerId` a real gateway-authored - // `worker.drain-ended` for a *different* worker would otherwise be indistinguishable from. - expect(forged).toEqual([]); - - await harness.service.stop(); - }); - - it("refuses to republish a request.granted a worker pushes, which only the gateway itself emits (ADR 0021 §4)", async () => { - const harness = fleet(); - await harness.service.start(); - const worker = new ScriptedWorkerClient(); - await harness.join("wrk_1", worker); - await vi.waitFor(() => expect(worker.subscribed).toBe(true)); - - worker.pushEvent({ + }, + { event: "request.granted", module: "fleet-lease-coordinator", payload: { leaseId: "wrk_1.lease_1", requestId: "req_forged", worker: "wrk_1" }, - }); - worker.pushEvent({ - event: "lease.granted", - module: "lease-engine", - payload: { deviceId: "dev_1", leaseId: "lease_1", requester: "agent-1" }, - }); - await vi.waitFor(() => - expect(harness.events.some((event) => event.event === "lease.granted")).toBe(true), - ); + }, + ])( + "refuses to republish a $event a worker pushes under a name reserved for the gateway itself (ADR 0021 §4)", + async (forgedEvent) => { + const harness = fleet(); + await harness.service.start(); + const worker = new ScriptedWorkerClient(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(worker.subscribed).toBe(true)); - expect(harness.events.filter((event) => event.event === "request.granted")).toEqual([]); + worker.pushEvent(forgedEvent); + worker.pushEvent({ + event: "lease.granted", + module: "lease-engine", + payload: { deviceId: "dev_1", leaseId: "lease_1", requester: "agent-1" }, + }); + await vi.waitFor(() => + expect(harness.events.some((event) => event.event === "lease.granted")).toBe(true), + ); - await harness.service.stop(); - }); + // why: never forwarded, and never with the forged `workerId` a real gateway-authored event + // for a *different* worker would otherwise be indistinguishable from. + expect(harness.events.filter((event) => event.event === forgedEvent.event)).toEqual([]); + + await harness.service.stop(); + }, + ); it("refuses to republish a request.dispatched a worker pushes, which only the gateway itself emits", async () => { const harness = fleet(); @@ -1138,19 +1071,6 @@ describe("GatewayService", () => { expect(harness.service.workers.view("wrk_1")?.connection).toBe("connected"); await harness.service.stop(); }); - - it("carries the worker's own downloads.timeoutMs on the view", async () => { - const worker = new ScriptedWorkerClient(); - worker.downloadTimeoutMs = 45 * 60_000; - - const harness = await joined(worker); - - expect(harness.service.workers.view("wrk_1")?.downloads).toEqual({ - policy: "on-request", - timeoutMs: 45 * 60_000, - }); - await harness.service.stop(); - }); }); describe("warning on a worker's lower lease.maxTtlMs (ADR 0005 §15)", () => { @@ -1260,28 +1180,6 @@ describe("GatewayService", () => { await harness.service.stop(); }); - it("marks a worker one protocol version behind the gateway incompatible (ADR 0022 §2: it does not know `device.add` or `device.remove`, and reports no `driverDeviceId`)", async () => { - const previous = { - min: PROTOCOL_VERSION_RANGE.max - 1, - max: PROTOCOL_VERSION_RANGE.max - 1, - }; - expect(PROTOCOL_VERSION_RANGE.max).toBe(52); - expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, previous)).toBeUndefined(); - const harness = fleet(); - await harness.service.start(); - const worker = new ScriptedWorkerClient(); - worker.failWith = protocolMismatchError(previous); - - await harness.join("wrk_1", worker); - await vi.waitFor(() => - expect(harness.service.workers.view("wrk_1")?.connection).toBe("incompatible"), - ); - - expect(worker.calls).toEqual(["status.get"]); - - await harness.service.stop(); - }); - it("a worker advertising protocol 10 is incompatible on the gateway and nothing it pushes reaches the gateway's bus", async () => { const worker10 = { min: 10, max: 10 }; expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, worker10)).toBeUndefined(); @@ -1521,38 +1419,6 @@ describe("GatewayService", () => { await harness.service.stop(); }); - // H4: a timed-out `events.subscribe` used to be logged exactly like a rejection ("Worker - // refused an event subscription"), asserting something this code cannot know -- the worker may - // never have answered at all, or may have subscribed successfully with the reply just arriving - // too late to matter. The two are worth telling apart in a log an operator reads. - it("logs a timed-out event subscription as a timeout, not a refusal (H4)", async () => { - const logger = new RecordingLogger(); - const harness = fleet({ logger }); - await harness.service.start(); - const worker = new ScriptedWorkerClient(); - // Never resolves, unlike a real rejection -- the exact shape of a subscribe call that just - // never gets an answer within `WORKER_CALL_TIMEOUT_MS`. Tracked by hand rather than via - // `pendingTimerCount` alone: the service's own periodic tick timer is already pending from - // `service.start()`, so that check alone cannot tell "the subscribe call's own timeout timer - // is now armed" apart from "some timer, possibly the unrelated tick, exists". - let subscribeCalled = false; - worker.subscribeEvents = (): Promise => { - subscribeCalled = true; - return new Promise(() => {}); - }; - - await harness.join("wrk_1", worker); - await vi.waitFor(() => expect(subscribeCalled).toBe(true)); - harness.clock.advance(WORKER_CALL_TIMEOUT_MS); - - await vi.waitFor(() => - expect(logger.warnings.some((entry) => entry.message.includes("did not answer"))).toBe(true), - ); - expect(logger.warnings.some((entry) => entry.message.includes("refused"))).toBe(false); - - await harness.service.stop(); - }); - // P1: a refresh timeout used to be swallowed into a debug log with nothing acting on it, so a // half-open uplink (NAT rebind, cable pull, kernel panic -- no FIN) had `connection` report // `connected` forever with a `lastSeenAt` that never moved again. One timeout recovering on diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index aced2c1c0..f6a297a75 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -388,18 +388,6 @@ describe("WorkerRegistry", () => { expect(view.protocol).toBeUndefined(); }); - it.each(["unauthenticated", "forbidden"] as const)( - "reports a %s uplink without inventing a view for it", - (reason) => { - const { events, workers } = registry(); - - workers.rejected(reason, undefined, undefined); - - expect(workers.views()).toEqual([]); - expect(events[0]).toMatchObject({ event: "worker.rejected", payload: { reason } }); - }, - ); - describe("a worker's load on its view", () => { const load = { cpu: { busyPercent: 34, cores: 10, limited: false }, diff --git a/src/history/projections/conformance.test.ts b/src/history/projections/conformance.test.ts index f1068fa3b..effa591c5 100644 --- a/src/history/projections/conformance.test.ts +++ b/src/history/projections/conformance.test.ts @@ -3,16 +3,9 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; -import { EventBus, type EventEnvelope } from "../../bus/index.js"; -import { - FakeClock, - JsonLinesLogger, - MemoryLogSink, - NodeFilesystem, - NodeSqliteOpener, - type SqliteDatabase, -} from "../../ports/index.js"; -import { createEventHistory, HISTORY_DB_NAME, type HistoryProjectionDefinition } from "../index.js"; +import type { EventEnvelope } from "../../bus/index.js"; +import { NodeSqliteOpener, type SqliteDatabase } from "../../ports/index.js"; +import type { HistoryProjectionDefinition } from "../index.js"; import { HISTORY_PROJECTIONS } from "./index.js"; const directories: string[] = []; @@ -23,79 +16,6 @@ afterEach(async () => { ); }); -async function projectionRows(path: string): Promise> { - const database = await new NodeSqliteOpener().open(path, { readOnly: true }); - try { - const tables = database - .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'") - .all() - .map((row) => String(row.name)) - .filter((name) => name !== "events"); - return Object.fromEntries( - tables.map((name) => [ - name, - Number(database.prepare(`SELECT count(*) AS n FROM "${name}"`).get()?.n), - ]), - ); - } finally { - database.close(); - } -} - -async function run( - definition: HistoryProjectionDefinition, - act: (bus: EventBus, wrapped: { applied: string[] }) => void, - options: { readonly throwOn?: string } = {}, -): Promise<{ - readonly applied: string[]; - readonly events: number; - readonly rows: Record; - readonly writing: boolean; -}> { - const directory = await mkdtemp(join(tmpdir(), "simlock-projection-")); - directories.push(directory); - const clock = new FakeClock(1_000); - const bus = new EventBus(clock); - const applied: string[] = []; - const wrapped: HistoryProjectionDefinition = { - ...definition, - create: (database, projectionOptions) => { - const inner = definition.create(database, projectionOptions); - return { - apply: (envelope) => { - applied.push(envelope.id); - inner.apply(envelope); - if (options.throwOn === envelope.id) throw new Error("apply failed"); - }, - prune: (now) => inner.prune(now), - rebuild: (oldest) => inner.rebuild(oldest), - }; - }, - }; - const history = createEventHistory({ - bus, - clock, - config: { maxBytes: 256 * 1024 * 1024, retention: 7 * 24 * 3_600_000 }, - dataDirectory: directory, - filesystem: new NodeFilesystem(), - logger: new JsonLinesLogger({ clock, sink: new MemoryLogSink() }), - projectionOptions: { fleet: false, metricsRetentionMs: 90 * 24 * 3_600_000 }, - projections: [wrapped], - sqlite: new NodeSqliteOpener(), - }); - await history.start(); - act(bus, { applied }); - const events = (await history.replay({ sinceTs: 0 })).length; - const writing = history.status().writing; - await history.stop(); - return { - applied, - events, - rows: await projectionRows(join(directory, HISTORY_DB_NAME)), - writing, - }; -} - async function openScratch(): Promise { const directory = await mkdtemp(join(tmpdir(), "simlock-projection-")); directories.push(directory); @@ -144,26 +64,6 @@ function conformance( registry: Readonly>, ) { describe.each(Object.entries(registry))(`${label} projection %s`, (_name, definition) => { - const relay = (bus: EventBus, id: string): void => { - bus.republish({ - event: "daemon.stopping", - id, - module: "daemon", - payload: { reason: id }, - timestamp: 1_000, - }); - }; - - it("apply of a duplicate never runs", async () => { - const result = await run(definition, (bus) => { - relay(bus, "evt_a"); - relay(bus, "evt_a"); - }); - - expect(result.applied).toEqual(["evt_a"]); - expect(result.events).toBe(1); - }); - it("its migrations from version 0 reach its version, and the check holds there", async () => { const database = await openScratch(); try { @@ -250,22 +150,6 @@ function conformance( database.close(); } }); - - it("a throwing apply writes nothing", async () => { - const baseline = await run(definition, (bus) => relay(bus, "evt_a")); - const result = await run( - definition, - (bus) => { - relay(bus, "evt_a"); - relay(bus, "evt_boom"); - }, - { throwOn: "evt_boom" }, - ); - - expect(result.events).toBe(1); - expect(result.rows).toEqual(baseline.rows); - expect(result.writing).toBe(false); - }); }); } diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 60b0a9ffa..d5e6122eb 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -628,21 +628,19 @@ describe("POST /v1/lease-requests", () => { expect(dispatcher.calls).toHaveLength(0); }); - it("forwards a body's imageTag to the dispatched lease.request", async () => { - const { app, dispatcher } = buildHarness(); - void postLeaseRequest(app, { ...defaultBody, imageTag: "google_apis_playstore" }); - const call = await waitForDispatch(dispatcher, "lease.request"); - expect(call.input).toMatchObject({ imageTag: "google_apis_playstore" }); - }); - - it("forwards a body's physical true to the dispatched lease.request", async () => { + it.each([ + ["imageTag", { imageTag: "google_apis_playstore" }], + ["mode", { mode: "slim" }], + ["owner field rather than silently dropping it (ADR §27a, H7)", { owner: "someone-else" }], + ["physical true", { physical: true }], + ])("forwards a body's %s to the dispatched lease.request", async (_label, extra) => { const { app, dispatcher } = buildHarness(); const first = await Promise.race([ - postLeaseRequest(app, { ...defaultBody, physical: true }), + postLeaseRequest(app, { ...defaultBody, ...extra }), waitForDispatch(dispatcher, "lease.request").then((call) => call), ]); if (first instanceof Response) throw new Error(`the body was refused with ${first.status}`); - expect(first.input).toMatchObject({ physical: true }); + expect(first.input).toMatchObject(extra); }); it("answers 400 BAD_REQUEST naming allowDownload for a body with physical true and allowDownload true", async () => { @@ -665,21 +663,6 @@ describe("POST /v1/lease-requests", () => { expect(body.error.message).toContain("allowDownload"); }); - it("forwards a body's mode to the dispatched lease.request", async () => { - const { app, dispatcher } = buildHarness(); - void postLeaseRequest(app, { ...defaultBody, mode: "slim" }); - const call = await waitForDispatch(dispatcher, "lease.request"); - expect(call.input).toMatchObject({ mode: "slim" }); - }); - - it("forwards a body's owner field to the dispatched lease.request rather than silently dropping it (ADR §27a, H7)", async () => { - const { app, dispatcher } = buildHarness(); - void postLeaseRequest(app, { ...defaultBody, owner: "someone-else" }); - const call = await waitForDispatch(dispatcher, "lease.request"); - - expect((call.input as { owner?: string }).owner).toBe("someone-else"); - }); - it("builds an operator token's session as admin but never as the gateway's uplink, so §27a's owner gate still refuses it at the shared dispatcher (ADR §27a, H3)", async () => { const { app, dispatcher } = buildHarness(); void postLeaseRequest(app, { ...defaultBody, owner: "someone-else" }, operatorAuth); @@ -2229,27 +2212,6 @@ describe("operator-only listing routes", () => { expect(asked.map((input) => input.includeLedger === true)).toEqual([false, true]); }); - - it("answers HISTORY_NOT_KEPT with status 422 and oldestTs in the body, and HISTORY_UNAVAILABLE with 503", async () => { - const { dispatcher, get } = statsHarness(); - dispatcher.handlers["usage.get"] = () => { - throw new DispatchError("HISTORY_NOT_KEPT", "The history does not reach back.", { - oldestTs: 1_234, - }); - }; - const notKept = await get("?since=1h"); - dispatcher.handlers["usage.get"] = () => { - throw new DispatchError("HISTORY_UNAVAILABLE", "The history could not be opened."); - }; - const unavailable = await get("?since=1h"); - - expect(notKept.status).toBe(422); - expect(await notKept.json()).toMatchObject({ - error: { code: "HISTORY_NOT_KEPT", oldestTs: 1_234 }, - }); - expect(unavailable.status).toBe(503); - expect(await unavailable.json()).toMatchObject({ error: { code: "HISTORY_UNAVAILABLE" } }); - }); }); it("GET /v1/events/stream dispatches events.subscribe then follows the raw event bus live", async () => { @@ -2420,17 +2382,6 @@ describe("worker routes", () => { ]); }); - it("leaves the role check to the shared dispatcher, which 403s an agent token", async () => { - const { app, dispatcher } = gatewayHarness(); - dispatcher.handlers["worker.list"] = () => { - throw new DispatchError("FORBIDDEN", "Operation worker.list requires role admin"); - }; - - const response = await app.request("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/v1/workers", { headers: agentAuth }); - - expect(response.status).toBe(403); - }); - it("puts a refusal's typed details in the body, so a client need not parse prose", async () => { const { app, dispatcher } = gatewayHarness(); dispatcher.handlers["worker.remove"] = () => { diff --git a/src/http/auth.test.ts b/src/http/auth.test.ts index a533a2a0a..b0f6fe32c 100644 --- a/src/http/auth.test.ts +++ b/src/http/auth.test.ts @@ -3,18 +3,12 @@ import { describe, expect, it, vi } from "vitest"; import { type Auth, - type Identity, type AuthStrategyDefinition, createAuth, type StrategyAnswer, } from "../auth/index.js"; import { tokensOwner } from "../auth/index.js"; -import { - createAuthWith, - fakeAuth, - openMemoryStateDatabase, - tokenIdentity, -} from "../auth/testing.js"; +import { createAuthWith, openMemoryStateDatabase } from "../auth/testing.js"; import { CryptoTokenSecrets, FakeClock, @@ -25,57 +19,6 @@ import { import { type AuthEnv, requireAuth } from "./auth.js"; import { errorResponse } from "./errors.js"; -function appWithAuth(identities: Map) { - const app = new Hono(); - app.onError((error, c) => errorResponse(c, error)); - app.get("/resource", requireAuth(fakeAuth(identities)), (c) => - c.json({ identity: c.get("identity") }), - ); - return app; -} - -describe("requireAuth", () => { - it("401s with no Authorization header", async () => { - const response = await appWithAuth(new Map()).request("/resource"); - expect(response.status).toBe(401); - expect(await response.json()).toEqual({ - error: { code: "UNAUTHENTICATED", message: expect.any(String) }, - }); - }); - - it("401s on a malformed Authorization header (no Bearer prefix)", async () => { - const response = await appWithAuth(new Map()).request("/resource", { - headers: { authorization: "slk_secret" }, - }); - expect(response.status).toBe(401); - }); - - it("401s on an unknown bearer token", async () => { - const response = await appWithAuth(new Map()).request("/resource", { - headers: { authorization: "Bearer slk_unknown" }, - }); - expect(response.status).toBe(401); - }); - - it("admits a known agent token and stores its identity", async () => { - const agent = tokenIdentity("tok_agent", "agent"); - const response = await appWithAuth(new Map([["slk_agent", agent]])).request("/resource", { - headers: { authorization: "Bearer slk_agent" }, - }); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ identity: agent }); - }); - - it("admits a known operator token too -- role gating is the shared dispatcher's job now, not this middleware's", async () => { - const operator = tokenIdentity("tok_op", "operator"); - const response = await appWithAuth(new Map([["slk_op", operator]])).request("/resource", { - headers: { authorization: "Bearer slk_op" }, - }); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ identity: operator }); - }); -}); - describe("requireAuth over src/auth", () => { async function authOptions() { const { database } = await openMemoryStateDatabase([tokensOwner]); diff --git a/src/http/errors.test.ts b/src/http/errors.test.ts index 25084b24f..d9397171a 100644 --- a/src/http/errors.test.ts +++ b/src/http/errors.test.ts @@ -175,19 +175,6 @@ describe("errorResponse", () => { }); }); - it("includes extra fields (e.g. existingLeaseId) alongside code/message", async () => { - const response = await appWithError( - new RequesterAlreadyLeasedError("agent-1", "lse_9"), - ).request("/boom"); - expect(await response.json()).toEqual({ - error: { - code: "REQUESTER_ALREADY_LEASED", - existingLeaseId: "lse_9", - message: expect.any(String), - }, - }); - }); - it("sets Retry-After on a NO_CAPACITY response", async () => { const response = await appWithError(new NoCapacityError()).request("/boom"); expect(response.status).toBe(503); diff --git a/src/http/server.test.ts b/src/http/server.test.ts index 11e31945f..99b98a7e9 100644 --- a/src/http/server.test.ts +++ b/src/http/server.test.ts @@ -49,8 +49,7 @@ function harness(root: string) { const auth = fakeAuth( new Map([["slk_operator", tokenIdentity("tok_operator", "operator")]]), ); - const logSink = new MemoryLogSink(); - const logger = new JsonLinesLogger({ clock, sink: logSink }); + const logger = new JsonLinesLogger({ clock, sink: new MemoryLogSink() }); const app = createHttpApp({ clock, config: testConfig(), @@ -66,7 +65,7 @@ function harness(root: string) { const site = withConsole(app, { logger, root }); const get = (path: string, init: RequestInit = {}) => Promise.resolve(site.fetch(new Request(`http://127.0.0.1:4700${path}`, init))); - return { app, get, logSink }; + return { app, get }; } describe("withConsole", () => { @@ -187,22 +186,6 @@ describe("withConsole", () => { expect(post.status).toBe(404); }); - it("console requests are not written to the request log", async () => { - const { get, logSink } = harness(await builtConsole()); - - await get("/"); - await get("/workers"); - await get("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/assets/index-3f2a9c.js"); - await get("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/assets/missing.js"); - await get("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/v1/status", { headers: { authorization: "Bearer slk_operator" } }); - - const logged = logSink.records - .filter((record) => record.message === "request") - .map((record) => record.fields?.path); - // The API's own request still is: the log is wired, and only console paths skip it. - expect(logged).toEqual(["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/v1/status"]); - }); - it("answers 404 on the page and on files when the console is not built", async () => { const root = await emptyRoot(); // A stray file in an unbuilt root is still not served: without index.html there is no console. @@ -231,22 +214,6 @@ describe("HttpGateway", () => { return { gateway, port, warnings }; } - it("the daemon warns once at start when the console is not built", async () => { - const { gateway, port, warnings } = await started(await emptyRoot()); - try { - // Already logged once the listener is up, before any request arrives. - const atStart = warnings(); - const page = await fetch(`http://127.0.0.1:${port}/`); - await fetch(`http://127.0.0.1:${port}/workers`); - - expect(atStart).toEqual(["The web console is not built; console paths answer 404"]); - expect(page.status).toBe(404); - expect(warnings()).toEqual(atStart); - } finally { - await gateway.stop(); - } - }); - it("serves the console page at / on its listener, with no warning when it is built", async () => { const { gateway, port, warnings } = await started(await builtConsole()); try { diff --git a/src/http/tracker.test.ts b/src/http/tracker.test.ts index e3ea0b5bb..db5843465 100644 --- a/src/http/tracker.test.ts +++ b/src/http/tracker.test.ts @@ -131,16 +131,6 @@ describe("LeaseRequestTracker.submit", () => { } }); - it("replays an Idempotency-Key for the same requester instead of double-submitting", async () => { - const { dispatcher, tracker } = buildTracker(); - const { view: first } = await createTrackedWithKey(tracker, dispatcher, "key-1"); - - const replay = await tracker.submit(identity, body, "key-1"); - expect(replay.kind).toBe("created"); - if (replay.kind === "created") expect(replay.view.id).toBe(first.id); - expect(dispatcher.calls.filter((c) => c.operation === "lease.request")).toHaveLength(1); - }); - it("does not replay an Idempotency-Key across different requesters", async () => { const { dispatcher, tracker } = buildTracker(); await createTrackedWithKey(tracker, dispatcher, "key-1"); @@ -296,16 +286,23 @@ describe("LeaseRequestTracker.submit with allowDownload on a gateway", () => { }); }); -describe("LeaseRequestTracker.submit with a mode", () => { - it("passes mode through onto the dispatch input, and omits it when the body names none", async () => { - const { dispatcher, tracker } = buildTracker(); - await createTracked(tracker, dispatcher, { ...body, mode: "slim" }); - expect(dispatcher.calls[0]?.input).toMatchObject({ mode: "slim" }); +describe("LeaseRequestTracker.submit with an optional request field", () => { + it.each([ + ["mode", { mode: "slim" }], + ["imageTag", { imageTag: "google_apis_playstore" }], + ["physical", { physical: true }], + ] as const)( + "passes %s through onto the dispatch input, and omits it when the body names none", + async (field, extra) => { + const { dispatcher, tracker } = buildTracker(); + await createTracked(tracker, dispatcher, { ...body, ...extra }); + expect(dispatcher.calls[0]?.input).toMatchObject(extra); - const { dispatcher: dispatcher2, tracker: tracker2 } = buildTracker(); - await createTracked(tracker2, dispatcher2); - expect(dispatcher2.calls[0]?.input).not.toHaveProperty("mode"); - }); + const { dispatcher: dispatcher2, tracker: tracker2 } = buildTracker(); + await createTracked(tracker2, dispatcher2); + expect(Object.keys(dispatcher2.calls[0]?.input ?? {})).not.toContain(field); + }, + ); }); describe("LeaseRequestTracker granted lease payload", () => { @@ -381,30 +378,6 @@ describe("LeaseRequestTracker granted lease payload", () => { }); }); -describe("LeaseRequestTracker.submit with an image tag", () => { - it("passes imageTag through onto the dispatch input, and omits it when the body names none", async () => { - const { dispatcher, tracker } = buildTracker(); - await createTracked(tracker, dispatcher, { ...body, imageTag: "google_apis_playstore" }); - expect(dispatcher.calls[0]?.input).toMatchObject({ imageTag: "google_apis_playstore" }); - - const { dispatcher: dispatcher2, tracker: tracker2 } = buildTracker(); - await createTracked(tracker2, dispatcher2); - expect(dispatcher2.calls[0]?.input).not.toHaveProperty("imageTag"); - }); -}); - -describe("LeaseRequestTracker.submit with a physical request", () => { - it("passes physical through onto the dispatch input, and omits it when the body names none", async () => { - const { dispatcher, tracker } = buildTracker(); - await createTracked(tracker, dispatcher, { ...body, physical: true }); - expect(dispatcher.calls[0]?.input).toMatchObject({ physical: true }); - - const { dispatcher: dispatcher2, tracker: tracker2 } = buildTracker(); - await createTracked(tracker2, dispatcher2); - expect(Object.keys(dispatcher2.calls[0]?.input ?? {})).not.toContain("physical"); - }); -}); - describe("LeaseRequestTracker.waitForChange abort", () => { it("finishes immediately when the caller's signal aborts", async () => { const { dispatcher, tracker } = buildTracker(); diff --git a/src/leasing/create-leasing.test.ts b/src/leasing/create-leasing.test.ts index 81cb1f8ed..64d359078 100644 --- a/src/leasing/create-leasing.test.ts +++ b/src/leasing/create-leasing.test.ts @@ -559,43 +559,6 @@ describe("createLeasing", () => { expect(harness.driver.calls.map((call) => call.operation)).toContain("destroy"); }); - it("A purge failure logs nothing, because device.purge-failed carries the error.", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); - driver.failOn("reclaim", 1, new DriverCrashError("purge exploded")); - const sink = new MemoryLogSink(); - const harness = await createHarness({ - driver, - logger: new JsonLinesLogger({ clock, level: "debug", sink }), - }); - const first = await harness.engine.request(request, { - ownerId: "first", - requesterId: "first", - }); - - await harness.engine.release(first.lease.id, "explicit"); - await harness.engine.settle(); - - expect( - harness.bus.replay().filter((event) => event.event === "device.purge-failed"), - ).toMatchObject([ - { - payload: { - deviceId: first.device.id, - error: "DriverCrashError: purge exploded", - leaseId: first.lease.id, - }, - }, - ]); - // At `debug`, so a line at any level would be caught: nothing names the device or the error. - expect( - sink.records.filter((record) => { - const line = JSON.stringify(record); - return line.includes("purge exploded") || line.includes(first.device.id); - }), - ).toEqual([]); - }); - it("quarantines a release-time purge failure instead of keeping the device eligible", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); @@ -1213,21 +1176,6 @@ describe("createLeasing", () => { expect(driver.calls.filter((call) => call.operation === "makeReady")).toHaveLength(2); }); - it("rejects a no-wait request at capacity with a typed error", async () => { - const harness = await createHarness(); - await harness.engine.request(request, { - ownerId: "agent-1", - requesterId: "agent-1", - }); - - // A no-wait request that queued instead would leave an await hanging; this names it. - const outcome = await settledOrPending( - harness.engine.request(request, { noWait: true, ownerId: "agent-2", requesterId: "agent-2" }), - ); - - expect(outcome).toBeInstanceOf(NoCapacityError); - }); - it("rejects a timed-out queue entry and skips it on a later release", async () => { const harness = await createHarness(); const first = await harness.engine.request(request, { @@ -1322,27 +1270,6 @@ describe("createLeasing", () => { }); }); - it("enforces one active request or lease per requester, then permits another after release", async () => { - const harness = await createHarness(); - const first = await harness.engine.request(request, { - ownerId: "agent-1", - requesterId: "agent-1", - }); - - await expect( - harness.engine.request(request, { ownerId: "agent-1", requesterId: "agent-1" }), - ).rejects.toMatchObject({ - existingLeaseId: first.lease.id, - message: expect.stringContaining(first.lease.id), - name: "RequesterAlreadyLeasedError", - }); - await harness.engine.release(first.lease.id, "explicit"); - await harness.engine.settle(); - await expect( - harness.engine.request(request, { ownerId: "agent-1", requesterId: "agent-1" }), - ).resolves.toMatchObject({ lease: { ownerId: "agent-1", requesterId: "agent-1" } }); - }); - it("retries after a provision failure without leaking capacity", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); @@ -3967,7 +3894,7 @@ describe("createLeasing: a requester may hold up to lease.maxPerRequester leases const waitingMessage = "Requester agent-1 already has a waiting request; wait for it to be granted or cancel it before requesting another device"; - it("with no lease.maxPerRequester, a requester holding a lease is refused with today's message, naming that lease", async () => { + it("with no lease.maxPerRequester, a requester holding a lease is refused with today's message, naming that lease, and is granted another once it releases it", async () => { const harness = await createHarness({ limits: roomy }); const first = await harness.engine.request(request, asking("agent-1")); @@ -3980,6 +3907,12 @@ describe("createLeasing: a requester may hold up to lease.maxPerRequester leases message: `Requester agent-1 already holds lease ${first.lease.id}; release it (\`simlock release ${first.lease.id}\`) before requesting another device`, name: "RequesterAlreadyLeasedError", }); + + await harness.engine.release(first.lease.id, "explicit"); + await harness.engine.settle(); + await expect(harness.engine.request(request, asking("agent-1"))).resolves.toMatchObject({ + lease: { ownerId: "agent-1", requesterId: "agent-1" }, + }); }); it("with no lease.maxPerRequester, a requester with a waiting request is refused with today's message", async () => { diff --git a/src/leasing/lease-acquisition-coordinator.test.ts b/src/leasing/lease-acquisition-coordinator.test.ts index bb0920e2f..f3ae92426 100644 --- a/src/leasing/lease-acquisition-coordinator.test.ts +++ b/src/leasing/lease-acquisition-coordinator.test.ts @@ -744,9 +744,9 @@ describe("LeaseAcquisitionCoordinator: download progress", () => { describe("LeaseAcquisitionCoordinator", () => { it("rejects a second request from a requester whose first is still pending, under no key or a new idempotency key, with lease.rejected already-leased", async () => { - // The one-lease-or-pending-request-per-requester rule is enforced here, inside the admission + // why: the one-lease-or-pending-request-per-requester rule is enforced here, inside the admission // decision, and nowhere below it: the queue keeps no check of its own. A requester holding a - // lease is createLeasing's "enforces one active request or lease per requester" case. + // lease is createLeasing's "with no lease.maxPerRequester, a requester holding a lease is refused" case. const harness = await createHarness({ maxDevices: 1, maxRunning: 1 }); await harness.coordinator.request(request, { ownerId: "holder", requesterId: "holder" }); const pending = harness.coordinator.request(request, { @@ -3028,18 +3028,6 @@ describe("LeaseAcquisitionCoordinator: class requests", () => { await expect(pending).rejects.toMatchObject({ name: "UnknownModelError" }); }); - it("fails a class request with UnknownModelError when the catalog reader answers no entry for the platform", async () => { - const harness = await createHarness({ - catalogReader: { listCatalog: async () => [] }, - drivers: [iosDriver()], - preferences: iosPreferences, - }); - - await expect(harness.coordinator.request(phone, owner("agent"))).rejects.toMatchObject({ - name: "UnknownModelError", - }); - }); - it.each([ ["names none", undefined, "default"], ["names a version", "18.4", "18.4"], diff --git a/src/leasing/lease-end-participants.test.ts b/src/leasing/lease-end-participants.test.ts index 497de4b7c..9878cb72e 100644 --- a/src/leasing/lease-end-participants.test.ts +++ b/src/leasing/lease-end-participants.test.ts @@ -871,22 +871,6 @@ describe("lease-end participants (#469)", () => { expect(participant.calls.map((call) => call.abortedAtCall)).toEqual([true, true]); }); - it("advancing the clock past lease.endWaitMs after a nuke with leased devices logs no ceiling warning", async () => { - const { grant, harness, participant } = await (async () => { - const participant = new TestParticipant(); - const harness = await startEngine({ participants: [participant] }); - const grant = await harness.engine.request(request, asking("agent")); - await harness.engine.nuke(false); - return { grant, harness, participant }; - })(); - expect(participant.calls).toHaveLength(1); - - harness.clock.advance(END_WAIT_MS + 1); - await flush(); - - expect(warningsFor(harness, grant.lease.id)).toEqual([]); - }); - it("after nuke ends, a release waits for its participant again", async () => { const participant = new TestParticipant(); const harness = await startEngine({ participants: [participant] }); diff --git a/src/leasing/lease-lifecycle.test.ts b/src/leasing/lease-lifecycle.test.ts index ea9d0ad82..be4974449 100644 --- a/src/leasing/lease-lifecycle.test.ts +++ b/src/leasing/lease-lifecycle.test.ts @@ -99,21 +99,6 @@ describe("LeaseLifecycle", () => { }, ); - it("grants a lease at the width the request asked for, and stores that instead", async () => { - const harness = await createHarness(); - const grant = await harness.lifecycle.grant({ - environment: {}, - timing: noTiming, - requestId: "req_1", - source: "warm", - deviceId: harness.device.id, - requesterId: "agent", - ownerId: "agent", - ttlMs: 50, - }); - expect(grant.lease).toMatchObject({ ttlMs: 50, ttlDeadline: 1_050 }); - }); - it("keeps re-applying a width a previous renew set, not the grant-time one", async () => { const harness = await createHarness(); const grant = await harness.lifecycle.grant({ diff --git a/src/mcp/main.test.ts b/src/mcp/main.test.ts index 513b253ee..e1d0eeba6 100644 --- a/src/mcp/main.test.ts +++ b/src/mcp/main.test.ts @@ -25,17 +25,20 @@ const { connectToRunningDaemon, connectWithAutoLaunch } = vi.hoisted(() => ({ vi.mock("./connect.js", () => ({ connectToRunningDaemon, connectWithAutoLaunch })); describe("MCP stdio lifecycle", () => { - it.each(["transport", "SIGINT", "SIGTERM"])("closes once on %s", async (cause) => { + it.each(["transport", "SIGINT", "SIGTERM", "stdin EOF"])("closes once on %s", async (cause) => { const transport = new FakeTransport(); const server = new FakeServer(); const signals = new FakeSignals(); + const stdin = new FakeStdin(); const runner = await startMcpStdio({ createServer: () => server as unknown as McpServer, createTransport: () => transport, signals, + stdin, }); if (cause === "transport") transport.onclose?.(); + else if (cause === "stdin EOF") stdin.end(); else signals.emit(cause); await runner.finished; await runner.shutdown(); @@ -43,6 +46,7 @@ describe("MCP stdio lifecycle", () => { expect(server.closeCalls).toBe(1); expect(transport.closeCalls).toBe(1); expect(signals.listeners.size).toBe(0); + expect(stdin.listener).toBeUndefined(); }); // Regression for a real reentrancy bug: the SDK's transport.close() can invoke @@ -257,12 +261,6 @@ describe("MCP stdio lifecycle", () => { await runner.shutdown(); }); - it("sources the connection principal as claude-code: from CLAUDE_CODE_SESSION_ID when neither requesterId nor SIMLOCK_AGENT_ID is given", async () => { - await expect(principalFor({ env: { CLAUDE_CODE_SESSION_ID: "abc" } })).resolves.toBe( - "claude-code:abc", - ); - }); - it("falls back to mcp: when no requesterId, SIMLOCK_AGENT_ID or session id is given", async () => { await expect(principalFor({ env: {} })).resolves.toBe(`mcp:${process.pid}`); }); @@ -294,23 +292,6 @@ describe("MCP stdio lifecycle", () => { }, ); - it("closes once when stdin reaches EOF", async () => { - const transport = new FakeTransport(); - const server = new FakeServer(); - const stdin = new FakeStdin(); - const runner = await startMcpStdio({ - createServer: () => server as unknown as McpServer, - createTransport: () => transport, - stdin, - }); - - stdin.end(); - await runner.finished; - expect(server.closeCalls).toBe(1); - expect(transport.closeCalls).toBe(1); - expect(stdin.listener).toBeUndefined(); - }); - it("finishes when the transport closes during server connection", async () => { const transport = new FakeTransport(); const server = new FakeServer(undefined, () => transport.onclose?.()); diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 0f9b1c84b..4e7a9561c 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -146,40 +146,17 @@ describe("MCP server (smoke)", () => { } }); - it("the lease tool's input schema in tools/list has no fleetRequestId", async () => { + it("the lease tool's input schema in tools/list lists noWait and physical, and has no fleetRequestId and no requires", async () => { const { mcpClient, close } = await connectedServer(new FakeSimlockClient()); try { const tools = await mcpClient.request({ method: "tools/list" }, ListToolsResultSchema); const leaseTool = tools.tools.find((tool) => tool.name === "lease_simulator"); + const properties = Object.keys(leaseTool?.inputSchema.properties ?? {}); - expect(Object.keys(leaseTool?.inputSchema.properties ?? {})).toContain("noWait"); - expect(Object.keys(leaseTool?.inputSchema.properties ?? {})).not.toContain("fleetRequestId"); - } finally { - await close(); - } - }); - - it("the lease tool's input schema in tools/list has no requires", async () => { - const { mcpClient, close } = await connectedServer(new FakeSimlockClient()); - try { - const tools = await mcpClient.request({ method: "tools/list" }, ListToolsResultSchema); - const leaseTool = tools.tools.find((tool) => tool.name === "lease_simulator"); - - expect(Object.keys(leaseTool?.inputSchema.properties ?? {})).toContain("noWait"); - expect(Object.keys(leaseTool?.inputSchema.properties ?? {})).not.toContain("requires"); - } finally { - await close(); - } - }); - - it("the lease tool's input schema in tools/list lists physical", async () => { - const { mcpClient, close } = await connectedServer(new FakeSimlockClient()); - try { - const tools = await mcpClient.request({ method: "tools/list" }, ListToolsResultSchema); - const leaseTool = tools.tools.find((tool) => tool.name === "lease_simulator"); - - expect(Object.keys(leaseTool?.inputSchema.properties ?? {})).toContain("noWait"); - expect(Object.keys(leaseTool?.inputSchema.properties ?? {})).toContain("physical"); + expect(properties).toContain("noWait"); + expect(properties).not.toContain("fleetRequestId"); + expect(properties).not.toContain("requires"); + expect(properties).toContain("physical"); } finally { await close(); } diff --git a/src/mcp/session.test.ts b/src/mcp/session.test.ts index 12b837b4e..3e891e5b3 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -59,21 +59,6 @@ describe("McpSession", () => { ]); }); - it("adds released: true to a successful release without otherwise reshaping the result", async () => { - const client = new FakeSimlockClient(); - client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); - const session = new McpSession({ - clock: new FakeClock(), - connect: async () => client, - connectForRenew: async () => client, - }); - - await expect(session.release({ leaseId: "lease-1" })).resolves.toEqual({ - leaseId: "lease-1", - released: true, - }); - }); - it("forwards list_devices straight to getCatalog", async () => { const client = new FakeSimlockClient(); client.getCatalogImpl = () => Promise.resolve({ platforms: [] }); diff --git a/src/merge-pr.test.ts b/src/merge-pr.test.ts index 64bdf5f70..73e546c0a 100644 --- a/src/merge-pr.test.ts +++ b/src/merge-pr.test.ts @@ -376,29 +376,30 @@ describe("merge-pr.sh re-run of red CI", { timeout: 20_000 }, () => { expect(result.status).toBe(0); }); - it("re-runs a job GitHub cancelled, and merges when the re-run passes", () => { - const result = gate({ runs: [run("cancelled")], runsAfterRerun: [run("success")] }); - expect(result.reruns).toBe(1); - expect(result.merged).toBe(true); - }); - - it("re-runs a job GitHub cancelled, though the Quality check that needs it failed, and merges when the re-run passes", () => { - const result = gate({ + it.each([ + { + name: "a job", + runs: [run("cancelled")], + runsAfterRerun: [run("success")], + }, + { + name: "a job, though the Quality check that needs it failed,", runs: [run("cancelled", "E2E (2/3)"), run("failure")], runsAfterRerun: [run("success", "E2E (2/3)"), run("success")], - }); - expect(result.reruns).toBe(1); - expect(result.merged).toBe(true); - }); - - it("re-runs a Quality check GitHub cancelled while every job it needs passed, and merges when the re-run passes", () => { - const result = gate({ + }, + { + name: "a Quality check, while every job it needs passed,", runs: [run("success", "E2E (2/3)"), run("cancelled")], runsAfterRerun: [run("success", "E2E (2/3)"), run("success")], - }); - expect(result.reruns).toBe(1); - expect(result.merged).toBe(true); - }); + }, + ])( + "re-runs $name GitHub cancelled, and merges when the re-run passes", + ({ runs, runsAfterRerun }) => { + const result = gate({ runs, runsAfterRerun }); + expect(result.reruns).toBe(1); + expect(result.merged).toBe(true); + }, + ); it("does not count a pull request in the flaky-test list as a flaky-test issue", () => { const result = gate({ diff --git a/src/ports/host-load.test.ts b/src/ports/host-load.test.ts index c73a1f94e..d29bed8a5 100644 --- a/src/ports/host-load.test.ts +++ b/src/ports/host-load.test.ts @@ -376,17 +376,17 @@ describe("LinuxHostLoadProbe under cgroup v2 limits", () => { expect(counters.cpu).toStrictEqual(LIMITED_TWO_CORES); }); - it("reports a fractional quota as fractional cores", async () => { - const counters = await readCgroup("/x", { x: { cpuMax: "1000 100000\n", ...USAGE } }); - - expect(counters.cpu).toMatchObject({ cores: 0.01, limited: true, totalTime: 100_000 }); - }); - - it("reports a quota of 1000 over a period of 1000000 as 0.001 cores, limited", async () => { - const counters = await readCgroup("/x", { x: { cpuMax: "1000 1000000\n", ...USAGE } }); + it.each([ + ["1000 100000", 0.01, 100_000], + ["1000 1000000", 0.001, 10_000], + ] as const)( + "reports a quota of %s as fractional cores, limited", + async (cpuMax, cores, totalTime) => { + const counters = await readCgroup("/x", { x: { cpuMax: `${cpuMax}\n`, ...USAGE } }); - expect(counters.cpu).toMatchObject({ cores: 0.001, limited: true }); - }); + expect(counters.cpu).toMatchObject({ cores, limited: true, totalTime }); + }, + ); it("uses /sys/fs/cgroup itself for a 0::/ line", async () => { const counters = await readCgroup("/", { @@ -630,6 +630,7 @@ describe("LinuxHostLoadProbe under cgroup v2 limits", () => { it.each([ ["a cgroup path with files missing", "0::/user.slice/x\n"], ["v1 lines only", "12:cpu,cpuacct:/docker/abc\n1:name=systemd:/docker/abc\n"], + ["unreadable", undefined], ])("reports the machine's figures when /proc/self/cgroup is %s", async (_why, line) => { const files = folderFiles("docker/abc", { cpuMax: "200000 100000\n", @@ -645,17 +646,6 @@ describe("LinuxHostLoadProbe under cgroup v2 limits", () => { expect(counters.memory).toStrictEqual(MACHINE_MEMORY); }); - it("reports the machine's figures when /proc/self/cgroup cannot be read", async () => { - const files = folderFiles("docker/abc", { cpuMax: "200000 100000\n", ...USAGE }); - const accepted = await cgroupFilesystem("0::/docker/abc\n", files); - expect((await cgroupProbe(accepted).read()).cpu?.limited).toBe(true); - - const counters = await cgroupProbe(await cgroupFilesystem(undefined, files)).read(); - - expect(counters.cpu).toMatchObject({ cores: 64, limited: false }); - expect(counters.memory).toStrictEqual(MACHINE_MEMORY); - }); - it("reports the machine's figures when /proc/self/cgroup has only cgroup v1 lines and no 0:: line", async () => { const files = folderFiles("docker/abc", { cpuMax: "200000 100000\n", @@ -724,19 +714,6 @@ describe("NodeFilesystem.diskSpace", () => { }); }); -describe.skipIf(process.platform !== "linux")("production Linux probe on this machine", () => { - it("returns CPU counters, memory and disk from the real /proc and /sys", async () => { - const probe = productionHostLoadProbe({ platform: "linux", dataDirectory: tmpdir() }); - - const counters = await probe.read(); - - expect(counters.cpu?.totalTime).toBeGreaterThan(0); - expect(counters.cpu?.cores).toBeGreaterThan(0); - expect(counters.memory?.totalBytes).toBeGreaterThan(0); - expect(counters.disk?.totalBytes).toBeGreaterThan(0); - }); -}); - describe("productionHostLoadProbe", () => { afterEach(() => { vi.restoreAllMocks(); diff --git a/src/ports/logger.test.ts b/src/ports/logger.test.ts index 58534ae69..fdfccaa1c 100644 --- a/src/ports/logger.test.ts +++ b/src/ports/logger.test.ts @@ -72,15 +72,6 @@ describe("JsonLinesLogger", () => { expect(sink.records.map((record) => record.message)).toEqual(["kept"]); }); - it("scopes child loggers by dot-joining the module name", () => { - const sink = new MemoryLogSink(); - const logger = new JsonLinesLogger({ clock: new FakeClock(), module: "daemon", sink }); - - logger.child("connection-host").info("Claimed socket"); - - expect(sink.records[0]?.module).toBe("daemon.connection-host"); - }); - it("nests grandchild module scopes", () => { const sink = new MemoryLogSink(); const logger = new JsonLinesLogger({ clock: new FakeClock(), module: "daemon", sink }); diff --git a/src/ports/parent-watch.test.ts b/src/ports/parent-watch.test.ts index 0afa0c0dd..5170a265b 100644 --- a/src/ports/parent-watch.test.ts +++ b/src/ports/parent-watch.test.ts @@ -42,19 +42,6 @@ describe("FakeParentWatch", () => { expect(exitCount).toBe(0); }); - - it("fires at most once even if exit() is somehow observed twice", () => { - const watch = new FakeParentWatch(); - let exitCount = 0; - - watch.watch(4321, () => { - exitCount += 1; - }); - watch.exit(4321); - watch.exit(4321); - - expect(exitCount).toBe(1); - }); }); describe("NodeParentWatch", () => { diff --git a/src/ports/paths.test.ts b/src/ports/paths.test.ts index 63a854587..75bb61b27 100644 --- a/src/ports/paths.test.ts +++ b/src/ports/paths.test.ts @@ -4,7 +4,6 @@ import { describe, expect, it } from "vitest"; import { MemoryFilesystem } from "./filesystem.js"; import { - daemonDataDirectory, resolveDaemonHome, resolveDaemonSocketPath, resolveSimlockHome, @@ -85,13 +84,6 @@ describe("resolveSimlockHome", () => { }); }); -describe("daemonDataDirectory", () => { - it("puts the gateway in /gateway and the worker in ", () => { - expect(daemonDataDirectory("/home/me/.simlock", "gateway")).toBe("/home/me/.simlock/gateway"); - expect(daemonDataDirectory("/home/me/.simlock", "worker")).toBe("/home/me/.simlock"); - }); -}); - describe("resolveDaemonHome", () => { const root = "/home/me/.simlock"; diff --git a/src/ports/process-runner.test.ts b/src/ports/process-runner.test.ts index c6fdcc20a..86d961978 100644 --- a/src/ports/process-runner.test.ts +++ b/src/ports/process-runner.test.ts @@ -94,23 +94,6 @@ describe("ScriptedProcessRunner", () => { await expect(result).resolves.toEqual({ code: null, stderr: "", stdout: "" }); }); - - it("replays scripted output through line streams", async () => { - const runner = new ScriptedProcessRunner([ - { - match: { command: "adb", args: ["logcat"] }, - stdoutLines: ["booting", "ready"], - }, - ]); - const process = runner.spawn("adb", ["logcat"]); - const lines: string[] = []; - - for await (const line of process.stdout) { - lines.push(line); - } - - expect(lines).toEqual(["booting", "ready"]); - }); }); describe("ScriptedProcessRunner: spawnStreaming", () => { @@ -619,14 +602,6 @@ describe("NodeProcessRunner", () => { expect(Date.now() - startedAt).toBeLessThan(3_000); }, 15_000); - it("keeps a 10 s SIGTERM-to-SIGKILL grace, a 5 s exit deferral cap and a 1 s exit grace when no options are given", () => { - const runner = new NodeProcessRunner(); - - expect(runner.sigkillGraceMs).toBe(10_000); - expect(runner.exitDeferralCapMs).toBe(5_000); - expect(runner.exitGraceMs).toBe(1_000); - }); - it("settles wait() when a detached grandchild keeps the stdio pipe open after the process exits", async () => { const runner = new NodeProcessRunner({ exitGraceMs: 100 }); // The child forks its own detached grandchild that inherits our pipe's write diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index 174bad700..f7c195a01 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import { connectSimlockAdmin } from "../admin/index.js"; import { connectSimlock } from "../client/index.js"; +import type { SimlockAdminClient } from "./client.js"; import type { LeaseGrant } from "./types.js"; import { completeHello, ScriptedConnection } from "./test-support.js"; @@ -181,67 +182,61 @@ describe("connectSimlock: handshake", () => { expect(connection.sent).toHaveLength(before); }); - it("lists components from an agent client with component.list, sending the platform and returning the daemon's answer", async () => { - const connection = new ScriptedConnection(); - const connectPromise = connectSimlock({ connection }); - await flushMicrotasks(); - completeHello(connection); - const client = await connectPromise; - const answer = { - components: [ - { - devices: 0, - foreignDevices: 2, - installedBySimlock: false, - platform: "ios", - sizeBytes: 9_100_000_000, - variant: "23A343", - version: "26.0", - }, - ], - }; - - const callPromise = client.listComponents({ platform: "ios" }); - await flushMicrotasks(); - const call = connection.lastSentOf("component.list")!; - expect(call.payload).toEqual({ platform: "ios" }); - connection.reply(call.id, answer); - - await expect(callPromise).resolves.toEqual(answer); - }); - - it("identity() sends identity.get and returns its output", async () => { - const connection = new ScriptedConnection(); - const connectPromise = connectSimlock({ connection }); - await flushMicrotasks(); - completeHello(connection); - const client = await connectPromise; - const answer = { name: "ci-runner", principal: "tok_9f2c", role: "agent", via: "token" }; - - const callPromise = client.identity(); - await flushMicrotasks(); - const call = connection.lastSentOf("identity.get")!; - expect(call.payload).toEqual({}); - connection.reply(call.id, answer); - - await expect(callPromise).resolves.toEqual(answer); - }); - - it("removes a component from an admin client with component.remove, sending the input and returning the daemon's answer", async () => { + it.each([ + { + name: "component.list from an agent client", + admin: false, + operation: "component.list", + payload: { platform: "ios" }, + answer: { + components: [ + { + devices: 0, + foreignDevices: 2, + installedBySimlock: false, + platform: "ios", + sizeBytes: 9_100_000_000, + variant: "23A343", + version: "26.0", + }, + ], + }, + call: (client: SimlockAdminClient) => client.listComponents({ platform: "ios" }), + }, + { + name: "identity.get from an agent client", + admin: false, + operation: "identity.get", + payload: {}, + answer: { name: "ci-runner", principal: "tok_9f2c", role: "agent", via: "token" }, + call: (client: SimlockAdminClient) => client.identity(), + }, + { + name: "component.remove from an admin client", + admin: true, + operation: "component.remove", + payload: { dryRun: true, platform: "ios", version: "26.4" }, + answer: { outcome: "would-remove", platform: "ios", sizeBytes: 7, version: "26.4" }, + call: (client: SimlockAdminClient) => + client.removeComponent({ dryRun: true, platform: "ios", version: "26.4" }), + }, + ])("sends $name with its input and returns the daemon's answer", async (row) => { const connection = new ScriptedConnection(); - const connectPromise = connectSimlockAdmin({ connection, credential: "operator-secret" }); + const connectPromise = row.admin + ? connectSimlockAdmin({ connection, credential: "operator-secret" }) + : connectSimlock({ connection }); await flushMicrotasks(); - completeHello(connection, { role: "admin" }); - const client = await connectPromise; - const answer = { outcome: "would-remove", platform: "ios", sizeBytes: 7, version: "26.4" }; + if (row.admin) completeHello(connection, { role: "admin" }); + else completeHello(connection); + const client = (await connectPromise) as SimlockAdminClient; - const callPromise = client.removeComponent({ dryRun: true, platform: "ios", version: "26.4" }); + const callPromise = row.call(client); await flushMicrotasks(); - const call = connection.lastSentOf("component.remove")!; - expect(call.payload).toEqual({ dryRun: true, platform: "ios", version: "26.4" }); - connection.reply(call.id, answer); + const call = connection.lastSentOf(row.operation)!; + expect(call.payload).toEqual(row.payload); + connection.reply(call.id, row.answer); - await expect(callPromise).resolves.toEqual(answer); + await expect(callPromise).resolves.toEqual(row.answer); }); it("the admin client's testAlertDestination sends alerts.test and returns its output", async () => { diff --git a/src/stream/feed.test.ts b/src/stream/feed.test.ts index 8365240d1..6f461cc8b 100644 --- a/src/stream/feed.test.ts +++ b/src/stream/feed.test.ts @@ -35,17 +35,6 @@ describe("readScreenFeed", () => { expect(await outcome).toBe("answered"); }); - it("refuses a capture that paints nothing within the start bound, and closes it", async () => { - const clock = new FakeClock(); - const feed = new ScriptedFeed(); - const outcome = readScreenFeed(feed, { clock, ...BOUNDS }); - clock.advance(BOUNDS.startMs); - await expect(outcome).rejects.toThrow( - /wrote nothing for 5000ms while waiting for its first frame/u, - ); - expect(feed.closes).toBe(1); - }); - it("refuses a capture that ends before it writes a frame", async () => { const feed = new ScriptedFeed(); const outcome = readScreenFeed(feed, { clock: new FakeClock(), ...BOUNDS }); @@ -53,22 +42,6 @@ describe("readScreenFeed", () => { await expect(outcome).rejects.toThrow(/ended before it wrote a frame/u); }); - it("errors the body, and closes the capture, when it goes quiet mid-picture past the silence bound", async () => { - const clock = new FakeClock(); - const feed = new ScriptedFeed(); - feed.meta(); - const stream = await readScreenFeed(feed, { clock, ...BOUNDS }); - const reader = stream.body.getReader(); - await reader.read(); - const next = reader.read(); - await flush(); - clock.advance(BOUNDS.silenceMs); - await expect(next).rejects.toThrow( - /wrote nothing for 1000ms while waiting for the next frame/u, - ); - expect(feed.closes).toBe(1); - }); - it("keeps a picture that keeps arriving within the silence bound", async () => { const clock = new FakeClock(); const feed = new ScriptedFeed(); diff --git a/src/stream/framing.test.ts b/src/stream/framing.test.ts index 5a21f5a52..afa3e108a 100644 --- a/src/stream/framing.test.ts +++ b/src/stream/framing.test.ts @@ -31,13 +31,6 @@ describe("MetaFrameScanner", () => { expect(found.at(-1)?.bytes).toEqual(bytes); }); - it("reports the meta frame it returned as exactly the bytes that frame occupies", () => { - const bytes = metaFrame(); - const scanner = new MetaFrameScanner(); - const found = scanner.push(bytes); - expect(found?.bytes.byteLength).toBe(bytes.byteLength); - }); - it("refuses a stream that puts a video frame before the meta frame", () => { const scanner = new MetaFrameScanner(); // why: the meta frame is the one promise the envelope makes, and a decoder configured from a header diff --git a/ui/src/model/events.test.ts b/ui/src/model/events.test.ts index ecc0cdf2e..1f61b50df 100644 --- a/ui/src/model/events.test.ts +++ b/ui/src/model/events.test.ts @@ -49,24 +49,12 @@ describe("an envelope off the wire", () => { }); describe("the events the console holds", () => { - it("are listed newest first, by seq inside the same millisecond", () => { - const merged = mergeEvents([], [event("a", {}, 2), event("b", {}, 9), event("c", {}, 5)]); - - expect(merged.map((entry) => entry.seq)).toEqual([9, 5, 2]); - }); - it("show an event seen twice once, and two ids with the same seq and time both", () => { const first = event("lease.granted", {}, 1, "evt_a"); const merged = mergeEvents([first], [first, event("lease.granted", {}, 1, "evt_b")]); expect(merged.map((entry) => entry.id).sort()).toEqual(["evt_a", "evt_b"]); }); - - it("change nothing for an event already held", () => { - const held = [event("lease.granted")]; - - expect(mergeEvents(held, [event("lease.granted")])).toBe(held); - }); }); describe("the events an older page adds", () => { diff --git a/ui/src/model/workers.test.ts b/ui/src/model/workers.test.ts index 836a26890..ca0f5a5ce 100644 --- a/ui/src/model/workers.test.ts +++ b/ui/src/model/workers.test.ts @@ -14,15 +14,6 @@ const REFUSED: WarmTarget = { }; describe("the warm pool table's row identities", () => { - it("gives two refused targets of one kind two different identities, the kind and its place among them", () => { - const rows = warmPoolRows([REFUSED, REFUSED]); - - expect(rows.map((row) => row.key)).toEqual([ - "ios-iPhone 17-27.0-full#0", - "ios-iPhone 17-27.0-full#1", - ]); - }); - it("keeps the identity of a row when a row of another kind comes or goes", () => { const other: WarmTarget = { ...REFUSED, model: "iPhone 16" }; diff --git a/ui/src/state/inbox.test.ts b/ui/src/state/inbox.test.ts index a35816d3c..19248993f 100644 --- a/ui/src/state/inbox.test.ts +++ b/ui/src/state/inbox.test.ts @@ -28,18 +28,24 @@ describe("what the Inbox could not check", () => { expect(reads.waiting).toEqual({ data: { requests: [] }, kind: "ready" }); }); - it("names the waiting requests when that read failed after an earlier answer, and keeps the answer", () => { - const held = { requests: [] }; - const reads = inboxReadsOf( - { data: held, error: DOWN }, - { data: NO_LEASES }, - {}, - { data: NO_WORKERS }, - ); + it.each([ + ["waiting requests", "waiting"], + ["workers", "workers"], + ] as const)( + "names the %s when that read failed after an earlier answer, and keeps the answer", + (name, field) => { + const held = field === "waiting" ? { requests: [] } : NO_WORKERS; + const reads = inboxReadsOf( + field === "waiting" ? { data: { requests: [] }, error: DOWN } : { data: { requests: [] } }, + { data: NO_LEASES }, + {}, + field === "workers" ? { data: NO_WORKERS, error: DOWN } : { data: NO_WORKERS }, + ); - expect(reads.couldNotCheck).toEqual(["waiting requests"]); - expect(reads.waiting).toEqual({ data: held, kind: "ready", refusal: "down" }); - }); + expect(reads.couldNotCheck).toEqual([name]); + expect(reads[field]).toEqual({ data: held, kind: "ready", refusal: "down" }); + }, + ); it("names the leases when that read failed, before any answer and after one", () => { expect( @@ -86,16 +92,4 @@ describe("what the Inbox could not check", () => { expect(reads.leases).toBeUndefined(); }); - - it("names the workers when that read failed after an earlier answer, and keeps the answer", () => { - const reads = inboxReadsOf( - { data: { requests: [] } }, - { data: NO_LEASES }, - {}, - { data: NO_WORKERS, error: DOWN }, - ); - - expect(reads.couldNotCheck).toEqual(["workers"]); - expect(reads.workers).toEqual({ data: NO_WORKERS, kind: "ready", refusal: "down" }); - }); });