Skip to content

Commit 4b87e09

Browse files
committed
fix(apple): refuse fold on a scoped simulator set at runtime admission
fold on an iPhone Duo inside --ios-simulator-device-set failed after the HID send because CoreDevice's display inventory and hinge-angle readback resolve a scoped simulator as not found, so ADR 0025's post-dispatch verification is impossible. Refuse it instead at the owning setFoldPose fact when device.simulatorSetPath is present, with the typed unsupported-device-scope reason; the routed response derives the same reason and a hint naming the set. The default set and the existing kind/OS refusals are unchanged.
1 parent f47e9c9 commit 4b87e09

9 files changed

Lines changed: 167 additions & 4 deletions

File tree

‎packages/contracts/src/platform-runtime.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ export type RuntimeOperationUnavailability = Readonly<{
126126
| 'unsupported-platform-leaf'
127127
| 'unsupported-device-kind'
128128
| 'unsupported-device-backend'
129+
| 'unsupported-device-scope'
129130
| 'unsupported-provider-mode'
130131
| 'owner-capability-missing';
131132
hint?: string;
@@ -406,6 +407,7 @@ function isRuntimeOperationUnavailabilityReason(
406407
value === 'unsupported-platform-leaf' ||
407408
value === 'unsupported-device-kind' ||
408409
value === 'unsupported-device-backend' ||
410+
value === 'unsupported-device-scope' ||
409411
value === 'unsupported-provider-mode' ||
410412
value === 'owner-capability-missing'
411413
);
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { beforeEach, expect, test, vi } from 'vitest';
2+
3+
vi.mock('./pose.ts', () => ({ setAppleFoldPose: vi.fn() }));
4+
5+
import {
6+
localRuntimeOwner,
7+
narrowDeviceBinding,
8+
type DeviceBinding,
9+
type RuntimeFacts,
10+
} from '@agent-device/contracts/platform-runtime';
11+
import {
12+
foldRuntimeUse,
13+
type PlatformRuntimeOperations,
14+
} from '@agent-device/contracts/platform-runtime-operations';
15+
import { deviceShape, type DeviceInfo } from '@agent-device/kernel/device';
16+
17+
import { appleFoldableFacts, createAppleFoldableOperations } from './runtime.ts';
18+
import { setAppleFoldPose } from './pose.ts';
19+
20+
const mockPose = vi.mocked(setAppleFoldPose);
21+
22+
const duo: DeviceInfo = {
23+
platform: 'apple',
24+
appleOs: 'ios',
25+
id: '4F879835-4AB3-4046-B033-5AB769209DD4',
26+
name: 'iPhone Duo',
27+
kind: 'simulator',
28+
target: 'mobile',
29+
booted: true,
30+
};
31+
const scopedDuo: DeviceInfo = { ...duo, simulatorSetPath: '/tmp/scoped-set' };
32+
33+
/** A full owner binding whose fold cell is derived only from the fact under test. */
34+
function foldBinding(device: DeviceInfo): DeviceBinding<PlatformRuntimeOperations> {
35+
const { setFoldPose } = appleFoldableFacts(device);
36+
return {
37+
device,
38+
owner: localRuntimeOwner('apple'),
39+
facts: {
40+
device: { ...deviceShape(device), providerMode: 'local' },
41+
operations: { setFoldPose } as RuntimeFacts<PlatformRuntimeOperations>['operations'],
42+
},
43+
operations: createAppleFoldableOperations({ device, signal: new AbortController().signal }),
44+
[Symbol.asyncDispose]: async () => {},
45+
};
46+
}
47+
48+
function thrownBy<T>(run: () => T): unknown {
49+
try {
50+
run();
51+
} catch (error) {
52+
return error;
53+
}
54+
throw new Error('expected the routed fold binding to refuse');
55+
}
56+
57+
beforeEach(() => {
58+
mockPose.mockReset();
59+
});
60+
61+
test('the default-set iPhone Duo admits setFoldPose and binds the pose operation', () => {
62+
expect(appleFoldableFacts(duo).setFoldPose).toEqual({ available: true });
63+
expect(
64+
createAppleFoldableOperations({ device: duo, signal: new AbortController().signal }),
65+
).toHaveProperty('setFoldPose', expect.any(Function));
66+
});
67+
68+
test('a scoped simulator set refuses setFoldPose with the typed unsupported-device-scope fact', () => {
69+
expect(appleFoldableFacts(scopedDuo).setFoldPose).toMatchObject({
70+
available: false,
71+
reason: 'unsupported-device-scope',
72+
hint: expect.stringContaining('/tmp/scoped-set'),
73+
});
74+
});
75+
76+
test('a scoped simulator set binds no pose operation and never reaches a hinge', () => {
77+
const operations = createAppleFoldableOperations({
78+
device: scopedDuo,
79+
signal: new AbortController().signal,
80+
});
81+
expect(operations).not.toHaveProperty('setFoldPose');
82+
expect(mockPose).not.toHaveBeenCalled();
83+
});
84+
85+
test('the routed fold response refuses a scoped simulator set with the typed reason before any tool call', () => {
86+
const refusal = thrownBy(() => narrowDeviceBinding(foldBinding(scopedDuo), foldRuntimeUse)) as {
87+
code?: string;
88+
details?: { reason?: string; hint?: string };
89+
};
90+
expect(refusal.code).toBe('UNSUPPORTED_OPERATION');
91+
expect(refusal.details?.reason).toBe('unsupported-device-scope');
92+
expect(refusal.details?.hint).toContain('/tmp/scoped-set');
93+
expect(mockPose).not.toHaveBeenCalled();
94+
});
95+
96+
test('a scoped set never outranks the existing kind and OS refusals', () => {
97+
expect(appleFoldableFacts({ ...scopedDuo, kind: 'device' }).setFoldPose).toMatchObject({
98+
available: false,
99+
reason: 'unsupported-device-kind',
100+
});
101+
expect(
102+
appleFoldableFacts({ ...scopedDuo, appleOs: 'tvos', target: 'tv' }).setFoldPose,
103+
).toMatchObject({ available: false, reason: 'unsupported-platform-leaf' });
104+
});

‎packages/platform-apple/src/foldable/runtime.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,33 @@ const foldOsUnavailable = Object.freeze({
1919
hint: 'fold poses the hinge of a foldable iPhone; tvOS, macOS, watchOS and visionOS simulators have no hinge.',
2020
} as const);
2121

22+
/**
23+
* A fold inside a scoped simulator set cannot verify its pose: the HID send honours `--set`, but
24+
* `devicectl device info displays` and `devicectl device motion hinge-angle` take only `--device`
25+
* and resolve a scoped simulator as `not found`, so ADR 0025's post-dispatch readback is impossible.
26+
* The refusal is the owning fact, before any display probe or HID effect; the default set is unaffected.
27+
*/
28+
function foldScopeUnavailable(simulatorSetPath: string) {
29+
return {
30+
available: false,
31+
reason: 'unsupported-device-scope',
32+
hint: `fold cannot resolve a simulator scoped to the set at "${simulatorSetPath}": CoreDevice's display inventory and hinge-angle readback need a simulator in the default set, so the pose could not be verified. Run fold without --ios-simulator-device-set.`,
33+
} as const;
34+
}
35+
2236
/**
2337
* The simulator leaf that can carry a hinge: iPhone and iPad. Which *model* inside it actually
2438
* folds is not in `DeviceInfo`, so the operation answers that from CoreDevice's display table and
2539
* refuses a single-panel simulator with a typed `UNSUPPORTED_OPERATION`, the way the runner
26-
* answers for the Action Button hardware.
40+
* answers for the Action Button hardware. A simulator scoped to a non-default set is refused here
41+
* too: its pose cannot be read back through CoreDevice, so no display probe or HID effect runs.
2742
*/
2843
function appleFoldFact(device: DeviceInfo): RuntimeOperationFact {
2944
if (device.kind !== 'simulator') return foldKindUnavailable;
3045
const os = resolveDeviceAppleOs(device);
31-
return os === 'ios' || os === 'ipados' ? available : foldOsUnavailable;
46+
if (os !== 'ios' && os !== 'ipados') return foldOsUnavailable;
47+
if (device.simulatorSetPath) return foldScopeUnavailable(device.simulatorSetPath);
48+
return available;
3249
}
3350

3451
/** The foldable cell: `setFoldPose`. */

‎packages/platform-apple/src/runtime.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,28 @@ test.each(Object.entries(leaves))(
282282
},
283283
);
284284

