Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/cli/commands/lease.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ async function runLease(
"export-env": { type: "boolean" },
help: { type: "boolean", short: "h" },
"image-tag": { type: "string" },
label: { type: "string" },
"lease-id": { type: "string" },
mode: { type: "string" },
"no-wait": { type: "boolean" },
Expand All @@ -63,7 +64,7 @@ async function runLease(
environment.stdout.write(
"Usage: simlock lease --platform <ios|android> [--device <model> | --class <class>]\n" +
" [--os <version|range>] [--mode <slim|full>] [--image-tag <tag>] [--agent-id <id>]\n" +
" [--timeout <duration>] [--lease-id <id>] [--physical]\n" +
" [--timeout <duration>] [--lease-id <id>] [--label <text>] [--physical]\n" +
" [--no-wait] [--detach] [--ttl <duration>] [--allow-download]\n" +
" [--export-env] [--bind-pid <pid>]\n",
);
Expand Down Expand Up @@ -184,6 +185,7 @@ async function runLease(
...(typeof values.mode === "string" ? { mode: values.mode as "slim" | "full" } : {}),
...(typeof values["image-tag"] === "string" ? { imageTag: values["image-tag"] } : {}),
...(typeof values["lease-id"] === "string" ? { leaseId: values["lease-id"] } : {}),
...(typeof values.label === "string" ? { label: values.label } : {}),
...(timeoutMs === undefined ? {} : { timeoutMs }),
...(ttlMs === undefined ? {} : { ttlMs }),
},
Expand Down
23 changes: 22 additions & 1 deletion src/cli/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6741,6 +6741,27 @@ describe("CLI: holder renew and release (ADR 0004 §2)", () => {
expect(output.stderr).toContain('"code":"LEASE_ID_TAKEN"');
});

it("the CLI --label flag sends label, and an omitted flag sends none", async () => {
const output = outputCapture();
const requested: unknown[] = [];
const environment = output.environmentWith({
clock: new FakeClock(0),
connectAdmin: async () =>
fakeClient({
requestLease: (input) => {
requested.push("label" in input ? input.label : "absent");
return Promise.resolve(detachedGrant);
},
}),
});
const lease = ["lease", "--platform", "android", "--detach"];

await runCli([...lease, "--label", "feature-x"], environment);
await runCli(lease, environment);

expect(requested).toEqual(["feature-x", "absent"]);
});

it.each(["SIGINT", "SIGTERM"] as const)(
"releases explicitly on %s (ADR 0004 §2's catchable signals)",
async (signal) => {
Expand Down Expand Up @@ -9353,7 +9374,7 @@ describe("simlock lease: a request names a model, a class, or nothing", () => {
expect(output.stdout).toBe(
"Usage: simlock lease --platform <ios|android> [--device <model> | --class <class>]\n" +
" [--os <version|range>] [--mode <slim|full>] [--image-tag <tag>] [--agent-id <id>]\n" +
" [--timeout <duration>] [--lease-id <id>] [--physical]\n" +
" [--timeout <duration>] [--lease-id <id>] [--label <text>] [--physical]\n" +
" [--no-wait] [--detach] [--ttl <duration>] [--allow-download]\n" +
" [--export-env] [--bind-pid <pid>]\n",
);
Expand Down
24 changes: 24 additions & 0 deletions src/contract/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,30 @@ describe("lease.request osVersion", () => {
);
});

describe("lease.request label", () => {
const parse = (label: unknown) =>
OPERATIONS["lease.request"].input.safeParse({ label, platform: "android" });

it.each([
["a branch name", "feature/login"],
["spaces and characters outside ASCII", "Zé's phone"],
["64 characters", "a".repeat(64)],
])("accepts %s", (_label, label) => {
expect(parse(label).success).toBe(true);
});

it.each([
["an empty string", ""],
["65 characters", "a".repeat(65)],
["a line break", "feature-x\nhw.keyboard=yes"],
["a NUL", "feature\u0000x"],
["a line separator", "feature\u2028x"],
["a number", 7],
])("refuses %s", (_label, label) => {
expect(parse(label).success).toBe(false);
});
});

describe("lease.request leaseId", () => {
const parse = (leaseId: unknown) =>
OPERATIONS["lease.request"].input.safeParse({ leaseId, model: "iPhone 17", platform: "ios" });
Expand Down
2 changes: 2 additions & 0 deletions src/contract/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
hostLoadSchema,
imageTagSchema,
leaseGrantSchema,
leaseLabelSchema,
leaseRecordSchema,
nukeReportSchema,
passthroughCommandSchema,
Expand Down Expand Up @@ -166,6 +167,7 @@ const leaseRequestBaseSchema = z
owner: z.string().optional(),
idempotencyKey: z.string().min(1).max(200).optional(),
leaseId: leaseIdSchema.optional(),
label: leaseLabelSchema.optional(),
fleetRequestId: z.string().min(1).max(200).optional(),
requires: z
.array(capabilityNameSchema)
Expand Down
2 changes: 1 addition & 1 deletion src/contract/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export interface ProtocolRange {
const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() });

/** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 69, max: 69 };
export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 70, max: 70 };

const LEGACY_DAEMON_PROTOCOL_VERSION = 2;

Expand Down
13 changes: 13 additions & 0 deletions src/contract/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,19 @@ export const imageTagSchema = z
.max(IMAGE_TAG_MAX)
.regex(/^[A-Za-z0-9_.-]+$/, "imageTag may contain only letters, digits, '_', '.' and '-'");

/**
* A lease's label, the name of the simulator it boots.
* why: a driver passes it to `simctl rename`, so a line break or NUL never reaches one (safety rule 10).
*/
export const leaseLabelSchema = z
.string()
.min(1)
.max(64)
.refine(
(label) => !/[\p{Cc}\u2028\u2029]/u.test(label),
"label must not contain control characters",
);

const REQUESTER_ID_MAX = 256;
const GATEWAY_PREFIX = /^gw:[^:]{0,100}:/;

Expand Down
8 changes: 7 additions & 1 deletion src/core/device-provisioner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export interface ProvisionDeviceOptions {
* handoff, so a request planning in between sees a device that is on its way, and whose.
*/
readonly claim?: { readonly kind: "boot"; readonly owner?: string };
/** why: the boot titles the new device with it, so it reaches `makeReady` with the claim. */
readonly label?: string;
readonly onProgress?: (progress: ProvisionProgress) => void;
readonly reservation: CapacityReservation;
}
Expand Down Expand Up @@ -118,7 +120,11 @@ export class DeviceProvisioner {
stage: "booting",
etaMs: driver.estimate({ operation: "boot" }, spec),
});
const ready = await this.options.lifecycle.readyProvisionedForLease(device, bootClaim);
const ready = await this.options.lifecycle.readyProvisionedForLease(
device,
bootClaim,
options.label,
);
if (ready === undefined)
throw new Error(`Registered device could not be made ready: ${device.id}`);
return ready;
Expand Down
4 changes: 4 additions & 0 deletions src/core/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,8 @@ export interface Driver {
options: {
readonly purpose: "prepare" | "recover";
readonly mode: DeviceMode;
/** why: a `prepare` boot names the device with the lease's label where its platform can (iOS); a `recover` boot changes nothing (safety rule 2). */
readonly label?: string;
},
): Promise<DriverDevice>;
reclaim(
Expand Down Expand Up @@ -320,6 +322,8 @@ export interface Driver {
destroyLegacy?(device: VirtualDriverDevice): Promise<void>;
advisories?(): Promise<readonly DriverAdvisory[]>;
toolVersions?(): Promise<readonly DriverToolVersion[]>;
/** why: names a booted device for its lease, or back to its own name without a label; only a platform that can rename one has it (iOS). */
applyLabel?(device: DriverDevice, label: string | undefined): Promise<void>;
}

export interface LegacyDevice {
Expand Down
13 changes: 11 additions & 2 deletions src/core/fake-driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ export type FakeDriverOperation =
| "removeComponent"
| "revalidateRoot"
| "findLegacy"
| "destroyLegacy";
| "destroyLegacy"
| "applyLabel";

export type DriverEstimateOperation = "provision" | "boot" | "reclaim";

Expand Down Expand Up @@ -418,7 +419,11 @@ export class FakeDriver implements Driver {

async makeReady(
device: DriverDevice,
options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode },
options: {
readonly purpose: "prepare" | "recover";
readonly mode: DeviceMode;
readonly label?: string;
},
): Promise<DriverDevice> {
await this.#beforeCall("makeReady", device, options);
this.#requireDevice(device);
Expand Down Expand Up @@ -603,6 +608,10 @@ export class FakeDriver implements Driver {
return this.#leaseEnvironment;
}

async applyLabel(device: DriverDevice, label: string | undefined): Promise<void> {
await this.#beforeCall("applyLabel", device, label);
}

async passthrough(
tool: string,
device: VirtualDriverDevice | PhysicalDriverDevice | undefined,
Expand Down
8 changes: 6 additions & 2 deletions src/core/managed-device-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@ export class ManagedDeviceLifecycle {
async bootForLease(
target: VirtualDevice,
claim: DeviceOperationClaim,
label?: string,
): Promise<ReadyDeviceHandoff | undefined> {
return this.#makeReadyForLease(target, "shutdown", claim);
return this.#makeReadyForLease(target, "shutdown", claim, label);
}

/**
Expand All @@ -95,8 +96,9 @@ export class ManagedDeviceLifecycle {
async readyProvisionedForLease(
target: VirtualDevice,
claim?: DeviceOperationClaim,
label?: string,
): Promise<ReadyDeviceHandoff | undefined> {
return this.#makeReadyForLease(target, "provisioning", claim);
return this.#makeReadyForLease(target, "provisioning", claim, label);
}

async shutdown(
Expand Down Expand Up @@ -231,6 +233,7 @@ export class ManagedDeviceLifecycle {
target: VirtualDevice,
expectedState: "provisioning" | "shutdown",
existingClaim?: DeviceOperationClaim,
label?: string,
): Promise<ReadyDeviceHandoff | undefined> {
const claimed = await this.#claim(target, [expectedState], "boot", existingClaim);
if (claimed === undefined) return undefined;
Expand All @@ -242,6 +245,7 @@ export class ManagedDeviceLifecycle {
.makeReady(toDriverDevice(claimed.device), {
mode: specMode(claimed.device.spec),
purpose: "prepare",
...(label === undefined ? {} : { label }),
});
} catch (error: unknown) {
await this.#release(claimed);
Expand Down
2 changes: 1 addition & 1 deletion src/daemon-protocol/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {

describe("daemon protocol", () => {
it("keeps the current protocol version and newline framing", () => {
expect(DAEMON_PROTOCOL_VERSION).toBe(69);
expect(DAEMON_PROTOCOL_VERSION).toBe(70);
expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n');
});

Expand Down
17 changes: 17 additions & 0 deletions src/daemon/dispatcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,23 @@ describe("Dispatcher: parsing", () => {
]);
});

it("boots the device of a lease.request with its label", async () => {
const { dispatcher, driver } = await buildDispatcher();

await dispatcher.dispatch(
"lease.request",
{ label: "feature-x", model: "iPhone 17 Pro", platform: "ios" },
session(),
);

expect(driver.calls.find((call) => call.operation === "makeReady")?.arguments[1]).toMatchObject(
{
label: "feature-x",
purpose: "prepare",
},
);
});

it("grants lease.request's leaseId as the lease ID, and answers an ID that is in use with LEASE_ID_TAKEN carrying it in details", async () => {
const { dispatcher } = await buildDispatcher();
const input = { leaseId: "ad-7f3a", model: "iPhone 17 Pro", platform: "ios" } as const;
Expand Down
1 change: 1 addition & 0 deletions src/daemon/dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,7 @@ export class Dispatcher {
: { onAdmitted: session.onRequestAdmitted }),
...(input.idempotencyKey === undefined ? {} : { idempotencyKey: input.idempotencyKey }),
...(input.leaseId === undefined ? {} : { leaseId: input.leaseId }),
...(input.label === undefined ? {} : { label: input.label }),
...(input.fleetRequestId === undefined ? {} : { fleetRequestId: input.fleetRequestId }),
...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
...(input.ttlMs === undefined ? {} : { ttlMs: input.ttlMs }),
Expand Down
12 changes: 10 additions & 2 deletions src/drivers/ios/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,18 @@ Boot — `makeReady`:
what was written. A label not as written → `full`; a readback that fails → `slim`; both
→ `onSlimSkipped` (logged only). Every label as written, and the write ok → `slim`, `onSlimmed` →
`device.slimmed`.
4. `purpose: "recover"`: boot only, no write, no readback.
4. `prepare` with a `label`: `simctl rename <udid> <label>` before step 1, so Simulator.app
titles the window with it.
5. `purpose: "recover"`: boot only, no write, no readback, no rename.

Reclaim — `reclaim` ignores the clean level: shut down → `simctl erase` → write mark →
Reclaim — `reclaim` ignores the clean level: shut down → `simctl erase` → `simctl rename` back to
the stored `name` → write mark →
`shutdown` / `erase`. The erase keeps the overrides file, so the next `prepare` finds it as wanted.

Label — `applyLabel`: `simctl rename <udid>` to the label, or back to the stored `name` without
one (5 s timeout, since the grant waits on it). Reclaim's rename back is logged when it fails
and never fails the reclaim. A booted simulator takes the new name at once, but
a window Simulator.app already has open keeps its old title.
Physical → `devicectl device uninstall app` for every app not enrolled → `ready` / `uninstall`.
`destroy` / `destroyLegacy`: shut down, `simctl delete`, then remove the overrides folder (a failed removal is logged). `listManaged`: `simctl list -j devices` in the set, plus marks.

Expand Down
Loading