Repository navigation
Expand file tree
/
Copy pathpose.ts
More file actions
280 lines (258 loc) · 10.8 KB
/
Copy pathpose.ts
File metadata and controls
280 lines (258 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import {
type SetFoldPoseInput,
foldPoseForHingeAngle,
FOLD_SCREEN_COORDINATE_SPACE,
type FoldPose,
} from '@agent-device/contracts/device';
import type { FoldScreenReport, SetFoldPoseResult } from '@agent-device/contracts/fold-runtime';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import { IOS_FOLD_POSE_SETTLE_ATTEMPTS, IOS_FOLD_POSE_STABLE_DEGREES } from '../core/config.ts';
import {
queryAppleDisplayInventory,
type AppleDeviceDisplay,
type AppleDisplayInventory,
} from '../core/display-inventory.ts';
import { HINGE_ANGLE_UNAVAILABLE_REASON, readAppleHingeAngle } from '../core/hinge-angle.ts';
import { requireSimulatorDevice } from '../core/simulator.ts';
import { sendSimulatorFoldPose } from './simulator-hid.ts';
const FOLDABLE_REQUIRED_HINT =
'fold sets the hinge angle of a foldable simulator such as iPhone Duo; this simulator reports one integrated panel, so it has no hinge to pose.';
const INVENTORY_REQUIRED_HINT =
"fold needs 'devicectl device info displays' to tell a foldable from a single-panel simulator; update Xcode to a version that ships the display-information feature.";
const DISPATCHED_UNVERIFIED_HINT =
"The pose request was sent and the device may have followed it, but 'devicectl device motion hinge-angle' is unavailable here, so fold cannot confirm it. Take a screenshot or snapshot to see which panel is lit, or update Xcode to a version that ships the hinge-angle stream.";
const POSE_UNSETTLED_HINT =
'The hinge reached the requested pose and was still moving when the read budget ended. Retry the fold, then read the angle directly with xcrun devicectl device motion hinge-angle --device <udid> --session-timeout 1 --timeout 5 to see whether the simulator holds the pose.';
/** Sets a simulator hinge through guest HID and verifies the pose through CoreDevice. */
export async function setAppleFoldPose(
device: DeviceInfo,
input: SetFoldPoseInput,
options: { signal?: AbortSignal } = {},
): Promise<SetFoldPoseResult> {
options.signal?.throwIfAborted();
requireSimulatorDevice(device, 'fold');
const intent = input;
const targetAngle = intent.keyframes?.at(-1)?.angle;
const pose = intent.pose ?? foldPoseForHingeAngle(targetAngle!)!;
const inventory = await queryAppleDisplayInventory(device, { signal: options.signal });
requireFoldableInventory(device, inventory);
await sendSimulatorFoldPose(device, intent.keyframes ?? pose, options.signal);
emitDiagnostic({
level: 'info',
phase: 'apple_fold_pose_dispatched',
data: { deviceId: device.id, pose },
});
const hingeAngleDegrees = await awaitHingePose(device, pose, options.signal, targetAngle);
const litPanel = await readLitPanel(device, options.signal);
return {
pose: foldPoseForHingeAngle(hingeAngleDegrees)!,
hingeAngleDegrees,
...(litPanel ? { screen: screenReport(litPanel) } : {}),
};
}
function isHingeAngleUnavailable(error: unknown): boolean {
return error instanceof AppError && error.details?.reason === HINGE_ANGLE_UNAVAILABLE_REASON;
}
/**
* The toolchain cannot read the hinge, so the pose is neither confirmed nor refuted. The HID
* command was delivered, though, so the device may already be in the requested pose; the lit
* panel is evidence for the caller to weigh, not a verification (panel power cannot separate
* `half-open` from `open`).
*/
async function dispatchedUnverifiedPoseError(
device: DeviceInfo,
pose: FoldPose,
signal: AbortSignal | undefined,
targetAngle: number | undefined,
cause: unknown,
): Promise<AppError> {
const litPanel = await readLitPanel(device, signal);
return new AppError(
'COMMAND_FAILED',
`${device.name} received the ${pose} pose request, but this toolchain cannot read the hinge angle to verify it`,
{
deviceId: device.id,
requestedPose: pose,
...(targetAngle === undefined ? {} : { targetAngleDegrees: targetAngle }),
reason: 'fold-pose-dispatched-unverified',
...(litPanel ? { screen: screenReport(litPanel) } : {}),
...(cause instanceof AppError ? { hingeReadFailure: cause.details } : {}),
hint: DISPATCHED_UNVERIFIED_HINT,
},
cause,
);
}
function requireFoldableInventory(device: DeviceInfo, inventory: AppleDisplayInventory): void {
if (inventory.unresolved) {
throw new AppError(
'COMMAND_FAILED',
'CoreDevice reported no display table for this simulator',
{
deviceId: device.id,
hint: INVENTORY_REQUIRED_HINT,
},
);
}
if (!inventory.multiScreen) {
throw new AppError(
'UNSUPPORTED_OPERATION',
`${device.name} is not a foldable simulator: fold requires more than one integrated panel`,
{ deviceId: device.id, reason: 'single-panel-device', hint: FOLDABLE_REQUIRED_HINT },
);
}
}
/**
* Reads the hinge until it reports the requested pose. Each read costs one bounded devicectl
* stream, so the attempt count is the whole settle budget. HID delivery alone cannot prove
* the runtime accepted the requested hinge state.
*
* `closed` and `open` are the hinge's two end stops, so one read at the stop is the pose. A
* `half-open` angle proves only the category, because a hinge travelling between the stops passes
* through it, so that pose is the hinge *resting* inside the interval and two consecutive reads
* have to show it (ADR 0025).
*/
async function awaitHingePose(
device: DeviceInfo,
pose: FoldPose,
signal: AbortSignal | undefined,
targetAngle?: number,
): Promise<number> {
let observed: number | undefined;
let previous: number | undefined;
for (let attempt = 1; attempt <= IOS_FOLD_POSE_SETTLE_ATTEMPTS; attempt += 1) {
signal?.throwIfAborted();
previous = observed;
try {
observed = await readAppleHingeAngle(device, { signal });
} catch (error) {
if (observed !== undefined || !isHingeAngleUnavailable(error)) throw error;
throw await dispatchedUnverifiedPoseError(device, pose, signal, targetAngle, error);
}
if (isVerifiedHingePose(observed, previous, pose, targetAngle)) return observed;
}
throw hingeVerificationError(device, pose, observed, previous, targetAngle);
}
function isVerifiedHingePose(
observed: number,
previous: number | undefined,
pose: FoldPose,
targetAngle: number | undefined,
): boolean {
if (targetAngle !== undefined) return isSettledTargetAngle(observed, previous, targetAngle);
if (foldPoseForHingeAngle(observed) !== pose) return false;
return (
pose !== 'half-open' || (previous !== undefined && isSettledHalfOpenPair(observed, previous))
);
}
function isSettledTargetAngle(
observed: number,
previous: number | undefined,
targetAngle: number,
): boolean {
if (!matchesTargetAngle(observed, targetAngle)) return false;
if (targetAngle === 0 || targetAngle === 180) return true;
return (
previous !== undefined &&
matchesTargetAngle(previous, targetAngle) &&
Math.abs(observed - previous) <= IOS_FOLD_POSE_STABLE_DEGREES
);
}
function matchesTargetAngle(
observed: number | undefined,
targetAngle: number | undefined,
): boolean {
return (
targetAngle === undefined ||
(observed !== undefined && Math.abs(observed - targetAngle) <= IOS_FOLD_POSE_STABLE_DEGREES)
);
}
function hingeVerificationError(
device: DeviceInfo,
pose: FoldPose,
observed: number | undefined,
previous: number | undefined,
targetAngle: number | undefined,
): AppError {
if (!matchesTargetAngle(observed, targetAngle)) {
return new AppError('COMMAND_FAILED', 'The hinge did not reach the final keyframe angle', {
reason: 'fold-angle-unverified',
targetAngleDegrees: targetAngle,
hingeAngleDegrees: observed,
deviceId: device.id,
});
}
if (targetAngle !== undefined && observed !== undefined)
return unsettledPoseError(device, foldPoseForHingeAngle(observed)!, observed, previous);
if (observed !== undefined && pose === 'half-open' && foldPoseForHingeAngle(observed) === pose) {
return unsettledPoseError(device, pose, observed, previous);
}
return unverifiedPoseError(device, pose, observed);
}
/**
* Whether two consecutive readings are one hinge at rest in `half-open`. Both must classify as
* `half-open`: two angles 0.2° apart on either side of the 179° boundary are two poses.
*/
function isSettledHalfOpenPair(observed: number, previous: number): boolean {
return (
foldPoseForHingeAngle(observed) === 'half-open' &&
foldPoseForHingeAngle(previous) === 'half-open' &&
Math.abs(observed - previous) <= IOS_FOLD_POSE_STABLE_DEGREES
);
}
function hingePoseDetails(device: DeviceInfo, pose: FoldPose, observed: number | undefined) {
return {
deviceId: device.id,
requestedPose: pose,
observedPose: observed === undefined ? undefined : foldPoseForHingeAngle(observed),
hingeAngleDegrees: observed,
};
}
/** The budget ended with the hinge classified as some pose other than the one requested. */
function unverifiedPoseError(device: DeviceInfo, pose: FoldPose, observed: number | undefined) {
return new AppError(
'COMMAND_FAILED',
`${device.name} did not reach the ${pose} pose: CoreDevice still reports a hinge angle of ${observed}°`,
{
...hingePoseDetails(device, pose, observed),
reason: 'fold-pose-unverified',
hint: 'The simulator HID command completed, but the hinge did not follow. Verify that the selected Xcode and simulator runtime support foldable HID control, then retry.',
},
);
}
/** The hinge was seen `half-open` and never came to rest inside that interval. */
function unsettledPoseError(
device: DeviceInfo,
pose: FoldPose,
observed: number,
previous: number | undefined,
) {
return new AppError(
'COMMAND_FAILED',
`${device.name} was observed ${pose} at ${observed}° but did not settle: ${IOS_FOLD_POSE_SETTLE_ATTEMPTS} hinge reads never held two consecutive angles within ${IOS_FOLD_POSE_STABLE_DEGREES}° of each other`,
{
...hingePoseDetails(device, pose, observed),
reason: 'fold-pose-unsettled',
...(previous === undefined ? {} : { previousHingeAngleDegrees: previous }),
hint: POSE_UNSETTLED_HINT,
},
);
}
async function readLitPanel(
device: DeviceInfo,
signal: AbortSignal | undefined,
): Promise<AppleDeviceDisplay | undefined> {
const inventory = await queryAppleDisplayInventory(device, { signal });
if (inventory.unresolved || inventory.ambiguous) return undefined;
return inventory.activeDisplay;
}
/** The panel's native points: pixels divided by its own point scale, never rotated by orientation. */
function screenReport(display: AppleDeviceDisplay): FoldScreenReport {
return {
display: display.name,
coordinateSpace: FOLD_SCREEN_COORDINATE_SPACE,
widthPt: Math.round(display.widthPx / display.pointScale),
heightPt: Math.round(display.heightPx / display.pointScale),
};
}