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
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => ({
...(await importOriginal<typeof import('@agent-device/host-kit/diagnostics')>()),
emitDiagnostic: vi.fn(),
}));
// Keyboard intro preparation has its own coverage in ios-simulator-keyboard.test.ts.
vi.mock('../ios-simulator-keyboard.ts', () => ({ prepareIosSimulatorKeyboardIntros: vi.fn() }));
vi.mock('../simulator.ts', () => ({ ensureBootedSimulator: vi.fn() }));
import { ensureBootedSimulator } from '../simulator.ts';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ vi.mock('@agent-device/host-kit/command', async (importOriginal) => {
const actual = await importOriginal<typeof import('@agent-device/host-kit/command')>();
return { ...actual, runCmd: vi.fn(actual.runCmd) };
});
// Keyboard intro preparation has its own coverage in ios-simulator-keyboard.test.ts.
vi.mock('../ios-simulator-keyboard.ts', () => ({ prepareIosSimulatorKeyboardIntros: vi.fn() }));
vi.mock('../simulator.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../simulator.ts')>();
return { ...actual, ensureBootedSimulator: vi.fn(actual.ensureBootedSimulator) };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ vi.mock('@agent-device/host-kit/command', async (importOriginal) => {
const actual = await importOriginal<typeof import('@agent-device/host-kit/command')>();
return { ...actual, runCmd: vi.fn(actual.runCmd) };
});
// Keyboard intro preparation has its own coverage in ios-simulator-keyboard.test.ts.
vi.mock('../ios-simulator-keyboard.ts', () => ({ prepareIosSimulatorKeyboardIntros: vi.fn() }));
vi.mock('../simulator.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../simulator.ts')>();
return { ...actual, ensureBootedSimulator: vi.fn(actual.ensureBootedSimulator) };
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { beforeEach, test, vi } from 'vitest';
import { build, type PlistValue } from 'plist';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { mkdtempForTest } from '../../__tests__/tmp-dir.ts';
import { withFakeAppleTool } from '../../__tests__/fake-apple-tool.ts';
import {
IOS_TEST_DEVICE,
IOS_TEST_SIMULATOR,
MACOS_TEST_DEVICE,
} from './apple-core-stub-helpers.ts';

vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => ({
...(await importOriginal<typeof import('@agent-device/host-kit/diagnostics')>()),
emitDiagnostic: vi.fn(),
}));
vi.mock('../simulator.ts', () => ({ ensureBootedSimulator: vi.fn() }));
// withFakeAppleTool installs a scoped provider, which never reads this host's preferences, so the
// host-read tests below call the prepare step outside it with runXcrun answered here.
vi.mock('../tool-provider.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../tool-provider.ts')>();
return { ...actual, runXcrun: vi.fn(actual.runXcrun) };
});
vi.mock('../ios-simulator-accessibility.ts', () => ({
prepareIosSimulatorAccessibility: vi.fn(),
}));
const { emitDiagnostic } = await import('@agent-device/host-kit/diagnostics');
const { ensureBootedSimulator } = await import('../simulator.ts');
const { runXcrun, withAppleToolProvider } = await import('../tool-provider.ts');
const actualRunXcrun = (
await vi.importActual<typeof import('../tool-provider.ts')>('../tool-provider.ts')
).runXcrun;
const { openIosApp } = await import('../app-launch.ts');
const { prepareIosSimulatorKeyboardIntros } = await import('../ios-simulator-keyboard.ts');

let setPath: string;
let device: DeviceInfo;

beforeEach(async () => {
vi.clearAllMocks();
vi.mocked(runXcrun).mockImplementation(actualRunXcrun);
setPath = await mkdtempForTest('agent-device-keyboard-set-');
device = { ...IOS_TEST_SIMULATOR, simulatorSetPath: setPath };
});

function preferencesDir(): string {
const dir = path.join(setPath, device.id, 'data/Library/Preferences');
fs.mkdirSync(dir, { recursive: true });
return dir;
}