285+
// A simulator scoped to a non-default set is refused by the owner's own fact, before any display
286+
// probe or HID effect: CoreDevice's display inventory and hinge-angle readback cannot resolve it,
287+
// so ADR 0025's post-dispatch verification is impossible. The default-set iOS leaf stays admitted.
288+
test('refuses the fold fact for a scoped simulator set and binds no pose operation', async () => {
289+
const scoped = appleDevice({ simulatorSetPath: '/tmp/scoped-set' });
290+
const binding = await createApplePlatformRuntime(platformRuntimeHostFixture()).bind({
291+
device: scoped,
292+
intent: { kind: 'ordinary' },
293+
scope: {
294+
signal: new AbortController().signal,
295+
diagnostics: { emit: () => {} },
296+
progress: { report: () => {} },
297+
},
298+
});
299+
expect(binding.facts.operations.setFoldPose).toMatchObject({
300+
available: false,
301+
reason: 'unsupported-device-scope',
302+
hint: expect.stringContaining('/tmp/scoped-set'),
303+
});
304+
expect(binding.operations.setFoldPose).toBeUndefined();
305+
});
306+
285307
/**
286308
* The Action Button is a physical control on iPhone and iPad leaves only. visionOS is the leaf that
287309
* separates this from `orientation`'s mobile-input reading: a headset has a Digital Crown and no

‎src/commands/schema/cli-help.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -749,7 +749,7 @@ Screens are handled for you:
749749
750750
Changing the pose:
751751
agent-device fold closed | half-open | open
752-
fold sends a private HID hinge event inside the selected simulator and then reads the hinge angle back from CoreDevice until it agrees: closed is 0 degrees, open is 180, and half-open is any angle between them (requested at 130 degrees). An angle in that interval only proves the category, so half-open is reported once two consecutive readings both fall inside it and agree within 0.5 degrees. The response reports the verified pose, the hinge angle, and the panel the device now lights with its native panel point size, marked coordinateSpace "native-panel". That point size is the panel's own geometry, not the next snapshot's viewport, so it cannot place a tap: the active app window can differ (a 669x951 inner panel hosts a 951x669 window). A hinge whose last reading is some other pose fails with COMMAND_FAILED and reason fold-pose-unverified, naming the angle CoreDevice still reports; a hinge seen half-open but never at rest fails with reason fold-pose-unsettled, naming the observed and previous angles. A single-panel simulator fails with UNSUPPORTED_OPERATION.
752+
fold sends a private HID hinge event inside the selected simulator and then reads the hinge angle back from CoreDevice until it agrees: closed is 0 degrees, open is 180, and half-open is any angle between them (requested at 130 degrees). An angle in that interval only proves the category, so half-open is reported once two consecutive readings both fall inside it and agree within 0.5 degrees. The response reports the verified pose, the hinge angle, and the panel the device now lights with its native panel point size, marked coordinateSpace "native-panel". That point size is the panel's own geometry, not the next snapshot's viewport, so it cannot place a tap: the active app window can differ (a 669x951 inner panel hosts a 951x669 window). A hinge whose last reading is some other pose fails with COMMAND_FAILED and reason fold-pose-unverified, naming the angle CoreDevice still reports; a hinge seen half-open but never at rest fails with reason fold-pose-unsettled, naming the observed and previous angles. A single-panel simulator fails with UNSUPPORTED_OPERATION. A simulator scoped to a non-default set with --ios-simulator-device-set is refused before any hinge is touched, with UNSUPPORTED_OPERATION and reason unsupported-device-scope: the HID send honors the set, but CoreDevice's display inventory and hinge-angle readback resolve a scoped simulator as not found, so the pose could not be verified. Run fold without --ios-simulator-device-set (in the default set).
753753
Expect a fold to take 10-16 seconds: each hinge read is a five-second devicectl stream, and half-open waits for the hinge to stop moving. Re-snapshot after every fold; refs and coordinates from before it are stale, and the command's message says so.
754754
Timed motion: fold --keyframes '[{"atMs":0,"angle":0},{"atMs":5000,"angle":180}]'. Use 2–64 frames starting at 0ms, increasing integer timestamps up to 60000ms, and angles from 0 to 180. The last timestamp sets motion duration, excluding setup and verification. Equal angles hold; cancellation stops motion. See the fold examples in the command and Node API documentation for trajectories.
755755

‎src/commands/system/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ const homeCommandDescription =
7272
'Send the selected device to its home screen. This leaves the app session open but moves the foreground away from the app.';
7373
const orientationCommandDescription = 'Set device orientation on iOS and Android';
7474
const foldCommandDescription =
75-
'Fold or unfold a foldable iPhone simulator (iPhone Duo) into the closed, half-open, or open pose, or follow timestamped angle keyframes, by sending a simulator HID hinge event, then read the hinge angle back from CoreDevice to confirm it. A pose change moves the app to a different panel with a different point size, so every ref and coordinate from before it is stale: re-snapshot after this command. Taps, long presses, and scrolling target the app window on its current panel in closed, half-open, and open poses. Simulator-only; requires the iOS simulator SDK; Device Hub and host Accessibility permission are not required.';
75+
'Fold or unfold a foldable iPhone simulator (iPhone Duo) into the closed, half-open, or open pose, or follow timestamped angle keyframes, by sending a simulator HID hinge event, then read the hinge angle back from CoreDevice to confirm it. A pose change moves the app to a different panel with a different point size, so every ref and coordinate from before it is stale: re-snapshot after this command. Taps, long presses, and scrolling target the app window on its current panel in closed, half-open, and open poses. Simulator-only; requires the iOS simulator SDK; Device Hub and host Accessibility permission are not required. A simulator scoped to a non-default simulator set is refused with UNSUPPORTED_OPERATION and reason unsupported-device-scope before any hinge is touched, because CoreDevice cannot read back a scoped simulator; run fold against a simulator in the default set.';
7676
const appSwitcherCommandDescription =
7777
'Open the device app switcher to inspect or change foreground apps. This changes the visible system UI and may move focus away from the current app.';
7878
const keyboardCommandDescription =

‎src/daemon/__tests__/fold-runtime.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,12 @@ test('rejects an unavailable exact-owner fact before binding', async () => {
159159
command: 'fold',
160160
device: testDevice,
161161
unavailable,
162+
// The fold route derives its refusal from the fact, so the wire error keeps the typed reason.
163+
refusal: {
164+
code: 'UNSUPPORTED_OPERATION',
165+
message: 'fold is not supported on this device',
166+
details: { reason: 'unsupported-platform-leaf' },
167+
},
162168
});
163169
});
164170

‎src/daemon/fold-runtime.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
import { foldRuntimeUse } from '@agent-device/contracts/platform-runtime-operations';
99
import type { BoundDeviceRuntime } from '@agent-device/contracts/platform-runtime';
1010
import type { DeviceInfo } from '@agent-device/kernel/device';
11+
import { errorResponse } from '@agent-device/kernel/contracts';
1112
import { successText } from '@agent-device/kernel/success-text';
1213
import type { ResolvedGenericExecution } from './request-generic-dispatch.ts';
1314
import { resolveBoundGenericRuntime, type RuntimeAdmissionBindings } from './runtime-admission.ts';
@@ -43,6 +44,16 @@ export async function resolveBoundFoldRuntime(
4344
use: foldRuntimeUse,
4445
inspectFacts: params.inspectFacts,
4546
bindDevice: params.bindDevice,
47+
// Derive the refusal from the same `setFoldPose` fact that gates admission, so the command
48+
// response keeps the fact's typed reason (e.g. `unsupported-device-scope`) and hint rather
49+
// than the shared hint-only wording; capability and response never diverge.
50+
unavailableResponse: (unavailable) =>
51+
errorResponse(
52+
'UNSUPPORTED_OPERATION',
53+
'fold is not supported on this device',
54+
{ reason: unavailable.reason },
55+
unavailable.hint ? { hint: unavailable.hint } : undefined,
56+
),
4657
},
4758
(runtime) => executeSetFoldPose(runtime, input),
4859
);

‎website/docs/docs/commands.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ agent-device fold open
9393
- `fold <closed|half-open|open>` puts a foldable iPhone simulator (iPhone Duo) into a hinge pose. The command sends a private HID hinge event inside the selected simulator (ADR 0025), then reads the hinge angle back with `devicectl device motion hinge-angle` and reports the pose only when that reading agrees: `closed` is 0°, `open` is 180°, and `half-open` is any angle between them (requested at 130°). An angle inside that interval only proves the category, so `half-open` is reported once two consecutive readings both fall inside it and agree within 0.5°. The response names the panel the device now lights and its native panel point size, marked `coordinateSpace: "native-panel"`; that size is the panel's own geometry, not the next snapshot's viewport (a 669x951 inner panel can host a 951x669 app window), so it cannot place a tap. Re-snapshot afterwards, and never carry refs or coordinates across a `fold`. After that snapshot, taps, long presses, and scrolling follow the app window on the active panel in closed, half-open, and open poses.
9494
- For timed motion, use `fold --keyframes '[{"atMs":0,"angle":0},{"atMs":1667,"angle":160},{"atMs":3333,"angle":100},{"atMs":5000,"angle":180}]'`. This runs the opening/reversal/reopening sequence over five seconds. Supply either a preset or keyframes, never both. Use 2–64 keyframes starting at 0ms with strictly increasing integer timestamps up to 60,000ms and finite angles in 0–180°. Linear interpolation runs at roughly 60Hz; equal consecutive angles hold the hinge. Motion duration excludes preparation and final-angle verification. Cancellation stops at the current angle; re-snapshot even after an interrupted trajectory.
9595
- `fold` is simulator-only and requires an Xcode toolchain with the iOS simulator SDK and foldable HID support (verified on Xcode 27.1). It compiles a temporary helper and runs it against the session UDID. Device Hub and host Accessibility permission are not required. Build failures report `fold-helper-build-failed`; dispatch failures report `fold-hid-dispatch-failed`. There is no UI fallback. Single-panel simulators and physical devices are refused.
96+
- A simulator scoped to a non-default set with `--ios-simulator-device-set` is refused before any hinge is touched with `UNSUPPORTED_OPERATION` and `details.reason: "unsupported-device-scope"`. The HID send accepts `--set`, but `devicectl device info displays` and `devicectl device motion hinge-angle` accept only `--device` and resolve a scoped simulator as not found, so the pose could not be read back (ADR 0025). Run `fold` against a simulator in the default set.
9697
- `fold` costs one bounded hinge stream per read, and devicectl's smallest stream is five seconds: `closed` and `open` take about ten seconds, `half-open` about sixteen, because the hinge animates and the command waits for it to stop. A hinge whose last reading is some other pose fails with `COMMAND_FAILED` and `reason: fold-pose-unverified`, naming the angle CoreDevice still reports. A hinge seen `half-open` but never at rest fails with `reason: fold-pose-unsettled`, naming the observed and previous angles: the requested category was observed, and what is missing is a pose the hinge holds (#2730).
9798
- `action-button` is not a cheap command to loop. On an iPhone 17 Pro Simulator the press itself spent about five seconds inside XCUITest, while `home` and `app-switcher` on the same session took under two seconds each.
9899
- On iOS devices, `http(s)://` URLs open in Safari when no app is active. Custom scheme URLs require an active app in the session.

0 commit comments

Comments
 (0)