Skip to content
Merged
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
2 changes: 1 addition & 1 deletion src/drivers/ios/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Resolve and boot:
- 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`.
- A recovery boot writes no slim overrides and reads nothing back. DeviceHub clipboard isolation is configured before preparation and recovery boots; ready default-set simulators reboot under the lease claim before a grant. Active leases at upgrade keep clipboard sync until a later boot or lease end.
- A recovery boot writes no slim overrides and reads nothing back. DeviceHub clipboard isolation is set, read back, before preparation and recovery boots (not `false`: refused); ready default-set simulators reboot under the claim before a grant. Leases active at upgrade keep it until a later boot.
- `launchdOverridesRoot` is outside the device set: `destroy` and each seed deletion remove their folder after `simctl delete`.
- After every boot and before the readback, `runAfterBoot` (`boot-courtesies.ts`) runs the volume step, then the window step. Each only reports its failure (`onSilenceFailed`, `onWindowFailed`).
- Volume (`ios.simulator.audio: false`): apps play at volume 0. A baseline source is not silenced.
Expand Down
17 changes: 11 additions & 6 deletions src/drivers/ios/boot-courtesies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/
import { promiseState } from "../../test-support/promise-state.js";
import { IosSimctlDriver, type WindowFailedFact } from "./index.js";
import { memorySourceDatabase } from "./testing.js";
import { deviceHubEdit } from "./test-slim.js";
import { deviceHubDisable } from "./test-slim.js";

const instanceId = "instance-1";
const overridesRoot = "/private/var/tmp";
Expand Down Expand Up @@ -80,7 +80,8 @@ describe("IosSimctlDriver simulator window", () => {
const slimData = { ...driverData, runtimeId: "com.apple.CoreSimulator.SimRuntime.iOS-18-5" };
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 clipboardSteps = deviceHubDisable(udid);
const clipboard = clipboardSteps.map((step) => step.match);
const renameCall = xcrun("rename", udid, driverData.name);
const bootCalls = [xcrun("boot", udid), xcrun("bootstatus", udid, "-b"), xcrun("listapps", udid)];
const deviceHub = open(
Expand Down Expand Up @@ -133,14 +134,16 @@ 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(
[...renamed, ...clipboard, ...c.expected].map((match) => ({
const runner = new ScriptedProcessRunner([
...renamed.map((match) => ({ match })),
...clipboardSteps,
...c.expected.map((match) => ({
match,
...(match === deviceHub && c.deviceHubResult !== undefined
? { result: c.deviceHubResult }
: {}),
})),
);
]);
const driver = await IosSimctlDriver.create({
clock: new FakeClock(),
database: await memorySourceDatabase(),
Expand Down Expand Up @@ -212,7 +215,9 @@ describe("IosSimctlDriver simulator window", () => {
"makes the simulator ready and reports the failure when opening its window fails: $name",
async (c) => {
const runner = new ScriptedProcessRunner([
...[renameCall, ...clipboard, ...bootCalls].map((match) => ({ match })),
{ match: renameCall },
...clipboardSteps,
...bootCalls.map((match) => ({ match })),
...c.script,
]);
const clock = new FakeClock();
Expand Down
4 changes: 4 additions & 0 deletions src/drivers/ios/boot-deadline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ describe("IosSimctlDriver boot deadline", () => {
},
}
: {}),
// why: the clipboard read-back (#1822) needs PlistBuddy's Print to answer false.
...(args[1]?.startsWith("Print ")
? { result: { code: 0, stderr: "", stdout: "false\n" } }
: {}),
...(isShutdown ? { onSpawn: () => clock.advance(20_000) } : {}),
};
return new ScriptedProcessRunner([entry]).spawn(command, args, options);
Expand Down
75 changes: 73 additions & 2 deletions src/drivers/ios/clipboard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ class FakeDeviceHubDomain {
domain: Preferences = {};
staged: Preferences = {};
failing = "";
// why: a daemon that cannot reach DeviceHub's sandbox container (#1822): export sees an empty domain and import exits 0 but writes nothing.
containerBlocked = false;
hold: Promise<void> | undefined;

holdFirstImport(handle: { wait: () => Promise<unknown> }): void {
Expand All @@ -42,6 +44,14 @@ class FakeDeviceHubDomain {
answer(
command: string,
args: readonly string[],
): { code: number; stderr: string; stdout: string } {
const printed = command === "/usr/libexec/PlistBuddy" ? /^Print (.*)$/.exec(args[1]!) : null;
return printed === null ? this.exit(command, args) : this.print(printed[1]!);
}

private exit(
command: string,
args: readonly string[],
): { code: number; stderr: string; stdout: string } {
const warmBoot = this.warm && args[1] === "boot";
if (warmBoot) this.warm = false;
Expand All @@ -50,6 +60,14 @@ class FakeDeviceHubDomain {
return { code: warmBoot || !this.succeeds(command, args) ? 1 : 0, stderr, stdout: "" };
}

// why: PlistBuddy's Print writes a boolean as true or false, and exits 1 on a key that does not exist.
private print(path: string): { code: number; stderr: string; stdout: string } {
const [, , udid = "", key = ""] = path.split(":");
const value = this.staged[udid]?.[key];
if (value === undefined) return { code: 1, stderr: "Does Not Exist", stdout: "" };
return { code: 0, stderr: "", stdout: `${String(value)}\n` };
}

succeeds(command: string, args: readonly string[]): boolean {
if (command === this.failing || (this.failing === "delete" && args[1] === "delete")) {
return false;
Expand All @@ -59,6 +77,10 @@ class FakeDeviceHubDomain {
}

private transfer(verb: string): void {
if (this.containerBlocked) {
if (verb === "export") this.staged = {};
return;
}
if (verb === "export") this.staged = structuredClone(this.domain);
if (verb === "import") this.domain = structuredClone(this.staged);
}
Expand Down Expand Up @@ -144,6 +166,8 @@ describe("IosSimctlDriver DeviceHub clipboard", () => {
exportDomain,
staged(`Set :DevicePreferences:${udid}:pasteboardSyncEnabled false`),
importDomain,
exportDomain,
staged(`Print :DevicePreferences:${udid}:pasteboardSyncEnabled`),
["xcrun", "simctl", "boot", udid],
["xcrun", "simctl", "bootstatus", udid, "-b"],
["xcrun", "simctl", "listapps", udid],
Expand Down Expand Up @@ -210,9 +234,9 @@ describe("IosSimctlDriver DeviceHub clipboard", () => {
hub.failing = "";
hub.warm = true;
await driver.makeReady(device, prepareFull);
expect(calls.slice(0, 7)).toEqual([
expect(calls.slice(0, 9)).toEqual([
rename,
...syncOffThenBoot.slice(0, 4),
...syncOffThenBoot.slice(0, 6),
["xcrun", "simctl", "shutdown", udid],
["xcrun", "simctl", "boot", udid],
]);
Expand All @@ -229,4 +253,51 @@ describe("IosSimctlDriver DeviceHub clipboard", () => {
await expect(driver.destroy(device)).rejects.toThrow();
expect(calls.some((call) => call[0] === "defaults")).toBe(false);
});

it("refuses to boot a simulator, for preparation and recovery alike, when DeviceHub's preferences do not keep the pasteboard sync off", async () => {
const udid = driverData.udid;
const calls: string[][] = [];
const hub = new FakeDeviceHubDomain();
hub.domain = { [udid]: { pasteboardSyncEnabled: true, windowScale: 75 } };
hub.containerBlocked = true;
const answersEveryCall: ProcessRunner = {
run: () => Promise.reject(new Error("the driver runs commands through spawn")),
spawn(command, args, options) {
calls.push([command, ...args]);
return new ScriptedProcessRunner([
{ match: { args: [...args], command }, result: hub.answer(command, args) },
]).spawn(command, args, options);
},
spawnStreaming: () => {
throw new Error("the driver streams nothing here");
},
};
const driver = await IosSimctlDriver.create({
database: await memorySourceDatabase(),
clock: new FakeClock(),
coreSimulatorRoot: "/Users/u/Library/Developer/CoreSimulator",
driverConfig: { deviceSet: "default" },
filesystem: new MemoryFilesystem(),
idGenerator: { generate: () => "device-1" },
instanceId,
processRunner: answersEveryCall,
simlockHome: "/home/.simlock",
});
const device = { address: udid, deviceId: udid, driverData };
const boots = () => calls.filter((call) => call[1] === "simctl" && call[2] === "boot");

for (const purpose of ["prepare", "recover"] as const) {
calls.length = 0;
await expect(driver.makeReady(device, { mode: "full", purpose })).rejects.toThrow(
`Could not disable DeviceHub clipboard sync for ${udid}`,
);
expect(calls).toContainEqual([
"defaults",
"import",
"com.apple.dt.Devices",
expect.any(String),
]);
expect(boots()).toEqual([]);
}
});
});
22 changes: 18 additions & 4 deletions src/drivers/ios/devicehub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,24 +49,38 @@ export class DeviceHubPreferences {
// to a scratch file, edited there with PlistBuddy, and imported back through cfprefsd.
async #editDeviceHubPreferences(
edit: (buddy: (command: string) => Promise<boolean>) => Promise<boolean>,
readBack?: string,
): Promise<boolean> {
return await withPasteboardWrite(async () => {
await this.#filesystem.mkdirp(this.#overridesRoot, { mode: 0o700 });
const staged = join(this.#overridesRoot, DEVICEHUB_STAGING_FILE);
const run = async (command: string, args: string[]): Promise<boolean> => {
const output = async (command: string, args: string[]): Promise<string | undefined> => {
const outcome = await runCommand(
this.#processRunner,
this.#clock,
command,
args,
COMMAND_TIMEOUT_MS,
);
return outcome.kind !== "timed-out" && outcome.result.code === 0;
if (outcome.kind === "timed-out" || outcome.result.code !== 0) return undefined;
return outcome.result.stdout;
};
const run = async (command: string, args: string[]): Promise<boolean> =>
(await output(command, args)) !== undefined;
try {
if (!(await run("defaults", ["export", DEVICEHUB_DOMAIN, staged]))) return false;
const buddy = (command: string) => run("/usr/libexec/PlistBuddy", ["-c", command, staged]);
return (await edit(buddy)) && (await run("defaults", ["import", DEVICEHUB_DOMAIN, staged]));
if (
!(await edit(buddy)) ||
!(await run("defaults", ["import", DEVICEHUB_DOMAIN, staged]))
) {
return false;
}
if (readBack === undefined) return true;
// why: an import that exits 0 can still have written nothing (cfprefsd cannot reach DeviceHub's container from an ssh-started daemon), so the value is read from a fresh export.
if (!(await run("defaults", ["export", DEVICEHUB_DOMAIN, staged]))) return false;
const value = await output("/usr/libexec/PlistBuddy", ["-c", `Print ${readBack}`, staged]);
return value?.trim() === "false";
} finally {
await this.#filesystem.rm(staged).catch(() => undefined);
}
Expand All @@ -80,7 +94,7 @@ export class DeviceHubPreferences {
await buddy("Add :DevicePreferences dict");
await buddy(`Add ${path} dict`);
return await buddy(`Add ${path}:pasteboardSyncEnabled bool false`);
});
}, `${path}:pasteboardSyncEnabled`);
if (!done) throw new DriverCrashError(`Could not disable DeviceHub clipboard sync for ${udid}`);
}

Expand Down
5 changes: 2 additions & 3 deletions src/drivers/ios/index-device-set.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
deviceRoot,
sourcesSetPath,
simctlArgs,
deviceHubDisable,
deviceHubEdit,
plantManagedDevice,
instanceId,
Expand Down Expand Up @@ -121,9 +122,7 @@ describe("IosSimctlDriver device set", () => {
const runner = new ScriptedProcessRunner(
steps.flatMap((step) => [
...(!scoped && step.args[0] === "boot" && step.args[1] !== seedUdid
? deviceHubEdit(
`Set :DevicePreferences:${String(step.args[1])}:pasteboardSyncEnabled false`,
).map((match) => ({ match }))
? deviceHubDisable(String(step.args[1]))
: []),
{
match: { args: argvOf(step), command: "xcrun" },
Expand Down
4 changes: 3 additions & 1 deletion src/drivers/ios/index-seed-throwaway.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/
import { IosSimctlDriver } from "./index.js";
import { memorySourceDatabase, plantSource } from "./testing.js";
import {
deviceHubDisable,
deviceHubEdit,
deviceRoot,
sourcesSetPath,
Expand Down Expand Up @@ -83,6 +84,7 @@ describe("IosSimctlDriver seed throwaway", () => {
...(stdout === undefined ? {} : { result: { code: 0, stderr: "", stdout } }),
});
const inSet = (...args: string[]) => simctlIn(world, undefined, ...args);
const disableSync = (udid: string) => (world.isDefault ? deviceHubDisable(udid) : []);
const hub = (command: string) =>
world.isDefault ? deviceHubEdit(command).map((match) => ({ match })) : [];
const database = await memorySourceDatabase();
Expand All @@ -99,7 +101,7 @@ describe("IosSimctlDriver seed throwaway", () => {
inSet("create", name, driverData.deviceTypeId, driverData.runtimeId),
`${throwawayUdid}\n`,
),
...hub(`Set :DevicePreferences:${throwawayUdid}:pasteboardSyncEnabled false`),
...disableSync(throwawayUdid),
{
match: inSet("boot", throwawayUdid),
onSpawn: () => {
Expand Down
16 changes: 16 additions & 0 deletions src/drivers/ios/test-slim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,22 @@ export function deviceHubEdit(command: string) {
];
}

// why: turning clipboard sync off is read back from a fresh export (#1822), so its calls end with an export and a Print that answers false.
export function deviceHubDisable(udid: string) {
const path = `:DevicePreferences:${udid}:pasteboardSyncEnabled`;
return [
...deviceHubEdit(`Set ${path} false`).map((match) => ({ match })),
{ match: { command: "defaults", args: ["export", "com.apple.dt.Devices", deviceHubStaging] } },
{
match: {
command: "/usr/libexec/PlistBuddy",
args: ["-c", `Print ${path}`, deviceHubStaging],
},
result: { code: 0, stderr: "", stdout: "false\n" },
},
];
}

/** why: Lets queued continuations run, so a test can see that something has not happened yet. */
export async function flushMicrotasks221(): Promise<void> {
for (let count = 0; count < 100; count += 1) await Promise.resolve();
Expand Down
Loading