function writePreferences(contents: Record<string, PlistValue>): void {
fs.writeFileSync(
path.join(preferencesDir(), 'com.apple.keyboard.preferences.plist'),
build(contents),
);
}

const keyWrite = (key: string) => [
'simctl',
'--set',
setPath,
'spawn',
device.id,
'defaults',
'write',
'com.apple.keyboard.preferences',
key,
'-bool',
'YES',
];

const writtenKeys = (calls: string[][]) =>
calls.filter((args) => args.includes('defaults')).map((args) => args.at(-3));

async function prepare(failKey?: string): Promise<string[][]> {
vi.mocked(runXcrun).mockImplementation(async (args) => {
if (failKey && args.includes(failKey)) throw new Error('denied');
return { exitCode: 0, stdout: '', stderr: '' };
});
await prepareIosSimulatorKeyboardIntros(device);
return vi.mocked(runXcrun).mock.calls.map(([args]) => [...args]);
}

test('marks both intros as shown on a simulator whose preferences file is missing', async () => {
assert.deepEqual(await prepare(), [
keyWrite('DidShowContinuousPathIntroduction'),
keyWrite('MultilingualKeyboardTip'),
]);
});

for (const [label, preferences, expected] of [
[
'both keys are on',
{ DidShowContinuousPathIntroduction: true, MultilingualKeyboardTip: true },
[],
],
['one key is on', { DidShowContinuousPathIntroduction: true }, ['MultilingualKeyboardTip']],
['a key is 1', { DidShowContinuousPathIntroduction: 1, MultilingualKeyboardTip: true }, []],
[
'a key is off',
{ DidShowContinuousPathIntroduction: false, MultilingualKeyboardTip: true },
['DidShowContinuousPathIntroduction'],
],
] as const) {
test(`writes only the missing keys when ${label} on this host`, async () => {
writePreferences(preferences);
assert.deepEqual(writtenKeys(await prepare()), expected);
});
}

test('reads a binary preferences file', async () => {
fs.copyFileSync(
new URL('./fixtures/keyboard-intros-shown.plist', import.meta.url),
path.join(preferencesDir(), 'com.apple.keyboard.preferences.plist'),
);
assert.deepEqual(await prepare(), []);
});

test('each write is bounded by the keyboard timeout, not the accessibility one', async () => {
await prepare();
assert.deepEqual(
vi.mocked(runXcrun).mock.calls.map(([, options]) => options),
[{ timeoutMs: 15_000 }, { timeoutMs: 15_000 }],
);
});

const scoped = <T>(task: () => Promise<T>) =>
withAppleToolProvider({} as Parameters<typeof withAppleToolProvider>[0], task);

test('a scoped (remote) tool provider writes even when this host has both keys', async () => {
writePreferences({ DidShowContinuousPathIntroduction: true, MultilingualKeyboardTip: true });
assert.deepEqual(writtenKeys(await scoped(() => prepare())), [
'DidShowContinuousPathIntroduction',
'MultilingualKeyboardTip',
]);
});

test('a failed write warns with its key and still writes the other key', async () => {
const calls = await prepare('DidShowContinuousPathIntroduction');
assert.deepEqual(writtenKeys(calls), [
'DidShowContinuousPathIntroduction',
'MultilingualKeyboardTip',
]);
assert.deepEqual(
vi
.mocked(emitDiagnostic)
.mock.calls.map(([event]) => [
event.level,
event.phase,
(event.data as { key?: string }).key,
]),
[['warn', 'ios_simulator_keyboard_intro_prepare_failed', 'DidShowContinuousPathIntroduction']],
);
});

for (const other of [
IOS_TEST_DEVICE,
MACOS_TEST_DEVICE,
{ ...IOS_TEST_SIMULATOR, appleOs: 'tvos' },
{ ...IOS_TEST_SIMULATOR, appleOs: 'visionos' },
] as DeviceInfo[]) {
test(`does not write keyboard preferences for ${other.kind}/${other.appleOs}`, async () => {
device = other;
assert.deepEqual(await prepare(), []);
});
}

