diff --git a/e2e/slow-ios-window.test.ts b/e2e/slow-ios-window.test.ts index 4d57c48a5..583af4771 100644 --- a/e2e/slow-ios-window.test.ts +++ b/e2e/slow-ios-window.test.ts @@ -258,5 +258,56 @@ describe.skipIf(process.platform !== "darwin")( } }, ); + it( + "a leased simulator on Xcode's set takes the lease's label as its name", + { timeout: 600_000 }, + async () => { + const { env } = await withHttpDaemon((httpPort) => ({ + configOverrides: { + drivers: { ios: { deviceSet: "default" } }, + http: { enabled: true, host: "127.0.0.1", port: httpPort }, + ios: { simulator: { headless: false } }, + }, + driver: "real", + })); + const nameOf = async (udid: string): Promise => { + const listed = await execFileAsync("xcrun", ["simctl", "list", "devices", "-j"]); + const runtimes = ( + JSON.parse(listed.stdout) as { + devices: Record; + } + ).devices; + return Object.values(runtimes) + .flat() + .find((device) => device.udid === udid)?.name; + }; + try { + const labelled = await env.cli( + [ + "lease", + "--platform", + "ios", + "--agent-id", + "ios-label", + "--label", + "feature-x", + "--detach", + ], + { timeout: DEVICE_READY_MS }, + ); + expect(labelled.code, `lease failed: ${labelled.stdout} ${labelled.stderr}`).toBe(0); + const grant = labelled.json as { + device: { driverDeviceId: string }; + lease: { id: string }; + }; + expect(await nameOf(grant.device.driverDeviceId)).toBe("feature-x"); + await env.cli(["release", grant.lease.id]).catch(() => undefined); + } finally { + await env + .cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }) + .catch(() => undefined); + } + }, + ); }, ); diff --git a/e2e/warm-pool-reserve.test.ts b/e2e/warm-pool-reserve.test.ts index 8dab9c83e..e06a2cd76 100644 --- a/e2e/warm-pool-reserve.test.ts +++ b/e2e/warm-pool-reserve.test.ts @@ -112,8 +112,9 @@ describe("warm pool reserve and requests that wait for a booting device", () => driverScript: { ios: IOS }, }); // why: the first lease's kind is learned, so the pool boots a spare while it is held (ADR 0069); - // the slow boot is set first so that spare is still booting when the five leases arrive. - await env.driverScript.merge({ ios: { latencyMs: { makeReady: 4_000 } } }); + // the slow boot is set first so that spare is still booting when the five leases arrive, with + // room for a slow runner to reach the check before that boot ends and frees a slot. + await env.driverScript.merge({ ios: { latencyMs: { makeReady: 10_000 } } }); const warm = await lease(env, "warm", ["--timeout", "60s"]); await waitFor(async () => (await makeReadyCalls(env)) === 2, { label: "the warm pool's boot of the spare for the held lease has started", @@ -130,6 +131,8 @@ describe("warm pool reserve and requests that wait for a booting device", () => await new Promise((resolve) => setTimeout(resolve, 1_500)); expect(await makeReadyCalls(env)).toBe(4); + // why: the check is made; later boots run at full speed. + await env.driverScript.merge({ ios: { latencyMs: { makeReady: 0 } } }); const granted = await Promise.all(grants); await untilQuiet(env); @@ -137,7 +140,7 @@ describe("warm pool reserve and requests that wait for a booting device", () => // why: five held copies leave one spare ready, the seventh boot (ADR 0069). expect(await makeReadyCalls(env)).toBe(7); expect((await deviceStates(env)).filter((state) => state === "leased")).toHaveLength(5); - // why: the boots are still slow, so the spare may still be booting when the pool goes quiet. + // why: the spare may still be booting when the pool goes quiet. await waitFor( async () => (await deviceStates(env)).filter((state) => state === "ready").length === 1, { label: "the one spare is ready" }, diff --git a/src/core/device-provisioner.ts b/src/core/device-provisioner.ts index b79b153e3..d17ad4422 100644 --- a/src/core/device-provisioner.ts +++ b/src/core/device-provisioner.ts @@ -51,6 +51,8 @@ export interface ProvisionDeviceOptions { readonly claim?: { readonly kind: "boot"; readonly owner?: string }; /** why: the categories a slim lease keeps running, handed to the driver at the boot before the grant (ADR 0066 ยง2). */ readonly except?: readonly string[]; + /** why: the lease's label, handed to the driver at the boot before the grant so the device carries it from its first boot. */ + readonly label?: string; readonly onProgress?: (progress: ProvisionProgress) => void; readonly reservation: CapacityReservation; } @@ -174,6 +176,7 @@ export class DeviceProvisioner { device, bootClaim, options.except, + options.label, ); if (ready === undefined) throw new Error(`Registered device could not be made ready: ${device.id}`); diff --git a/src/core/driver.ts b/src/core/driver.ts index 15e596a10..18e6dc005 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -323,6 +323,8 @@ export interface Driver { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode; readonly except?: readonly string[]; + /** why: the lease's label, given on a `prepare` boot made for a lease; a driver that can name its device by it does. */ + readonly label?: string; }, ): Promise; reclaim( diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index f8a47d055..7b98be715 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -521,6 +521,7 @@ export class FakeDriver implements Driver { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode; readonly except?: readonly string[]; + readonly label?: string; }, ): Promise { await this.#beforeCall("makeReady", device, options); diff --git a/src/core/managed-device-lifecycle.ts b/src/core/managed-device-lifecycle.ts index 6c4870522..1b608835c 100644 --- a/src/core/managed-device-lifecycle.ts +++ b/src/core/managed-device-lifecycle.ts @@ -76,8 +76,9 @@ export class ManagedDeviceLifecycle { target: VirtualDevice, claim: DeviceOperationClaim, except?: readonly string[], + label?: string, ): Promise { - return this.#makeReadyForLease(target, "shutdown", claim, except); + return this.#makeReadyForLease(target, "shutdown", claim, except, label); } /** @@ -107,6 +108,7 @@ export class ManagedDeviceLifecycle { target: VirtualDevice, claim: DeviceOperationClaim, except: readonly string[], + label?: string, ): Promise { const claimed = await this.#claim(target, ["ready"], "boot", claim); if (claimed === undefined) return undefined; @@ -116,6 +118,7 @@ export class ManagedDeviceLifecycle { await driver.shutdown(toDriverDevice(claimed.device)); ready = await driver.makeReady(toDriverDevice(claimed.device), { except, + ...(label === undefined ? {} : { label }), mode: specMode(claimed.device.spec), purpose: "prepare", }); @@ -161,8 +164,9 @@ export class ManagedDeviceLifecycle { target: VirtualDevice, claim?: DeviceOperationClaim, except?: readonly string[], + label?: string, ): Promise { - return this.#makeReadyForLease(target, "provisioning", claim, except); + return this.#makeReadyForLease(target, "provisioning", claim, except, label); } async shutdown( @@ -303,6 +307,7 @@ export class ManagedDeviceLifecycle { expectedState: "provisioning" | "shutdown", existingClaim?: DeviceOperationClaim, except?: readonly string[], + label?: string, ): Promise { const claimed = await this.#claim(target, [expectedState], "boot", existingClaim); if (claimed === undefined) return undefined; @@ -315,6 +320,7 @@ export class ManagedDeviceLifecycle { mode: specMode(claimed.device.spec), purpose: "prepare", ...(except === undefined ? {} : { except }), + ...(label === undefined ? {} : { label }), }); } catch (error: unknown) { await this.#release(claimed); diff --git a/src/drivers/ios/AGENTS.md b/src/drivers/ios/AGENTS.md index 3da73ff3a..56475f312 100644 --- a/src/drivers/ios/AGENTS.md +++ b/src/drivers/ios/AGENTS.md @@ -16,7 +16,7 @@ Resolve and boot: - A slim spec is returned only for a slim request the driver will slim. The registry alone records a device's mode. - `RuntimeMissingError` is only for what a download can fix: an OS outside the device type's range, an installed runtime not paired with the type, and anything below iOS 16 are refused instead. -- A boot is `simctl boot`, `bootstatus -b`, then `listapps` until it succeeds, on one deadline: bootstatus can finish before the installer is ready. +- A boot is `simctl rename` (prepare only: label, else stored name; failure logged), `simctl boot`, `bootstatus -b`, then `listapps` until it succeeds, on one deadline: bootstatus can finish before the installer is ready. - Slim (ADR 0060), on `prepare` of a slim spec only: the managed labels are merged into the simulator's `disabled.plist` before the boot (other entries kept; a failed write is logged, the boot goes on), and `launchctl print-disabled system` is read back after it. A label not as written is `full`; a failed readback is `slim`; both call `onSlimSkipped`, logged only. All as written and the write ok: `slim`, and `onSlimmed` is `device.slimmed`. Nothing written off and no kept category: `full`, no readback. - Named services (ADR 0083): `exclude` beats `include` beats a category; `simlock-managed.json` records the names, so one dropped from both is written back on. A baseline saved before it keeps a dropped name off; `include` it. - Slim `except` (ADR 0066): an excepted category's labels are written `false`; an unknown name is `BAD_REQUEST`; a kept label not read back throws `KeptCategoriesError`. diff --git a/src/drivers/ios/boot-courtesies.test.ts b/src/drivers/ios/boot-courtesies.test.ts index 15ba96edc..c7903ec3b 100644 --- a/src/drivers/ios/boot-courtesies.test.ts +++ b/src/drivers/ios/boot-courtesies.test.ts @@ -81,6 +81,7 @@ describe("IosSimctlDriver simulator window", () => { const xcrun = (...args: string[]) => ({ command: "xcrun", args: ["simctl", ...args] }); const open = (...args: string[]) => ({ command: "open", args: ["-g", ...args] }); const clipboard = deviceHubEdit(`Set :DevicePreferences:${udid}:pasteboardSyncEnabled false`); + const renameCall = xcrun("rename", udid, driverData.name); const bootCalls = [xcrun("boot", udid), xcrun("bootstatus", udid, "-b"), xcrun("listapps", udid)]; const deviceHub = open( "-b", @@ -131,8 +132,9 @@ describe("IosSimctlDriver simulator window", () => { ])( "shows a simulator in a window without taking focus when ios.simulator.headless is false: $name", async (c) => { + const renamed = (c.options?.purpose ?? "prepare") === "prepare" ? [renameCall] : []; const runner = new ScriptedProcessRunner( - [...clipboard, ...c.expected].map((match) => ({ + [...renamed, ...clipboard, ...c.expected].map((match) => ({ match, ...(match === deviceHub && c.deviceHubResult !== undefined ? { result: c.deviceHubResult } @@ -162,6 +164,7 @@ describe("IosSimctlDriver simulator window", () => { ), ).resolves.toMatchObject({ address: udid }); expect(runner.calls.map(({ command, args }) => ({ command, args }))).toEqual([ + ...renamed, ...clipboard, ...c.expected, ]); @@ -209,7 +212,7 @@ describe("IosSimctlDriver simulator window", () => { "makes the simulator ready and reports the failure when opening its window fails: $name", async (c) => { const runner = new ScriptedProcessRunner([ - ...[...clipboard, ...bootCalls].map((match) => ({ match })), + ...[renameCall, ...clipboard, ...bootCalls].map((match) => ({ match })), ...c.script, ]); const clock = new FakeClock(); @@ -234,7 +237,7 @@ describe("IosSimctlDriver simulator window", () => { ); if (c.script.some((step) => "hangs" in step)) { const state = promiseState(ready); - await waitForCalls(runner, clipboard.length + bootCalls.length + c.script.length); + await waitForCalls(runner, 1 + clipboard.length + bootCalls.length + c.script.length); clock.advance(29_999); await flushMicrotasks(); expect(state.state).toBe("pending"); diff --git a/src/drivers/ios/boot-deadline.test.ts b/src/drivers/ios/boot-deadline.test.ts index f221522e1..7b0c4daa7 100644 --- a/src/drivers/ios/boot-deadline.test.ts +++ b/src/drivers/ios/boot-deadline.test.ts @@ -71,6 +71,7 @@ describe("IosSimctlDriver boot deadline", () => { async ({ budgetMs, config, data, options }) => { const clock = new FakeClock(); const runner = new ScriptedProcessRunner([ + { match: { command: "xcrun", args: simctlArgs("rename", data.udid, driverData.name) } }, { hangs: true, match: { command: "xcrun", args: simctlArgs("boot", data.udid) } }, ]); const driver = await bootBudgetDriver(runner, clock, config); @@ -80,10 +81,10 @@ describe("IosSimctlDriver boot deadline", () => { options, ); void ready.catch(() => undefined); - await waitForCalls(runner, 1); + await waitForCalls(runner, 2); const readyState = promiseState(ready); - expect(runner.calls[0]?.options).toEqual({ timeoutMs: budgetMs }); + expect(runner.calls[1]?.options).toEqual({ timeoutMs: budgetMs }); clock.advance(budgetMs - 1); await flushMicrotasks221(); expect(readyState.state).toBe("pending"); @@ -98,6 +99,7 @@ describe("IosSimctlDriver boot deadline", () => { async ({ budgetMs, config, data, options }) => { const clock = new FakeClock(); const runner = new ScriptedProcessRunner([ + { match: { command: "xcrun", args: simctlArgs("rename", data.udid, driverData.name) } }, { match: { command: "xcrun", args: simctlArgs("boot", data.udid) }, onSpawn: () => clock.advance(100_000), @@ -115,10 +117,10 @@ describe("IosSimctlDriver boot deadline", () => { options, ); void ready.catch(() => undefined); - await waitForCalls(runner, 2); + await waitForCalls(runner, 3); const readyState = promiseState(ready); - expect(runner.calls[1]?.options).toEqual({ timeoutMs: budgetMs - 100_000 }); + expect(runner.calls[2]?.options).toEqual({ timeoutMs: budgetMs - 100_000 }); clock.advance(budgetMs - 100_000 - 1); await flushMicrotasks221(); expect(readyState.state).toBe("pending"); @@ -126,6 +128,7 @@ describe("IosSimctlDriver boot deadline", () => { clock.advance(1); expect(await settledValue(ready)).toBeInstanceOf(BootTimeoutError); expect(runner.calls.map((call) => call.args)).toEqual([ + simctlArgs("rename", data.udid, driverData.name), simctlArgs("boot", data.udid), simctlArgs("bootstatus", data.udid, "-b"), simctlArgs("shutdown", data.udid), diff --git a/src/drivers/ios/clipboard.test.ts b/src/drivers/ios/clipboard.test.ts index 529177c0b..9bd2c3122 100644 --- a/src/drivers/ios/clipboard.test.ts +++ b/src/drivers/ios/clipboard.test.ts @@ -139,6 +139,7 @@ describe("IosSimctlDriver DeviceHub clipboard", () => { const exportDomain = ["defaults", "export", "com.apple.dt.Devices", expect.any(String)]; const importDomain = ["defaults", "import", "com.apple.dt.Devices", expect.any(String)]; + const rename = ["xcrun", "simctl", "rename", udid, driverData.name]; const syncOffThenBoot = [ exportDomain, staged(`Set :DevicePreferences:${udid}:pasteboardSyncEnabled false`), @@ -158,6 +159,7 @@ describe("IosSimctlDriver DeviceHub clipboard", () => { expect(hub.domain).toEqual({ other: { pasteboardSyncEnabled: true, windowScale: 50 } }); expect(calls).toEqual([ + rename, ...syncOffThenBoot, ...syncOffThenBoot, ["xcrun", "simctl", "shutdown", udid], @@ -200,14 +202,16 @@ describe("IosSimctlDriver DeviceHub clipboard", () => { await expect(driver.makeReady(device, prepareFull)).rejects.toThrow( "Could not disable DeviceHub clipboard sync", ); - expect(calls.every((call) => call[0] === "defaults")).toBe(true); + expect(calls[0]).toEqual(rename); + expect(calls.slice(1).every((call) => call[0] === "defaults")).toBe(true); expect(hub.domain[udid]?.pasteboardSyncEnabled).toBe(true); calls.length = 0; hub.failing = ""; hub.warm = true; await driver.makeReady(device, prepareFull); - expect(calls.slice(0, 6)).toEqual([ + expect(calls.slice(0, 7)).toEqual([ + rename, ...syncOffThenBoot.slice(0, 4), ["xcrun", "simctl", "shutdown", udid], ["xcrun", "simctl", "boot", udid], diff --git a/src/drivers/ios/index-device-set.test.ts b/src/drivers/ios/index-device-set.test.ts index 243f91a42..611dcaa37 100644 --- a/src/drivers/ios/index-device-set.test.ts +++ b/src/drivers/ios/index-device-set.test.ts @@ -94,6 +94,7 @@ describe("IosSimctlDriver device set", () => { sources: true, stdout: `${driverData.udid}\n`, }, + { args: ["rename", driverData.udid, driverData.name], scoped: true }, { args: ["boot", driverData.udid], scoped: true }, { args: ["bootstatus", driverData.udid, "-b"], scoped: true }, { args: ["listapps", driverData.udid], scoped: true }, diff --git a/src/drivers/ios/index-rename.test.ts b/src/drivers/ios/index-rename.test.ts new file mode 100644 index 000000000..553a75f62 --- /dev/null +++ b/src/drivers/ios/index-rename.test.ts @@ -0,0 +1,110 @@ +import { afterEach, expect, describe, it } from "vitest"; +import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; +import { promiseState } from "../../test-support/promise-state.js"; +import { + createSlimDriver, + deviceRoot, + driverData, + flushMicrotasks221, + simctl, + simctlArgs, + waitForCalls, +} from "./test-slim.js"; +import { RecordingLogger, UNSCOPED_LEGACY_CALLS, scopedRunners } from "./test-index.js"; + +afterEach(() => { + for (const call of scopedRunners.splice(0).flatMap((runner) => runner.calls)) { + if (call.command !== "xcrun" || call.args[0] !== "simctl") continue; + if (UNSCOPED_LEGACY_CALLS.has(call.args.join(" "))) continue; + expect(call.args.slice(0, 3)).toEqual(["simctl", "--set", deviceRoot]); + } +}); + +describe("IosSimctlDriver naming a simulator at its boot", () => { + const udid = driverData.udid; + const boot = [ + simctlArgs("boot", udid), + simctlArgs("bootstatus", udid, "-b"), + simctlArgs("listapps", udid), + ]; + + it.each([ + { + name: "a label", + options: { mode: "full", purpose: "prepare", label: "feature-x" } as const, + expected: [simctlArgs("rename", udid, "feature-x"), ...boot], + }, + { + name: "no label names it back to its stored name", + options: { mode: "full", purpose: "prepare" } as const, + expected: [simctlArgs("rename", udid, driverData.name), ...boot], + }, + { + name: "a recovery boot renames nothing", + options: { mode: "full", purpose: "recover", label: "feature-x" } as const, + expected: boot, + }, + { + name: "a rename that exits non-zero", + rename: { code: 1, stderr: "Invalid device", stdout: "" }, + options: { mode: "full", purpose: "prepare", label: "feature-x" } as const, + expected: [simctlArgs("rename", udid, "feature-x"), ...boot], + warned: `could not rename ${udid} to feature-x: Invalid device`, + }, + { + name: "a rename that hangs past 5 s", + rename: "hangs" as const, + options: { mode: "full", purpose: "prepare", label: "feature-x" } as const, + expected: [simctlArgs("rename", udid, "feature-x"), ...boot], + warned: `could not rename ${udid} to feature-x: timed out after 5000ms`, + }, + ])("runs simctl rename before simctl boot on a prepare boot: $name", async (c) => { + const renames = c.expected.length > boot.length; + const runner = new ScriptedProcessRunner([ + ...(!renames + ? [] + : [ + { + match: simctl("rename", udid, c.expected[0]![5]!), + ...(c.rename === "hangs" + ? { hangs: true } + : c.rename === undefined + ? {} + : { result: c.rename }), + }, + ]), + { match: simctl("boot", udid) }, + { match: simctl("bootstatus", udid, "-b") }, + { match: simctl("listapps", udid) }, + ]); + scopedRunners.push(runner); + const clock = new FakeClock(); + const logger = new RecordingLogger(); + const driver = await createSlimDriver( + runner, + new MemoryFilesystem(), + { bootTimeoutMs: 300_000, categories: ["widgets"] }, + undefined, + undefined, + false, + clock, + logger, + ); + + const ready = driver.makeReady({ address: udid, deviceId: udid, driverData }, c.options); + if (c.rename === "hangs") { + const state = promiseState(ready); + await waitForCalls(runner, 1); + clock.advance(4_999); + await flushMicrotasks221(); + expect(state.state).toBe("pending"); + clock.advance(1); + await flushMicrotasks221(); + } + const device = await ready; + + expect(device.address).toBe(udid); + expect(runner.calls.map((call) => call.args)).toEqual(c.expected); + expect(logger.warnings).toEqual(c.warned === undefined ? [] : [c.warned]); + }); +}); diff --git a/src/drivers/ios/index-save-source-lifecycle.test.ts b/src/drivers/ios/index-save-source-lifecycle.test.ts index e442cb6e7..1af924b2d 100644 --- a/src/drivers/ios/index-save-source-lifecycle.test.ts +++ b/src/drivers/ios/index-save-source-lifecycle.test.ts @@ -310,6 +310,7 @@ describe("IosSimctlDriver", () => { it("boots then checks bootstatus and installer readiness with bounded commands", async () => { const runner = new ScriptedProcessRunner([ + { match: simctl("rename", driverData.udid, driverData.name) }, { match: simctl("boot", driverData.udid) }, { match: simctl("bootstatus", driverData.udid, "-b") }, { match: simctl("listapps", driverData.udid) }, @@ -329,6 +330,7 @@ describe("IosSimctlDriver", () => { mode: "full", }); expect(runner.calls).toEqual([ + { ...simctl("rename", driverData.udid, driverData.name), options: { timeoutMs: 5_000 } }, { ...simctl("boot", driverData.udid), options: { timeoutMs: 300_000 } }, { ...simctl("bootstatus", driverData.udid, "-b"), options: { timeoutMs: 300_000 } }, { ...simctl("listapps", driverData.udid), options: { timeoutMs: 30_000 } }, @@ -340,6 +342,7 @@ describe("IosSimctlDriver", () => { async (hangs) => { const clock = new FakeClock(); const runner = new ScriptedProcessRunner([ + { match: simctl("rename", driverData.udid, driverData.name) }, { match: simctl("boot", driverData.udid) }, { match: simctl("bootstatus", driverData.udid, "-b") }, { @@ -375,6 +378,7 @@ describe("IosSimctlDriver", () => { async (hangs) => { const clock = new FakeClock(); const runner = new ScriptedProcessRunner([ + { match: simctl("rename", driverData.udid, driverData.name) }, { match: simctl("boot", driverData.udid) }, { match: simctl("bootstatus", driverData.udid, "-b"), @@ -415,6 +419,7 @@ describe("IosSimctlDriver", () => { async (slowCommand) => { const clock = new FakeClock(); const runner = new ScriptedProcessRunner([ + { match: simctl("rename", driverData.udid, driverData.name) }, { match: simctl("boot", driverData.udid) }, { match: simctl("bootstatus", driverData.udid, "-b"), @@ -435,6 +440,7 @@ describe("IosSimctlDriver", () => { ), ).rejects.toBeInstanceOf(BootTimeoutError); expect(runner.calls.map((call) => call.args)).toEqual([ + simctlArgs("rename", driverData.udid, driverData.name), simctlArgs("boot", driverData.udid), simctlArgs("bootstatus", driverData.udid, "-b"), ...(slowCommand === "listapps" ? [simctlArgs("listapps", driverData.udid)] : []), @@ -446,6 +452,7 @@ describe("IosSimctlDriver", () => { it("times out bootstatus and issues a best-effort shutdown", async () => { const clock = new FakeClock(); const runner = new ScriptedProcessRunner([ + { match: simctl("rename", driverData.udid, driverData.name) }, { match: simctl("boot", driverData.udid) }, { hangs: true, match: simctl("bootstatus", driverData.udid, "-b") }, { match: simctl("shutdown", driverData.udid) }, @@ -459,11 +466,12 @@ describe("IosSimctlDriver", () => { // unhandled rejection in whichever test happens to run next. void ready.catch(() => undefined); - await waitForCalls(runner, 2); + await waitForCalls(runner, 3); clock.advance(300_000); await expect(ready).rejects.toBeInstanceOf(BootTimeoutError); expect(runner.calls.map((call) => call.args)).toEqual([ + simctlArgs("rename", driverData.udid, driverData.name), simctlArgs("boot", driverData.udid), simctlArgs("bootstatus", driverData.udid, "-b"), simctlArgs("shutdown", driverData.udid), diff --git a/src/drivers/ios/index-simulator-audio.test.ts b/src/drivers/ios/index-simulator-audio.test.ts index 8e8f70f00..d8a4f2dd2 100644 --- a/src/drivers/ios/index-simulator-audio.test.ts +++ b/src/drivers/ios/index-simulator-audio.test.ts @@ -40,6 +40,13 @@ afterEach(() => { } }); +/** why: only a prepare boot renames the simulator, so only its script holds the rename. */ +function renameStep(purpose: "prepare" | "recover") { + return purpose === "prepare" + ? [{ match: simctl("rename", driverData.udid, driverData.name) }] + : []; +} + describe("IosSimctlDriver simulator audio", () => { const volumeState = "com.apple.springboard.volumestate"; const udid = driverData.udid; @@ -49,6 +56,7 @@ describe("IosSimctlDriver simulator audio", () => { simctlArgs("spawn", udid, "notifyutil", "-s", volumeState, "0"), simctlArgs("spawn", udid, "notifyutil", "-p", volumeState), ]; + const renameCall = simctlArgs("rename", udid, driverData.name); const bootCalls = [ simctlArgs("boot", udid), simctlArgs("bootstatus", udid, "-b"), @@ -60,7 +68,7 @@ describe("IosSimctlDriver simulator audio", () => { { name: "prepare", options: { mode: "full", purpose: "prepare" } as const, - expected: [...bootCalls, ...silence], + expected: [renameCall, ...bootCalls, ...silence], }, { name: "recover", @@ -71,26 +79,26 @@ describe("IosSimctlDriver simulator audio", () => { name: "a slim prepare, silenced before the readback", data: slimData, options: { mode: "slim", purpose: "prepare" } as const, - expected: [...bootCalls, ...silence, readbackCall], + expected: [renameCall, ...bootCalls, ...silence, readbackCall], }, { name: "the setting true", audio: true, options: { mode: "full", purpose: "prepare" } as const, - expected: bootCalls, + expected: [renameCall, ...bootCalls], }, { name: "a volume command that fails", volume: { code: 1, stderr: "boom", stdout: "" }, options: { mode: "full", purpose: "prepare" } as const, - expected: [...bootCalls, silence[0]], + expected: [renameCall, ...bootCalls, silence[0]], failure: "boom", }, { name: "a volume command that times out", volume: "hangs" as const, options: { mode: "full", purpose: "prepare" } as const, - expected: [...bootCalls, silence[0]], + expected: [renameCall, ...bootCalls, silence[0]], failure: "timed out", }, ])( @@ -102,6 +110,7 @@ describe("IosSimctlDriver simulator audio", () => { ...(result === undefined ? {} : { result }), }); const runner = new ScriptedProcessRunner([ + ...renameStep(c.options.purpose), { match: simctl("boot", udid) }, { match: simctl("bootstatus", udid, "-b") }, { match: simctl("listapps", udid) }, diff --git a/src/drivers/ios/index-slim-mode.test.ts b/src/drivers/ios/index-slim-mode.test.ts index ef0ad4a9a..032d65e85 100644 --- a/src/drivers/ios/index-slim-mode.test.ts +++ b/src/drivers/ios/index-slim-mode.test.ts @@ -172,13 +172,14 @@ describe("IosSimctlDriver", () => { expect(filesystem.writes).toEqual(rewritten ? [overridesPath(slim18_5.udid)] : []); expect(filesystem.modes).toEqual(rewritten ? { file: 0o644, folder: 0o700 } : {}); expect(runner.calls.map((call) => call.args)).toEqual([ + simctlArgs("rename", slim18_5.udid, driverData.name), simctlArgs("boot", slim18_5.udid), simctlArgs("bootstatus", slim18_5.udid, "-b"), simctlArgs("listapps", slim18_5.udid), simctlArgs("spawn", slim18_5.udid, "launchctl", "print-disabled", "system"), ]); - expect(runner.calls[1]?.options).toEqual({ timeoutMs: 260_000 }); - expect(runner.calls[3]?.options).toEqual({ timeoutMs: 120_000 }); + expect(runner.calls[2]?.options).toEqual({ timeoutMs: 260_000 }); + expect(runner.calls[4]?.options).toEqual({ timeoutMs: 120_000 }); expect(onSlimmed).toHaveBeenCalledTimes(1); expect(onSlimmed).toHaveBeenCalledWith({ address: slim18_5.udid, @@ -322,6 +323,7 @@ describe("IosSimctlDriver", () => { expect(result.mode).toBe(mode); expect(runner.calls.map((call) => call.args[3])).toEqual([ + "rename", "boot", "bootstatus", "listapps", @@ -395,7 +397,9 @@ describe("IosSimctlDriver", () => { await plantManagedDevice(filesystem); filesystem.writes.length = 0; const data = { ...driverData, runtimeId }; + const renamed = options.purpose === "prepare"; const runner = new ScriptedProcessRunner([ + ...(renamed ? [{ match: simctl("rename", data.udid, driverData.name) }] : []), { match: simctl("boot", data.udid) }, { match: simctl("bootstatus", data.udid, "-b") }, { match: simctl("listapps", data.udid) }, @@ -422,6 +426,7 @@ describe("IosSimctlDriver", () => { mode: "full", }); expect(runner.calls.map((call) => call.args)).toEqual([ + ...(renamed ? [simctlArgs("rename", data.udid, driverData.name)] : []), simctlArgs("boot", data.udid), simctlArgs("bootstatus", data.udid, "-b"), simctlArgs("listapps", data.udid), @@ -440,6 +445,7 @@ describe("IosSimctlDriver", () => { await plantManagedDevice(filesystem); const clock = new FakeClock(); const runner = new ScriptedProcessRunner([ + { match: { command: "xcrun", args: simctlArgs("rename", slim18_5.udid, driverData.name) } }, { match: { command: "xcrun", args: simctlArgs("boot", slim18_5.udid) } }, { hangs: true, @@ -465,7 +471,7 @@ describe("IosSimctlDriver", () => { prepareSlim, ); - await waitForCalls(runner, 2); + await waitForCalls(runner, 3); const readyState = promiseState(ready); // why: Just past the default 120s: a boot timed against it would have given up by now. @@ -475,7 +481,7 @@ describe("IosSimctlDriver", () => { clock.advance(300_000 - 120_001); expect(await settledValue(ready)).toBeInstanceOf(BootTimeoutError); - expect(runner.calls[1]?.options).toEqual({ timeoutMs: 300_000 }); + expect(runner.calls[2]?.options).toEqual({ timeoutMs: 300_000 }); }); it("an operator's full iOS boot waits ios.full.bootTimeoutMs, then fails with BootTimeoutError", async () => { @@ -492,7 +498,18 @@ describe("IosSimctlDriver", () => { const filesystem = new MemoryFilesystem(); await plantManagedDevice(filesystem); const clock = new FakeClock(); + const renamed = options.purpose === "prepare"; const runner = new ScriptedProcessRunner([ + ...(renamed + ? [ + { + match: { + command: "xcrun", + args: simctlArgs("rename", data.udid, driverData.name), + }, + }, + ] + : []), { match: { command: "xcrun", args: simctlArgs("boot", data.udid) } }, { hangs: true, @@ -520,7 +537,7 @@ describe("IosSimctlDriver", () => { { address: data.udid, deviceId: data.udid, driverData: data }, options, ); - await waitForCalls(runner, 2); + await waitForCalls(runner, renamed ? 3 : 2); const readyState = promiseState(ready); clock.advance(waitsMs - 1); @@ -571,15 +588,16 @@ function runnerReadingFileAtBoot(filesystem: FaultyFilesystem, clock: FakeClock) let contents: string | undefined; const calls = slimBootCalls(driverData.udid, wantedReadback()); const runner = new ScriptedProcessRunner([ + calls[0]!, { - ...calls[0]!, + ...calls[1]!, onSpawn: async () => { clock.advance(40_000); const path = overridesPath(driverData.udid); contents = (await filesystem.exists(path)) ? await filesystem.readFile(path) : undefined; }, }, - ...calls.slice(1), + ...calls.slice(2), ]); return { fileAtBoot: () => contents, runner }; } diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index a7be0610b..a8dc97ec8 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -38,9 +38,9 @@ import { type VirtualSpec, type ScreenCapture, } from "../../core/index.js"; -import type { Clock, ProcessRunner } from "../../ports/index.js"; +import type { Clock, Logger, ProcessRunner } from "../../ports/index.js"; import { runAfterBoot, type AfterBoot } from "./boot-courtesies.js"; -import { runCommand } from "./command-run.js"; +import { errorMessage, runCommand } from "./command-run.js"; import { SeedTurns } from "./seed-turns.js"; import { COMMAND_TIMEOUT_MS, Simctl } from "./simctl.js"; import { DeviceMarks } from "./marks.js"; @@ -108,11 +108,15 @@ const IOS_DEFAULT_MODELS: Readonly { const data = iosDriverData(device); + if (options.purpose === "prepare") { + await this.#rename(data.udid, options.label ?? data.name); + } if (this.#rootOptions === undefined) await this.#deviceHub.disablePasteboardSync(data.udid); const { plan, bootstatusTimeoutMs } = this.#slimBoot.plan(data, options); const write = @@ -396,6 +405,27 @@ export class IosSimctlDriver implements Driver { return this.#slimBoot.settle(device, data, plan, write); } + /** + * why: a lease's label is the simulator's name while the lease boots it, and any other prepare + * boot names it back to its own stored name, so a label never outlives its lease. A rename + * that fails or hangs is logged only: the lease must not wait on a cosmetic name. + */ + async #rename(udid: string, name: string): Promise { + const args = ["rename", udid, name]; + const warn = (reason: string): void => + this.#logger?.warn(`could not rename ${udid} to ${name}: ${reason}`); + try { + const outcome = await this.#simctl.invoke(args, RENAME_TIMEOUT_MS); + if (outcome.kind === "timed-out") { + warn(`timed out after ${String(RENAME_TIMEOUT_MS)}ms`); + } else if (outcome.result.code !== 0) { + warn(outcome.result.stderr.trim()); + } + } catch (error: unknown) { + warn(errorMessage(error)); + } + } + async reclaim( device: DriverDevice, _options: { readonly clean: "standard" | "full" }, diff --git a/src/drivers/ios/slim-except.test.ts b/src/drivers/ios/slim-except.test.ts index 30587568c..30e4aa899 100644 --- a/src/drivers/ios/slim-except.test.ts +++ b/src/drivers/ios/slim-except.test.ts @@ -61,12 +61,12 @@ async function bootWithExcept(options: { const calls = slimBootCalls(slim18_5.udid, ""); const readbackCall = typeof options.readback === "string" - ? { match: calls[3]!.match, result: { code: 0, stderr: "", stdout: options.readback } } + ? { match: calls[4]!.match, result: { code: 0, stderr: "", stdout: options.readback } } : { - match: calls[3]!.match, + match: calls[4]!.match, result: { code: options.readback.code, stderr: options.readback.stderr, stdout: "" }, }; - const runner = new ScriptedProcessRunner([...calls.slice(0, 3), readbackCall]); + const runner = new ScriptedProcessRunner([...calls.slice(0, 4), readbackCall]); const onSlimmed = vi.fn<(fact: SlimmedFact) => void>(); const onSlimSkipped = vi.fn<(fact: SlimSkippedFact) => void>(); const driver = await createSlimDriver( diff --git a/src/drivers/ios/slim-named-services.test.ts b/src/drivers/ios/slim-named-services.test.ts index a19cdf25e..8b717971b 100644 --- a/src/drivers/ios/slim-named-services.test.ts +++ b/src/drivers/ios/slim-named-services.test.ts @@ -78,9 +78,9 @@ async function boot(options: { }; const calls = slimBootCalls(slim18_5.udid, ""); const runner = new ScriptedProcessRunner([ - ...calls.slice(0, 3), + ...calls.slice(0, 4), { - match: calls[3]!.match, + match: calls[4]!.match, result: options.readbackFails === true ? { code: 1, stderr: "boom\n", stdout: "" } diff --git a/src/drivers/ios/test-slim.ts b/src/drivers/ios/test-slim.ts index 2bd7ecd93..68c19ebcb 100644 --- a/src/drivers/ios/test-slim.ts +++ b/src/drivers/ios/test-slim.ts @@ -198,6 +198,7 @@ export function printDisabled(entries: Readonly>): string /** why: The calls of one slim boot: the boot, its wait, the installer poll, then the readback. */ export function slimBootCalls(udid: string, readback: string) { return [ + { match: simctl("rename", udid, driverData.name) }, { match: simctl("boot", udid) }, { match: simctl("bootstatus", udid, "-b") }, { match: simctl("listapps", udid) }, @@ -229,14 +230,14 @@ export async function prepareSlimWith( const calls = slimBootCalls(udid, ""); const readbackCall = readback === "hangs" - ? { hangs: true, match: calls[3]!.match } + ? { hangs: true, match: calls[4]!.match } : "stdout" in readback - ? { match: calls[3]!.match, result: { code: 0, stderr: "", stdout: readback.stdout } } + ? { match: calls[4]!.match, result: { code: 0, stderr: "", stdout: readback.stdout } } : { - match: calls[3]!.match, + match: calls[4]!.match, result: { code: readback.code, stderr: readback.stderr, stdout: "" }, }; - const runner = new ScriptedProcessRunner([...calls.slice(0, 3), readbackCall]); + const runner = new ScriptedProcessRunner([...calls.slice(0, 4), readbackCall]); const clock = new FakeClock(); const onSlimmed = vi.fn<(fact: SlimmedFact) => void>(); const onSlimSkipped = vi.fn<(fact: SlimSkippedFact) => void>(); @@ -254,7 +255,7 @@ export async function prepareSlimWith( prepareSlim, ); if (readback === "hangs") { - await waitForCalls(runner, 4); + await waitForCalls(runner, 5); clock.advance(120_000); } return { onSlimSkipped, onSlimmed, result: await ready, runner }; diff --git a/src/leasing/acquisition-waiter.ts b/src/leasing/acquisition-waiter.ts index 133805284..5e35a9608 100644 --- a/src/leasing/acquisition-waiter.ts +++ b/src/leasing/acquisition-waiter.ts @@ -58,6 +58,12 @@ export function exceptOption(waiter: AcquisitionWaiter): { readonly except?: rea return except === undefined || waiter.spec?.mode !== "slim" ? {} : { except }; } +/** why: a request's label goes to the driver's boot only when it has one, so an unlabelled lease passes no key. */ +export function labelOption(waiter: AcquisitionWaiter): { readonly label?: string } { + const label = waiter.options.label; + return label === undefined ? {} : { label }; +} + /** * why: a plan handed out the capacity or device claim its operation needs; dropping the plan has * to give it back, or the resource stays held with nobody left to release it. diff --git a/src/leasing/acquisition-workflow.ts b/src/leasing/acquisition-workflow.ts index 34e78a964..9d5c2af23 100644 --- a/src/leasing/acquisition-workflow.ts +++ b/src/leasing/acquisition-workflow.ts @@ -34,6 +34,7 @@ import { type AcquisitionWaiter, blockedReason, exceptOption, + labelOption, type GrantingPlanKind, type OperationPlan, operationPlan, @@ -258,6 +259,7 @@ export class AcquisitionWorkflow { handoff = await this.options.provisioner.provision(spec, { claim: { kind: "boot", owner: waiter.id }, ...exceptOption(waiter), + ...labelOption(waiter), onProgress: (progress) => this.options.queue.notifyProgress(waiter, progress), reservation, }); @@ -461,7 +463,12 @@ export class AcquisitionWorkflow { etaMs: waiter.timing.estimatedBootMs, }); const except = exceptOption(waiter).except ?? []; - const ready = await this.options.lifecycle.rebootForLease(device, claim, except); + const ready = await this.options.lifecycle.rebootForLease( + device, + claim, + except, + waiter.options.label, + ); if (ready === undefined) throw new Error(`Reboot target is no longer safe: ${device.id}`); handoff = ready; } catch (error: unknown) { @@ -570,6 +577,7 @@ export class AcquisitionWorkflow { device, claim, exceptOption(waiter).except, + waiter.options.label, ); if (ready === undefined) throw new Error(`Boot target is no longer safe: ${device.id}`); handoff = ready; diff --git a/src/leasing/create-leasing-label.test.ts b/src/leasing/create-leasing-label.test.ts new file mode 100644 index 000000000..f4cb0bab3 --- /dev/null +++ b/src/leasing/create-leasing-label.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from "vitest"; +import { FakeClock } from "../ports/index.js"; +import { FakeDriver } from "../core/testing.js"; +import { request, createHarness, seedReady } from "./test-create-leasing.js"; + +describe("createLeasing: a lease's label reaches the driver's boot", () => { + const slim = { ...request, mode: "slim", except: ["store"] } as const; + const slimSpec = { ...request, mode: "slim", physical: false } as const; + + async function build() { + const driver = new FakeDriver({ + availableOsVersions: ["26.5"], + clock: new FakeClock(1_000), + platform: "ios", + slimmableOsVersions: ["26.5"], + }); + return createHarness({ driver, iosModes: ["full", "slim"] }); + } + + const cases = [ + { name: "provision", seed: "none", ask: request, xcodeSet: false }, + { name: "boot of a shut-down device", seed: "shutdown", ask: request, xcodeSet: false }, + { name: "reboot on Xcode's set", seed: "ready", ask: request, xcodeSet: true }, + { name: "reboot for an except lease", seed: "slim", ask: slim, xcodeSet: false }, + ] as const; + + async function seeded(harness: Awaited>, seed: string) { + if (seed === "ready") await seedReady(harness); + if (seed === "slim") await seedReady(harness, slimSpec, "slim"); + if (seed !== "shutdown") return; + const device = await seedReady(harness); + await harness.registry.transitionDevice(device.id, "shutdown", { + event: "device.shutdown", + payload: { deviceId: device.id, initiator: "test" }, + }); + } + + /** why: the options of the one `makeReady` a lease of this case made, with or without a label. */ + async function bootOptionsOf(c: (typeof cases)[number], label: string | undefined) { + const harness = await build(); + if (c.xcodeSet) { + Object.defineProperty(harness.driver, "rebootReadyBeforeGrant", { value: true }); + } + await seeded(harness, c.seed); + const before = harness.driver.calls.length; + await harness.engine.request(c.ask, { + ownerId: "o", + requesterId: "r", + ...(label === undefined ? {} : { label }), + }); + const boots = harness.driver.calls + .slice(before) + .filter((call) => call.operation === "makeReady"); + expect(boots, c.name).toHaveLength(1); + return boots[0]!.arguments[1] as { label?: string }; + } + + it("passes the request's label to makeReady on a provision, a boot and a reboot, and none without one", async () => { + for (const c of cases) { + expect((await bootOptionsOf(c, "feature-x")).label, `${c.name} with a label`).toBe( + "feature-x", + ); + expect(await bootOptionsOf(c, undefined), `${c.name} without one`).not.toHaveProperty( + "label", + ); + } + }); +}); diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index e700d40ba..49bb93c8a 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -136,7 +136,7 @@ simlock lease --platform [--device | --class ] | `--timeout ` | How long to wait in the queue before failing with `QUEUE_TIMEOUT` (exit 10). | No limit: waits until a device is free | | `--lease-id ` | The ID the lease gets, in place of a generated one. 1 to 64 letters, digits, `-` and `_`, starting with a letter or digit. | A generated ID | | `--run ` | The run id the lease carries: a name a CI job gives every lease it takes, 1 to 128 letters, digits, `.`, `_` or `-`, such as `123-1`. A gateway passes it to its worker and its admission command. `simlock status` shows it on the lease line. A bad value exits 2, before the command connects. The `SIMLOCK_RUN` environment variable sets it when the flag is absent; an empty value is unset. | `SIMLOCK_RUN`, else on GitHub Actions `$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT` (`-1` when the attempt is unset), else none | -| `--label ` | A name for the lease, such as `feature-x`: 1 to 64 characters, none of them a control character. It is display-only: nothing routes or limits by it. `simlock status` shows it on the lease line after the run id, and every lease read answers it as `label`. On Android and physical devices it shows on the lease only. A bad value is refused by the daemon with `BAD_REQUEST` (exit 2). | None | +| `--label ` | A name for the lease, such as `feature-x`: 1 to 64 characters, none of them a control character. It is display-only: nothing routes or limits by it. `simlock status` shows it on the lease line after the run id, and every lease read answers it as `label`. An iOS simulator booted for the lease takes the label as its name before it boots, so with `drivers.ios.deviceSet: "default"` and `ios.simulator.headless: false` DeviceHub and Simulator.app show it; the next boot of that simulator for any other lease names it back. A warm simulator granted without a boot keeps its name. On Android and physical devices the label shows on the lease only. A bad value is refused by the daemon with `BAD_REQUEST` (exit 2). | None | | `--meta ` | Repeatable. Context for the gateway's admission command, such as `--meta project=checkout-app --meta role=ci`. The key is the text before the first `=`; the value is everything after it. The same key twice keeps the last. At most 16 keys; a key is 1 to 64 characters, a value 0 to 256, and keys and values together at most 2048. A gateway passes it to its admission command only: it is stored nowhere, in no event, and a worker ignores it. A flag with no `=`, or a bound broken, exits 2. | None | | `--physical` | Lease an enrolled physical device. Cannot be combined with `--mode`, `--image-tag`, `--baseline` or `--allow-download`. | Off: simulators and emulators only | | `--no-wait` | Fail with `NO_CAPACITY` (exit 11) instead of waiting in the queue. | Off |