diff --git a/docs/adr/0025-foldable-apple-panels.md b/docs/adr/0025-foldable-apple-panels.md index 6af3deb56d..9e32235aee 100644 --- a/docs/adr/0025-foldable-apple-panels.md +++ b/docs/adr/0025-foldable-apple-panels.md @@ -289,7 +289,7 @@ A verified response includes the angle and lit panel's point size. The guest switches panel power after the hinge stop, so the first panel read can name the panel lit before the fold. Amendment (2026-11-23): for a named pose, the reported panel must be the measured panel that the pose lights. That panel is `primary` for `closed` and the other panel for `half-open` and `open`, the only poses with panel measurements. -Panel reads repeat until a short deadline, and each read ends by that deadline. Then the response omits `screen`. +Panel reads repeat until a short deadline, and each read's timeout ends at that deadline. Then the response omits `screen`. An unresolved table, or a table in which no panel reports measured power, cannot show the switch, so it ends the reads. A custom keyframe angle keeps one panel read, because no panel measurement exists for interior angles. This is an explicit exception to the rejected pose-to-panel map below: the pose selects among measured panels and never supplies a panel. diff --git a/packages/platform-android/src/foldable/pose.test.ts b/packages/platform-android/src/foldable/pose.test.ts index acd493ed56..0d832d2f1c 100644 --- a/packages/platform-android/src/foldable/pose.test.ts +++ b/packages/platform-android/src/foldable/pose.test.ts @@ -11,6 +11,7 @@ vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => { }); import { sleep } from '@agent-device/host-kit/retry'; +import { AppError } from '@agent-device/kernel/errors'; import { runAndroidAdb, runAndroidShell } from '../adb.ts'; import { ANDROID_EMULATOR } from '../runtime.fixtures.ts'; @@ -65,6 +66,8 @@ function stubEmulator(options: { stateReads: string[]; keyguardReads?: boolean[]; posture?: string; + /** Thrown by the posture command instead of answering it. */ + postureError?: unknown; hinge?: string; }) { const stateReads = [...options.stateReads]; @@ -83,7 +86,10 @@ function stubEmulator(options: { }); mockAdb.mockImplementation(async (_device, args) => { const command = args.join(' '); - if (command.startsWith('emu posture ')) return answer(options.posture ?? 'OK\n'); + if (command.startsWith('emu posture ')) { + if (options.postureError !== undefined) throw options.postureError; + return answer(options.posture ?? 'OK\n'); + } if (command === 'emu sensor get hinge-angle0') { return answer(options.hinge ?? 'hinge-angle0 = 0\nOK\n'); } @@ -232,6 +238,55 @@ test('reads a KO reply as a dispatch failure even though the console exits 0', a }); }); +const consoleTimeout = () => + new AppError('COMMAND_FAILED', 'adb timed out after 10000ms', { timeoutMs: 10_000 }); + +test('reports a posture whose console answer timed out as possibly applied', async () => { + stubEmulator({ stateReads: ['0'], postureError: consoleTimeout() }); + + const failure = await setAndroidFoldPose(ANDROID_EMULATOR, { pose: 'open' }).catch( + (error: unknown) => error, + ); + expect(failure).toMatchObject({ + code: 'COMMAND_FAILED', + details: { + reason: 'fold-posture-dispatch-timed-out', + dispatched: 'unknown', + deviceId: ANDROID_EMULATOR.id, + timeoutMs: 10_000, + }, + }); + // The refusal ends the fold: no device-state read claims a pose the dispatch cannot vouch for. + expect(shellCommands()).not.toContain('cmd device_state print-state'); +}); + +test('keeps a failed posture exit and a cancelled posture as they are, not possibly applied', async () => { + stubEmulator({ + stateReads: ['0'], + postureError: new AppError('COMMAND_FAILED', 'adb emu posture 3 exited with code 1', { + exitCode: 1, + }), + }); + const exited = await setAndroidFoldPose(ANDROID_EMULATOR, { pose: 'open' }).catch( + (error: unknown) => error, + ); + expect((exited as AppError).details).not.toHaveProperty('reason'); + + // A timeout raised while the caller cancels is the cancellation's, not a late posture answer. + const controller = new AbortController(); + stubEmulator({ stateReads: ['0'] }); + mockAdb.mockImplementationOnce(async () => { + controller.abort(new DOMException('request cancelled', 'AbortError')); + throw consoleTimeout(); + }); + const cancelled = await setAndroidFoldPose( + ANDROID_EMULATOR, + { pose: 'open' }, + { signal: controller.signal }, + ).catch((error: unknown) => error); + expect((cancelled as AppError).details).not.toHaveProperty('reason'); +}); + test('fails as fold-pose-unverified when the guest never commits the device state', async () => { stubEmulator({ stateReads: ['2'] }); diff --git a/packages/platform-android/src/foldable/pose.ts b/packages/platform-android/src/foldable/pose.ts index 61ad863117..20b6081be1 100644 --- a/packages/platform-android/src/foldable/pose.ts +++ b/packages/platform-android/src/foldable/pose.ts @@ -1,5 +1,6 @@ import type { FoldPose, SetFoldPoseInput } from '@agent-device/contracts/device'; import { FOLD_REASONS, type SetFoldPoseResult } from '@agent-device/contracts/fold-runtime'; +import { isCommandTimeoutError } from '@agent-device/host-kit/command'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { sleep } from '@agent-device/host-kit/retry'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -33,6 +34,9 @@ const ANDROID_FOLD_REASONS = { keyframesUnsupported: { reason: 'fold-keyframes-unsupported' }, // The Android emulator console refused the posture command. postureDispatchFailed: { reason: 'fold-posture-dispatch-failed' }, + // The Android emulator console did not answer the posture command in time, so the posture may + // have applied. + postureDispatchTimedOut: { reason: 'fold-posture-dispatch-timed-out' }, // The lock screen that folding raised on Android did not stay dismissed. lockScreenPersists: { reason: 'fold-lock-screen-persists' }, // The Android emulator console returned no hinge angle. @@ -55,6 +59,8 @@ const KEYFRAMES_HINT = 'The emulator console poses the hinge at fixed angles only; request closed, half-open, or open.'; const POSTURE_DISPATCH_HINT = 'The emulator console refused the posture. Check that the AVD is a foldable profile (hw.sensor.hinge=yes), then retry.'; +const POSTURE_TIMEOUT_HINT = + 'Check the pose with a screenshot or `adb shell cmd device_state print-state`. A retry sends the posture again and waits for its device state.'; const POSE_UNVERIFIED_HINT = 'The emulator console accepted the posture, but the guest did not commit the matching device state. Read it directly with `adb shell cmd device_state print-state` to see which state the emulator holds.'; const HINGE_ANGLE_HINT = @@ -163,7 +169,11 @@ async function sendEmulatorPosture( postureId: string, signal: AbortSignal | undefined, ): Promise { - const sent = await runEmulatorConsole(device, ['posture', postureId], signal); + const sent = await runEmulatorConsole(device, ['posture', postureId], signal).catch( + (error: unknown) => { + throw postureTimeoutError(device, pose, error, signal); + }, + ); if (sent.refusal !== undefined) { throw new AppError('COMMAND_FAILED', `Unable to set the emulator posture for ${pose}`, { deviceId: device.id, @@ -174,6 +184,28 @@ async function sendEmulatorPosture( } } +/** A console that answers late may still apply the posture, so its timeout is not an unsent posture. */ +function postureTimeoutError( + device: DeviceInfo, + pose: FoldPose, + error: unknown, + signal: AbortSignal | undefined, +): unknown { + if (signal?.aborted || !isCommandTimeoutError(error)) return error; + return new AppError( + 'COMMAND_FAILED', + `Timed out setting the emulator posture for ${pose}; the posture may have applied`, + { + ...error.details, + deviceId: device.id, + reason: ANDROID_FOLD_REASONS.postureDispatchTimedOut.reason, + dispatched: 'unknown', + hint: POSTURE_TIMEOUT_HINT, + }, + error, + ); +} + /** * The console returns before the guest reacts, and a posture the console accepted is not yet a * pose the app sees, so the device state is the verification: it is what `WindowManager`'s diff --git a/packages/platform-apple/src/core/config.ts b/packages/platform-apple/src/core/config.ts index c5e57fdb70..971738bf57 100644 --- a/packages/platform-apple/src/core/config.ts +++ b/packages/platform-apple/src/core/config.ts @@ -57,11 +57,17 @@ export const IOS_FOLD_POSE_STABLE_DEGREES = 0.5; /** * How long a verified named pose waits for the guest panel table to light that pose's panel. The * hinge reaches its stop before panel power switches, and the table can report both panels lit for - * a few seconds in between. Lit-panel reads repeat at the interval below. The time left on this - * deadline bounds each read, so the wait costs about one read at `IOS_APPLE_DISPLAY_PROBE_TIMEOUT_MS`. + * a few seconds in between. Lit-panel reads repeat at the interval below. Each read's timeout ends + * at this deadline, so the wait costs about one read at `IOS_APPLE_DISPLAY_PROBE_TIMEOUT_MS`. A read + * that times out also gets the helper's 1 s kill grace, so the wait can end up to 1 s past it. */ export const IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS = 5_000; export const IOS_FOLD_PANEL_READ_INTERVAL_MS = 500; +/** + * The last lit-panel read starts at the latest this long before the deadline above, so it has time + * to answer. + */ +export const IOS_FOLD_PANEL_LAST_READ_MS = 500; /** * Bounded lit-panel reads cover delayed HID effects and the two-lit interval after a fold. * A fixed picker value is sent once per lit panel; the remaining reads only observe. diff --git a/packages/platform-apple/src/foldable/fold-helper.test.ts b/packages/platform-apple/src/foldable/fold-helper.test.ts index 9945e31f9a..f39a622f22 100644 --- a/packages/platform-apple/src/foldable/fold-helper.test.ts +++ b/packages/platform-apple/src/foldable/fold-helper.test.ts @@ -64,12 +64,15 @@ test.each(['success', 'dispatch'] as const)( expect(calls.map((call) => call.args)).toEqual([ ['simctl', 'spawn', 'selected-duo', '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/cache/fold-helper', 'set', 'half-open'], ]); - if (outcome === 'success') expect(value).toBeUndefined(); - else - expect(value).toMatchObject({ - code: 'COMMAND_FAILED', - details: { reason: 'fold-hid-dispatch-failed', deviceId: 'selected-duo' }, - }); + if (outcome === 'success') { + expect(value).toBeUndefined(); + return; + } + expect(value).toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'fold-hid-dispatch-failed', deviceId: 'selected-duo' }, + }); + expect((value as AppError).details).not.toHaveProperty('dispatched'); }, ); @@ -205,7 +208,6 @@ test.each([ }); test.each([ - ['setPose', (helper: FoldHelper) => helper.setPose('open'), 'fold-hid-dispatch-failed', {}], [ 'readHingeAngle', (helper: FoldHelper) => helper.readHingeAngle(), @@ -218,7 +220,23 @@ test.each([ 'fold-helper-panels-unreadable', {}, ], - // The rotation can land after the deadline, so the refusal discloses an unknown dispatch. + // A pose or a rotation can land after the deadline, so the refusal discloses an unknown dispatch. + [ + 'setPose (named pose)', + (helper: FoldHelper) => helper.setPose('open'), + 'fold-hid-dispatch-timed-out', + { dispatched: 'unknown', hint: expect.not.stringContaining('keyframe') }, + ], + [ + 'setPose (keyframes)', + (helper: FoldHelper) => + helper.setPose([ + { atMs: 0, angle: 0 }, + { atMs: 1000, angle: 180 }, + ]), + 'fold-hid-dispatch-timed-out', + { dispatched: 'unknown', hint: expect.stringContaining('first keyframe') }, + ], [ 'rotate', (helper: FoldHelper) => helper.rotate('landscape-left'), diff --git a/packages/platform-apple/src/foldable/fold-helper.ts b/packages/platform-apple/src/foldable/fold-helper.ts index 7e2f4d3f87..e5922bcf89 100644 --- a/packages/platform-apple/src/foldable/fold-helper.ts +++ b/packages/platform-apple/src/foldable/fold-helper.ts @@ -14,6 +14,8 @@ import { ensureFoldHelperBinary, type FoldHelperBinary } from './fold-helper-cac export const FOLD_HELPER_REASONS = { // The fold helper could not send the hinge pose to the iOS simulator. hidDispatchFailed: { reason: 'fold-hid-dispatch-failed' }, + // The fold helper did not finish sending the hinge pose in time, so the pose may have applied. + hidDispatchTimedOut: { reason: 'fold-hid-dispatch-timed-out' }, // An iOS simulator hinge read returned no usable sample; `details` say why. hingeAngleNoSample: { reason: 'fold-hinge-angle-no-sample' }, } as const satisfies ReasonTable<'fold'>; @@ -131,7 +133,11 @@ export function createFoldHelper(device: DeviceInfo): FoldHelper { const payload = typeof pose === 'string' ? pose : JSON.stringify(pose); await run( ['set', payload], - { signal, timeoutMs: durationMs + 10_000, failure: DISPATCH_FAILURE }, + { + signal, + timeoutMs: durationMs + 10_000, + failure: typeof pose === 'string' ? POSE_DISPATCH_FAILURE : KEYFRAMES_DISPATCH_FAILURE, + }, () => true, ); }, @@ -173,10 +179,28 @@ type ModeFailure = ModeFailureShape & timedOut?: ModeFailureShape; }>; -const DISPATCH_FAILURE: ModeFailure = { - message: 'Unable to send the simulator hinge pose', - details: { reason: FOLD_HELPER_REASONS.hidDispatchFailed.reason }, -}; +/** The set-mode failure; `retry` says what sending the same request again does. */ +function dispatchFailure(retry: string): ModeFailure { + return { + message: 'Unable to send the simulator hinge pose', + details: { reason: FOLD_HELPER_REASONS.hidDispatchFailed.reason }, + timedOut: { + message: 'Timed out sending the simulator hinge pose; the pose may have applied', + details: { + reason: FOLD_HELPER_REASONS.hidDispatchTimedOut.reason, + dispatched: 'unknown', + hint: `Check the pose with a screenshot or snapshot. ${retry}`, + }, + }, + }; +} + +const POSE_DISPATCH_FAILURE = dispatchFailure( + 'A retry sends the pose again and reads the hinge back.', +); +const KEYFRAMES_DISPATCH_FAILURE = dispatchFailure( + 'A retry replays the motion from its first keyframe.', +); const ROTATE_FAILURE: ModeFailure = { message: 'Unable to send the simulator orientation', diff --git a/packages/platform-apple/src/foldable/pose.test.ts b/packages/platform-apple/src/foldable/pose.test.ts index a3584ec476..5f0492c29f 100644 --- a/packages/platform-apple/src/foldable/pose.test.ts +++ b/packages/platform-apple/src/foldable/pose.test.ts @@ -17,6 +17,11 @@ vi.mock('./fold-helper.ts', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, createFoldHelper: vi.fn(() => FOLD_HELPER) }; }); +vi.mock('../core/config.ts', async (importOriginal) => ({ + ...(await importOriginal()), + // Distinct from the lit-panel read interval, so the poll tests tell the two apart. + IOS_FOLD_PANEL_LAST_READ_MS: 1_000, +})); vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, emitDiagnostic: vi.fn() }; @@ -31,6 +36,7 @@ import { type AppleDisplayInventory, } from '../core/display-inventory.ts'; import { + IOS_FOLD_PANEL_LAST_READ_MS, IOS_FOLD_PANEL_READ_INTERVAL_MS, IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS, IOS_FOLD_POSE_READ_INTERVAL_MS, @@ -234,7 +240,52 @@ test('omits the screen when the panel lit before the fold is still lit at the de hingeAngleDegrees: 180, }); const panelReads = mockInventory.mock.calls.length - 1; - expect(panelReads).toBe(IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS / IOS_FOLD_PANEL_READ_INTERVAL_MS + 1); + expect(panelReads).toBe( + (IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS - IOS_FOLD_PANEL_LAST_READ_MS) / + IOS_FOLD_PANEL_READ_INTERVAL_MS + + 1, + ); +}); + +test('ends the timeout of every lit-panel read at the panel settle deadline', async () => { + // Each read answers after 300 ms and still names the pre-fold panel, so the poll runs to its end. + const reads: { startMs: number; timeoutMs: number }[] = []; + mockInventory + .mockResolvedValueOnce(duoInventory('outer')) + .mockImplementation(async (_device, options) => { + reads.push({ startMs: Date.now(), timeoutMs: options.timeoutMs! }); + await new Promise((resolve) => setTimeout(resolve, 300)); + return duoInventory('outer'); + }); + mockHinge.mockResolvedValue(180); + + await expect(foldOnFakeClock({ pose: 'open' })).resolves.not.toHaveProperty('screen'); + expect(reads.length).toBeGreaterThan(1); + const pollStartMs = reads[0]!.startMs; + // The last read starts early enough to answer, and every read's timeout ends at the deadline. + expect(reads.at(-1)!.timeoutMs).toBeGreaterThanOrEqual(IOS_FOLD_PANEL_LAST_READ_MS); + expect(reads.map(({ startMs, timeoutMs }) => startMs + timeoutMs - pollStartMs)).toEqual( + reads.map(() => IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS), + ); +}); + +test('bounds a lit-panel read that starts after the panel settle deadline', async () => { + // A stalled host moves the clock past the deadline while the poll sleeps before its next read. + const timeouts: number[] = []; + mockInventory + .mockResolvedValueOnce(duoInventory('outer')) + .mockImplementation(async (_device, options) => { + timeouts.push(options.timeoutMs!); + if (timeouts.length === 1) { + setTimeout(() => vi.setSystemTime(Date.now() + IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS), 10); + } + return duoInventory('outer'); + }); + mockHinge.mockResolvedValue(180); + + await expect(foldOnFakeClock({ pose: 'open' })).resolves.not.toHaveProperty('screen'); + // A zero exec timeout would mean no timeout at all. + expect(timeouts).toEqual([IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS, 1]); }); test.each<[string, AppleDisplayInventory]>([ diff --git a/packages/platform-apple/src/foldable/pose.ts b/packages/platform-apple/src/foldable/pose.ts index 665f5928f2..13f79c6a09 100644 --- a/packages/platform-apple/src/foldable/pose.ts +++ b/packages/platform-apple/src/foldable/pose.ts @@ -15,6 +15,7 @@ import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { Deadline, pollUntilSettled } from '@agent-device/host-kit/retry'; import { + IOS_FOLD_PANEL_LAST_READ_MS, IOS_FOLD_PANEL_READ_INTERVAL_MS, IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS, IOS_FOLD_POSE_READ_INTERVAL_MS, @@ -315,15 +316,22 @@ async function awaitPoseLitPanel( // CONSERVATIVE: The guest switches panel power after the hinge stop, so the first read can name // the panel lit before the fold; wait for the pose's panel and omit `screen` at the deadline. // Revisit only if the panel table reports the switch together with the hinge stop. - const deadline = Deadline.fromTimeoutMs(IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS); + const startedAtMs = Date.now(); + const settleDeadline = Deadline.fromTimeoutMs(IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS, startedAtMs); + const lastReadStart = Deadline.fromTimeoutMs( + IOS_FOLD_PANEL_SETTLE_TIMEOUT_MS - IOS_FOLD_PANEL_LAST_READ_MS, + startedAtMs, + ); const { value } = await pollUntilSettled({ - // The time left on the deadline bounds each read, so the poll costs about one full read. + // Each read's timeout ends at the settle deadline, so the poll costs about one full read, plus + // the 1 s kill grace when a read times out. A zero exec timeout means no timeout, so a read that + // starts after the deadline still gets 1 ms. probe: () => readGuestPanelTable(device, helper, signal, { - timeoutMs: Math.max(deadline.remainingMs(), IOS_FOLD_PANEL_READ_INTERVAL_MS), + timeoutMs: Math.max(settleDeadline.remainingMs(), 1), }), settled: (inventory) => !hasMeasuredPanelPower(inventory) || posePanel(inventory) !== undefined, - deadline, + deadline: lastReadStart, intervalMs: IOS_FOLD_PANEL_READ_INTERVAL_MS, signal, }); diff --git a/test/integration/provider-scenarios/ios-fold.test.ts b/test/integration/provider-scenarios/ios-fold.test.ts index e4e0433055..08bec0d00a 100644 --- a/test/integration/provider-scenarios/ios-fold.test.ts +++ b/test/integration/provider-scenarios/ios-fold.test.ts @@ -429,9 +429,10 @@ test('fold worst-case ledger covers the client envelope with the daemon-result m assertWithinEnvelope(measured, envelopeMs!, REQUIRED_DAEMON_RESULT_MARGIN_MS); // A named pose waits for its panel after the hinge settles. Its worst case settles the hinge on - // the last read it allows, then polls a panel table whose lit panel never matches the pose. Each - // poll read ends by the poll deadline, so one read that spends its whole budget is the poll's - // worst case, and the ledger records that one read. + // the last read it allows, then polls a panel table whose lit panel never matches the pose. The + // ledger charges every call its full timeout, so this run bounds one panel read that spends the + // whole poll budget, not a poll of several shorter reads. Such a poll costs no more: each read's + // timeout ends at the poll deadline (`pose.test.ts`), and a read that times out ends the poll. const poseCalibration = await runFoldLedgerScenario({ hingeAngleAt: () => 170, withVirtualClock: false, diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index ff7e8f53ec..9febaa9ca9 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -127,10 +127,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `fold-posture-unsupported` | The emulator profile has no device state for the requested pose; `details.supportedPoses` lists the poses it has. | | `fold-keyframes-unsupported` | Android poses fixed postures only, so fold keyframes are refused. | | `fold-posture-dispatch-failed` | The Android emulator console refused the posture command. | +| `fold-posture-dispatch-timed-out` | The Android emulator console did not answer the posture command in time, so the posture may have applied. | | `fold-lock-screen-persists` | The lock screen that folding raised on Android did not stay dismissed. | | `fold-hinge-angle-unreadable` | The Android emulator console returned no hinge angle. | | `fold-helper-build-failed` | The iOS simulator fold helper could not be built with the selected Xcode. | | `fold-hid-dispatch-failed` | The fold helper could not send the hinge pose to the iOS simulator. | +| `fold-hid-dispatch-timed-out` | The fold helper did not finish sending the hinge pose in time, so the pose may have applied. | | `fold-hinge-angle-no-sample` | An iOS simulator hinge read returned no usable sample; `details` say why. | | `fold-pose-dispatched-unverified` | The iOS simulator received the pose, but the first hinge read returned no sample to verify it. | | `fold-angle-unverified` | The iOS simulator hinge did not reach the angle of the final keyframe. |