for (const app of ['com.example.app', 'myapp://home']) {
test(`open marks the intros after boot and before launching ${app}`, async () => {
let booted = false;
vi.mocked(ensureBootedSimulator).mockImplementation(async () => {
booted = true;
});
const writeBootStates: boolean[] = [];
await withFakeAppleTool(
(args) => {
if (args.includes('defaults')) writeBootStates.push(booted);
return '';
},
async ({ calls }) => {
await openIosApp(device, app, { appBundleId: 'com.example.app' });
assert.deepEqual(writeBootStates, [true, true]);
const launch = calls.findIndex((args) => args[3] === 'launch' || args[3] === 'openurl');
assert.deepEqual(writtenKeys(calls.slice(0, launch)), [
'DidShowContinuousPathIntroduction',
'MultilingualKeyboardTip',
]);
},
);
});
}

test('a guest write that exits non-zero warns with its key', async () => {
await withFakeAppleTool(
(args) => (args.includes('MultilingualKeyboardTip') ? { exitCode: 1, stderr: 'denied' } : ''),
async () => {
await prepareIosSimulatorKeyboardIntros(device);
},
);
assert.deepEqual(
vi.mocked(emitDiagnostic).mock.calls.map(([event]) => (event.data as { key?: string }).key),
['MultilingualKeyboardTip'],
);
});

test('a failed write does not block the launch', async () => {
await withFakeAppleTool(
(args) => (args.includes('defaults') ? { exitCode: 1, stderr: 'denied' } : ''),
async ({ calls }) => {
await openIosApp(device, 'com.example.app', { appBundleId: 'com.example.app' });
assert.equal(calls.at(-1)?.[3], 'launch');
},
);
});

