diff --git a/apple/fold-helper/Fold.m b/apple/fold-helper/Fold.m index 60ba17772c..c0c4bba88e 100644 --- a/apple/fold-helper/Fold.m +++ b/apple/fold-helper/Fold.m @@ -5,12 +5,14 @@ #import #import -// Private simulator HID entry points. `set` and `rotate` only dispatch; `hinge` and `panels` only -// observe, so the host verifies a pose with a separate process that never sends HID. +// Private simulator HID entry points. `set`, `rotate`, and `home` only dispatch; `hinge` and +// `panels` only observe, so the host verifies a pose with a separate process that never sends HID. extern CFDataRef IOCFSerialize(CFTypeRef object, CFOptionFlags options); extern CFTypeRef IOHIDEventCreateVendorDefinedEvent(CFAllocatorRef allocator, uint64_t timestamp, uint32_t usagePage, uint32_t usage, uint32_t version, const uint8_t *data, CFIndex length, uint32_t options); +extern CFTypeRef IOHIDEventCreateKeyboardEvent(CFAllocatorRef allocator, uint64_t timestamp, + uint32_t usagePage, uint32_t usage, Boolean down, uint32_t options); extern CFTypeRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator); extern void IOHIDEventSystemClientDispatchEvent(CFTypeRef client, CFTypeRef event); @@ -121,6 +123,35 @@ static int runRotate(NSString *orientation) { }); } +static BOOL sendHomeKey(CFTypeRef client, Boolean down) { + // Consumer page Menu is the Home button. XCUIDevice's home press never reaches SpringBoard on + // a foldable simulator (measured on iPhone Duo), while this key does. + CFTypeRef event = IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), + 0x0c, 0x40, down, 0); + if (!event) return NO; + IOHIDEventSystemClientDispatchEvent(client, event); + CFRelease(event); + return YES; +} + +// One press goes home; two quick presses open the app switcher. +static int runHome(NSString *argument) { + int presses = [argument isEqualToString:@"1"] ? 1 : [argument isEqualToString:@"2"] ? 2 : 0; + if (presses == 0) { + fprintf(stderr, "Expected 1 or 2 home presses\n"); + return 2; + } + return dispatchEvents(^BOOL(CFTypeRef client) { + for (int press = 0; press < presses; press++) { + if (press > 0) usleep(150000); + if (!sendHomeKey(client, true)) return NO; + usleep(80000); + if (!sendHomeKey(client, false)) return NO; + } + return YES; + }); +} + static BOOL responds(id target, SEL selector) { return target != nil && [target respondsToSelector:selector]; } @@ -260,12 +291,13 @@ int main(int argc, const char *argv[]) { NSString *mode = argc >= 2 ? @(argv[1]) : nil; if ([mode isEqualToString:@"set"] && argc == 3) return runSet(@(argv[2])); if ([mode isEqualToString:@"rotate"] && argc == 3) return runRotate(@(argv[2])); + if ([mode isEqualToString:@"home"] && argc == 3) return runHome(@(argv[2])); if ([mode isEqualToString:@"hinge"] && (argc == 2 || argc == 3)) { return readHinge(argc == 3 ? @(argv[2]) : nil); } if ([mode isEqualToString:@"panels"] && argc == 2) return readPanels(); fprintf(stderr, - "Usage: fold-helper set | rotate | hinge [window-ms] | panels\n"); + "Usage: fold-helper set | rotate | home <1|2> | hinge [window-ms] | panels\n"); return 2; } } diff --git a/packages/platform-apple/src/core/__tests__/display-inventory.test.ts b/packages/platform-apple/src/core/__tests__/display-inventory.test.ts index 25cf1a1c8d..18bdd5be08 100644 --- a/packages/platform-apple/src/core/__tests__/display-inventory.test.ts +++ b/packages/platform-apple/src/core/__tests__/display-inventory.test.ts @@ -843,6 +843,7 @@ describe('scoped simulator panel table', () => { const foldHelper = { setPose: vi.fn(), rotate: vi.fn(), + pressHome: vi.fn(), readHingeAngle: vi.fn(), readPanelPayload, }; @@ -864,6 +865,7 @@ describe('scoped simulator panel table', () => { const foldHelper = { setPose: vi.fn(), rotate: vi.fn(), + pressHome: vi.fn(), readHingeAngle: vi.fn(), readPanelPayload, }; diff --git a/packages/platform-apple/src/foldable/fold-helper-home.test.ts b/packages/platform-apple/src/foldable/fold-helper-home.test.ts new file mode 100644 index 0000000000..cab6ee62bc --- /dev/null +++ b/packages/platform-apple/src/foldable/fold-helper-home.test.ts @@ -0,0 +1,75 @@ +import fs from 'node:fs'; +import { beforeEach, expect, test, vi } from 'vitest'; +import { bindTestCommandHost, createLiveTestHostEnvironment } from '@agent-device/test-kit'; + +vi.mock('./fold-helper-cache.ts', () => ({ + ensureFoldHelperBinary: vi.fn(async () => ({ path: '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/cache/fold-helper' })), +})); +vi.mock('../core/runner-client.ts', () => ({ + runAppleRunnerCommand: vi.fn(async () => ({})), +})); + +import type { DeviceInfo } from '@agent-device/kernel/device'; +import type { Interactor } from '@agent-device/contracts/interactor-types'; +import { runAppleRunnerCommand } from '../core/runner-client.ts'; +import { createLocalAppleToolProvider, withAppleToolProvider } from '../core/tool-provider.ts'; +import { createAppleInteractor } from '../interactor.ts'; +import { IOS_SIMULATOR } from '../__tests__/device-fixtures.ts'; +import { IPHONE_17_SINGLE_PANEL, IPHONE_DUO_CLOSED } from '../__tests__/display-fixtures.ts'; + +bindTestCommandHost(); + +const mockRunner = vi.mocked(runAppleRunnerCommand); + +beforeEach(() => { + mockRunner.mockClear(); +}); + +/** A fresh simulator id per test: the daemon keeps each simulator's resolved panel count. */ +let simulatorCount = 0; +function simulator(): DeviceInfo { + simulatorCount += 1; + return { ...IOS_SIMULATOR, id: `${IOS_SIMULATOR.id}-home-${simulatorCount}` }; +} + +/** Runs `use` on an interactor whose simulator reports `panels`, and records the helper modes. */ +async function run(panels: object, use: (interactor: Interactor) => Promise) { + const device = simulator(); + const helpers: string[][] = []; + const provider = createLocalAppleToolProvider({ + runCommand: async (_command, args) => { + if (args.slice(0, 4).join(' ') === 'devicectl device info displays') { + fs.writeFileSync(args.at(-1)!, JSON.stringify(panels)); + return { stdout: '', stderr: '', exitCode: 0 }; + } + const spawn = args.slice(args.indexOf('spawn')); + expect(spawn.slice(0, 3)).toEqual(['spawn', device.id, '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/cache/fold-helper']); + helpers.push(spawn.slice(3)); + return { stdout: '', stderr: '', exitCode: 0 }; + }, + }); + await withAppleToolProvider(provider, () => + use(createAppleInteractor(device, {}, createLiveTestHostEnvironment())), + ); + return helpers; +} + +test.each([ + ['home', (i: Interactor) => i.home!(), ['home', '1']], + ['appSwitcher', (i: Interactor) => i.appSwitcher!(), ['home', '2']], +] as const)('%s on a foldable simulator presses Home through HID', async (_name, use, mode) => { + await expect(run(IPHONE_DUO_CLOSED, use)).resolves.toEqual([mode]); + expect(mockRunner).not.toHaveBeenCalled(); +}); + +test.each([ + ['home', (i: Interactor) => i.home!()], + ['appSwitcher', (i: Interactor) => i.appSwitcher!()], +] as const)('%s on a single-panel simulator keeps the runner press', async (command, use) => { + await expect(run(IPHONE_17_SINGLE_PANEL, use)).resolves.toEqual([]); + expect(mockRunner).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ command }), + expect.anything(), + ); +}); diff --git a/packages/platform-apple/src/foldable/fold-helper.test.ts b/packages/platform-apple/src/foldable/fold-helper.test.ts index f39a622f22..32026cd9b4 100644 --- a/packages/platform-apple/src/foldable/fold-helper.test.ts +++ b/packages/platform-apple/src/foldable/fold-helper.test.ts @@ -132,6 +132,31 @@ test('rotate dispatches every picker value, upside-down included', async () => { ]); }); +test('pressHome spawns home mode with the press count', async () => { + const { calls } = await withHelper(scopedDuo, { stdout: '', exitCode: 0 }, async (helper) => { + await helper.pressHome(1); + await helper.pressHome(2); + }); + expect(calls.map((call) => call.args.slice(-2))).toEqual([ + ['home', '1'], + ['home', '2'], + ]); +}); + +test('pressHome maps a failed helper exit to its dispatch-failed reason', async () => { + const { value } = await withHelper(scopedDuo, { stdout: '', exitCode: 1 }, (helper) => + caught(helper.pressHome(1)), + ); + expect(value).toMatchObject({ + code: 'COMMAND_FAILED', + details: { + reason: 'home-hid-dispatch-failed', + deviceId: 'scoped-duo', + dispatched: 'unknown', + }, + }); +}); + test('reads one guest hinge sample without sending HID', async () => { const { value, calls } = await withHelper( scopedDuo, @@ -243,6 +268,12 @@ test.each([ 'orientation-hid-dispatch-timed-out', { dispatched: 'unknown' }, ], + [ + 'pressHome', + (helper: FoldHelper) => helper.pressHome(2), + 'home-hid-dispatch-timed-out', + { dispatched: 'unknown' }, + ], ] as const)('%s maps a helper timeout to its typed reason', async (_mode, use, reason, extra) => { const value = await withAppleToolProvider( createLocalAppleToolProvider({ diff --git a/packages/platform-apple/src/foldable/fold-helper.ts b/packages/platform-apple/src/foldable/fold-helper.ts index e5922bcf89..2ac2277eba 100644 --- a/packages/platform-apple/src/foldable/fold-helper.ts +++ b/packages/platform-apple/src/foldable/fold-helper.ts @@ -27,6 +27,13 @@ const FOLD_HELPER_ORIENTATION_REASONS = { hidDispatchTimedOut: { reason: 'orientation-hid-dispatch-timed-out' }, } as const satisfies ReasonTable<'orientation'>; +const FOLD_HELPER_HOME_REASONS = { + // The fold helper could not send the Home button to the iOS simulator. + hidDispatchFailed: { reason: 'home-hid-dispatch-failed' }, + // The fold helper did not finish sending the Home button in time, so the press may have applied. + hidDispatchTimedOut: { reason: 'home-hid-dispatch-timed-out' }, +} as const satisfies ReasonTable<'home'>; + const FOLD_HELPER_PANEL_REASONS = { // The fold helper returned no panel table for the iOS simulator. panelsUnreadable: { reason: 'fold-helper-panels-unreadable' }, @@ -35,6 +42,7 @@ const FOLD_HELPER_PANEL_REASONS = { type FoldHelperFailureReason = | (typeof FOLD_HELPER_REASONS)[keyof typeof FOLD_HELPER_REASONS]['reason'] | (typeof FOLD_HELPER_ORIENTATION_REASONS)[keyof typeof FOLD_HELPER_ORIENTATION_REASONS]['reason'] + | (typeof FOLD_HELPER_HOME_REASONS)[keyof typeof FOLD_HELPER_HOME_REASONS]['reason'] | (typeof FOLD_HELPER_PANEL_REASONS)[keyof typeof FOLD_HELPER_PANEL_REASONS]['reason']; const HINGE_ANGLE_NO_SAMPLE_HINT = @@ -58,14 +66,16 @@ export type SimulatorPanelPayload = { result: { displays: unknown[] } }; /** * The fold helper bound to one simulator. Every mode is a separate `simctl spawn` of the cached - * binary, so it reaches a simulator in any device set. `setPose` and `rotate` only dispatch HID; - * the reads only observe, so a pose is verified by a process that never sent it. + * binary, so it reaches a simulator in any device set. `setPose`, `rotate`, and `pressHome` only + * dispatch HID; the reads only observe, so a pose is verified by a process that never sent it. */ export type FoldHelper = Readonly<{ /** Dispatches a preset pose or a keyframe trajectory through simulator HID. */ setPose(pose: FoldPose | readonly FoldKeyframe[], signal?: AbortSignal): Promise; /** Dispatches one picker value through the same simulator HID control channel. */ rotate(orientation: FoldPickerValue, signal?: AbortSignal): Promise; + /** Presses the Home button through simulator HID: once for home, twice for the app switcher. */ + pressHome(presses: 1 | 2, signal?: AbortSignal): Promise; /** * One fresh CoreMotion `CMAngleManager` subscription, the source `devicectl device motion * hinge-angle` relays. It reports the latest sample once `windowMs` has passed since the first, @@ -148,6 +158,13 @@ export function createFoldHelper(device: DeviceInfo): FoldHelper { () => true, ); }, + async pressHome(presses, signal) { + await run( + ['home', String(presses)], + { signal, timeoutMs: 5_000, failure: HOME_FAILURE }, + () => true, + ); + }, async readHingeAngle({ signal, windowMs = 0 } = {}) { return await run( ['hinge', String(windowMs)], @@ -215,6 +232,20 @@ const ROTATE_FAILURE: ModeFailure = { }, }; +const HOME_FAILURE: ModeFailure = { + message: 'Unable to send the simulator Home button', + // A failure on the second press or a key-up comes after a press already went out. + details: { reason: FOLD_HELPER_HOME_REASONS.hidDispatchFailed.reason, dispatched: 'unknown' }, + timedOut: { + message: 'Timed out sending the simulator Home button; the press may have applied', + details: { + reason: FOLD_HELPER_HOME_REASONS.hidDispatchTimedOut.reason, + dispatched: 'unknown', + hint: 'Check the foreground app with appstate or a screenshot before you press Home again.', + }, + }, +}; + const NO_SAMPLE_FAILURE: ModeFailure = { message: 'The simulator reported no hinge angle sample', details: { diff --git a/packages/platform-apple/src/foldable/orientation.ts b/packages/platform-apple/src/foldable/orientation.ts index 728f68ed21..dbc30c7c5a 100644 --- a/packages/platform-apple/src/foldable/orientation.ts +++ b/packages/platform-apple/src/foldable/orientation.ts @@ -52,9 +52,11 @@ function recordResolvedRead(device: DeviceInfo, read: number): void { } /** - * Whether a rotation must go through guest HID: a simulator the `fold` fact admits that has more - * than one integrated panel. XCUIDevice rotation has no effect there, and its readback repeats - * the requested value. + * Whether rotation, Home, and the app switcher must go through guest HID: a simulator the `fold` + * fact admits that has more than one integrated panel. XCUIDevice rotation and Home presses have no + * effect there, and the rotation readback repeats the requested value. It ignores the surface + * back-off of {@link readFoldablePanelTable}: a missed read must not send a foldable's input to + * XCUIDevice, where it reports success and does nothing. */ export async function isAppleFoldableSimulator( device: DeviceInfo, diff --git a/packages/platform-apple/src/foldable/pose.test.ts b/packages/platform-apple/src/foldable/pose.test.ts index 5f0492c29f..830d3437c4 100644 --- a/packages/platform-apple/src/foldable/pose.test.ts +++ b/packages/platform-apple/src/foldable/pose.test.ts @@ -4,6 +4,7 @@ const { FOLD_HELPER } = vi.hoisted(() => ({ FOLD_HELPER: { setPose: vi.fn(), rotate: vi.fn(), + pressHome: vi.fn(), readHingeAngle: vi.fn(), readPanelPayload: vi.fn(), }, diff --git a/packages/platform-apple/src/interactor.ts b/packages/platform-apple/src/interactor.ts index 1a6fc51624..06eec5e1e1 100644 --- a/packages/platform-apple/src/interactor.ts +++ b/packages/platform-apple/src/interactor.ts @@ -11,6 +11,7 @@ import { runMacOsScreenshotAction } from './os/macos/helper.ts'; import { actOnAppleAlert, awaitAppleAlert, readAppleAlertStatus } from './alert.ts'; import { runAppleRunnerCommand } from './core/runner-client.ts'; import { isAppleFoldableSimulator, setAppleFoldableOrientation } from './foldable/orientation.ts'; +import { createFoldHelper } from './foldable/fold-helper.ts'; import { shakeIosSimulator } from './navigation/shake.ts'; import { withAppleRunnerProvider, @@ -164,6 +165,10 @@ export function createAppleInteractor( ); return; } + // XCUIDevice's home press never reaches SpringBoard on a foldable simulator. + if (await isAppleFoldableSimulator(device, runnerOpts.signal)) { + return await createFoldHelper(device).pressHome(1, runnerOpts.signal); + } await runAppleRunnerCommand( device, { command: 'home', appBundleId: runnerContext.appBundleId }, @@ -179,6 +184,9 @@ export function createAppleInteractor( return await setRunnerOrientation(device, orientation, runnerContext, runnerOpts); }, appSwitcher: async () => { + if (await isAppleFoldableSimulator(device, runnerOpts.signal)) { + return await createFoldHelper(device).pressHome(2, runnerOpts.signal); + } await runAppleRunnerCommand( device, { command: 'appSwitcher', appBundleId: runnerContext.appBundleId }, diff --git a/src/commands/schema/cli-help-foldable.ts b/src/commands/schema/cli-help-foldable.ts index 978941d7a1..8cb5d631c8 100644 --- a/src/commands/schema/cli-help-foldable.ts +++ b/src/commands/schema/cli-help-foldable.ts @@ -17,5 +17,9 @@ Changing the pose: Requirements: an iOS simulator session on a foldable device and an Xcode toolchain with the iOS simulator SDK and foldable HID support (verified on Xcode 27.1). Device Hub and host Accessibility permission are not required. The command runs a small helper through simctl spawn for the session UDID; the helper is built once per Fold.m source hash and Xcode toolchain, cached under ~/.agent-device/fold-helper, and rebuilt only when the source or the toolchain changes. The same helper reads the hinge and the panels in either simulator set. Build or dispatch failures are reported without a UI fallback. The app under test reads the resulting pose as UIHinge.status. Android emulators: fold sets the posture through the emulator console (adb emu posture 1|2|3), then reads adb shell cmd device_state print-state until the guest commits CLOSED, HALF_OPENED, or OPENED, and reports the angle read from the hinge sensor. It can differ from the AVD profile's per-posture angles: 0, 90 and 180 degrees on the Pixel folds, 15, 90 and 165 on the generic 7.6in Foldable. Folding to the cover display can raise Android's "Swipe up to continue" lock screen; fold dismisses it so the app stays reachable. An emulator profile without those device states (a phone) fails with UNSUPPORTED_OPERATION and reason single-panel-device, and a physical device is refused. Keyframes are not supported on Android, and the response carries no panel geometry: re-snapshot after every fold. - If a task asserts behavior for more than one pose, fold to each pose and re-snapshot, and report which poses the run covered.`, + If a task asserts behavior for more than one pose, fold to each pose and re-snapshot, and report which poses the run covered. + +Home and app switcher: + On a foldable iOS simulator, home and app-switcher press the Home button through the same helper's simulator HID, once for home and twice for the app switcher, because the XCUITest Home press does not reach the home screen there. Verified closed, half-open, and open. The first press on a host or Xcode builds the helper and takes longer. + Split View on the open device: run open com.apple.springboard, longpress an app icon, press "Open in Split View", then press the icon of the second app. Take the labels from snapshot -i.`, } as const; diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index ee144eb04e..c87f62c998 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -396,6 +396,7 @@ Exact behavior: `agent-device help fold`. - `fold closed|half-open|open` sets the pose of an iPhone Duo simulator or a foldable Android emulator, such as `pixel_9_pro_fold`. It reports the pose only after the device confirms it. Physical devices are refused. - Take a new snapshot after every fold, even a failed one. Refs and coordinates from before it are stale. - On iOS, `fold` needs an Xcode with foldable HID support. The first fold on a host or Xcode builds a helper and takes longer. The response's panel size is not the next snapshot's viewport, so do not use it to place a tap. +- On a foldable iOS simulator, `home` and `app-switcher` press the Home button through the same helper, because the XCUITest Home press does not reach the home screen there. The first press on a host or Xcode builds the helper and takes longer. - `--keyframes` plays a timed hinge trajectory on iOS only, for example `fold --keyframes '[{"atMs":0,"angle":0},{"atMs":1667,"angle":160},{"atMs":5000,"angle":180}]'`. - For failure reasons, see [error reasons](/docs/error-reasons). For panels and poses, see `agent-device help foldable`. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 4958f8ac41..ca3e00bb10 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -149,6 +149,13 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `GESTURE_TRAJECTORY_NON_FINITE` | A trajectory sample carries a non-finite coordinate. | | `GESTURE_TRAJECTORY_OUT_OF_BOUNDS` | A trajectory sample leaves the viewport, so the contact would press outside the screen, or a two-finger path cannot keep its contacts the minimum span apart inside it. | +### `home` + +| Reason | Meaning | +| --- | --- | +| `home-hid-dispatch-failed` | The fold helper could not send the Home button to the iOS simulator. | +| `home-hid-dispatch-timed-out` | The fold helper did not finish sending the Home button in time, so the press may have applied. | + ### `install-from-source` | Reason | Meaning |