test('open <app> <url> that launches the app first marks the intros once', async () => {
vi.mocked(runXcrun).mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' });
await openIosApp(device, 'MyApp', {
appBundleId: 'com.example.app',
url: 'https://example.com/item',
launchArgs: ['-Flag', 'YES'],
});
assert.deepEqual(
vi.mocked(runXcrun).mock.calls.map(([args]) => args[3]),
['spawn', 'spawn', 'launch', 'openurl'],
);
});
25 changes: 20 additions & 5 deletions packages/platform-apple/src/core/app-launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ export async function openIosApp(
await terminateIosSimulatorApp(device, bundleId);
}
}
await openIosSimulatorUrl(device, explicitUrl, undefined, options?.runnerOptions);
// An app launched first has already marked the keyboard intros for this open.
await openIosSimulatorUrl(device, explicitUrl, undefined, options?.runnerOptions, {
keyboardPrepared: shouldLaunchAppBeforeUrl,
});
return;
}
const appBundleId = options?.appBundleId ?? (await resolveIosApp(device, app));
Expand Down Expand Up @@ -168,13 +171,13 @@ async function openIosSimulatorUrl(
url: string,
launchArgs: string[] | undefined,
runnerOptions?: AppleRunnerCommandOptions,
{ keyboardPrepared = false } = {},
): Promise<void> {
if (launchArgs && launchArgs.length > 0) {
throw new AppError('INVALID_ARGS', IOS_SIMULATOR_LAUNCH_ARGS_WITH_URL_MESSAGE);
}
await ensureBootedSimulator(device);
const { prepareIosSimulatorAccessibility } = await import('./ios-simulator-accessibility.ts');
await prepareIosSimulatorAccessibility(device);
await prepareIosSimulatorForLaunch(device, { keyboard: !keyboardPrepared });
const args = buildSimctlArgsForDevice(device, ['openurl', device.id, url]);
try {
await runXcrun(args, {
Expand All @@ -198,6 +201,19 @@ async function openIosSimulatorUrl(
}
}

async function prepareIosSimulatorForLaunch(
device: DeviceInfo,
options: { keyboard: boolean },
): Promise<void> {
const keyboard = options.keyboard
? import('./ios-simulator-keyboard.ts').then((module) =>
module.prepareIosSimulatorKeyboardIntros(device),
)
: undefined;
const { prepareIosSimulatorAccessibility } = await import('./ios-simulator-accessibility.ts');
await Promise.all([keyboard, prepareIosSimulatorAccessibility(device)]);
}

export async function openIosDevice(device: DeviceInfo): Promise<void> {
if (isMacOs(device)) {
return;
Expand Down Expand Up @@ -273,8 +289,7 @@ async function launchIosSimulatorApp(
): Promise<void> {
await assertNotSystemSurfaceHost(bundleId);
await ensureBootedSimulator(device);
const { prepareIosSimulatorAccessibility } = await import('./ios-simulator-accessibility.ts');
await prepareIosSimulatorAccessibility(device);
await prepareIosSimulatorForLaunch(device, { keyboard: true });

let consecutiveFBSFailures = 0;
const MAX_CONSECUTIVE_FBS_FAILURES = 3;
Expand Down
52 changes: 15 additions & 37 deletions packages/platform-apple/src/core/ios-simulator-accessibility.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import path from 'node:path';
import { isHandheldAppleSimulator, type DeviceInfo } from '@agent-device/kernel/device';
import { normalizeError } from '@agent-device/kernel/errors';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import { hostHomeDirectory, readHostBinaryFile } from '@agent-device/host-kit/host-file';
import { parseApplePlist } from './plist.ts';
import { buildSimctlArgsForDevice, simulatorAddressFor } from './simctl.ts';
import { hasScopedAppleToolProvider, runXcrun } from './tool-provider.ts';
import {
enableSimulatorBoolPreference,
readHostSimulatorPreferences,
} from './simulator-preferences.ts';

const ACCESSIBILITY_PREPARE_TIMEOUT_MS = 2_000;

Expand All @@ -15,19 +14,11 @@ const ACCESSIBILITY_PREPARE_TIMEOUT_MS = 2_000;
*/
export async function enableIosSimulatorAppAccessibility(device: DeviceInfo): Promise<void> {
if (!isHandheldAppleSimulator(device)) return;
await runXcrun(
buildSimctlArgsForDevice(device, [
'spawn',
device.id,
'defaults',
'write',
'com.apple.Accessibility',
'ApplicationAccessibilityEnabled',
'-bool',
'YES',
]),
{ timeoutMs: ACCESSIBILITY_PREPARE_TIMEOUT_MS },
);
await enableSimulatorBoolPreference(device, {
domain: 'com.apple.Accessibility',
key: 'ApplicationAccessibilityEnabled',
timeoutMs: ACCESSIBILITY_PREPARE_TIMEOUT_MS,
});
}

/**
Expand Down Expand Up @@ -57,23 +48,10 @@ export async function prepareIosSimulatorAccessibility(device: DeviceInfo): Prom
async function readHostAppAccessibility(
device: DeviceInfo,
): Promise<'enabled' | 'disabled' | 'unknown'> {
if (hasScopedAppleToolProvider()) return 'unknown';
try {
const { udid, simulatorSetPath } = simulatorAddressFor(device);
const setPath =
simulatorSetPath ?? path.join(hostHomeDirectory(), 'Library/Developer/CoreSimulator/Devices');
const preferences = path.join(
setPath,
udid,
'data/Library/Preferences/com.apple.Accessibility.plist',
);
const parsed = await parseApplePlist(await readHostBinaryFile(preferences));
if (!parsed) return 'unknown';
const value = parsed.ApplicationAccessibilityEnabled;
if (value === undefined || value === true || value === 1) return 'enabled';
if (value === false || value === 0) return 'disabled';
return 'unknown';
} catch {
return 'unknown';
}
const parsed = await readHostSimulatorPreferences(device, 'com.apple.Accessibility');
if (!parsed) return 'unknown';
const value = parsed.ApplicationAccessibilityEnabled;
if (value === undefined || value === true || value === 1) return 'enabled';
if (value === false || value === 0) return 'disabled';
return 'unknown';
}
Loading
Loading