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
2 changes: 1 addition & 1 deletion docs/adr/0025-foldable-apple-panels.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
57 changes: 56 additions & 1 deletion packages/platform-android/src/foldable/pose.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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];
Expand All @@ -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');
}
Expand Down Expand Up @@ -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'] });

Expand Down
34 changes: 33 additions & 1 deletion packages/platform-android/src/foldable/pose.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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.
Expand All @@ -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 =
Expand Down Expand Up @@ -163,7 +169,11 @@ async function sendEmulatorPosture(
postureId: string,
signal: AbortSignal | undefined,
): Promise<void> {
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,
Expand All @@ -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
Expand Down
10 changes: 8 additions & 2 deletions packages/platform-apple/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
34 changes: 26 additions & 8 deletions packages/platform-apple/src/foldable/fold-helper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,15 @@ test.each(['success', 'dispatch'] as const)(
expect(calls.map((call) => call.args)).toEqual([
['simctl', 'spawn', 'selected-duo', '/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');
},
);

Expand Down Expand Up @@ -205,7 +208,6 @@ test.each([
});

test.each([
['setPose', (helper: FoldHelper) => helper.setPose('open'), 'fold-hid-dispatch-failed', {}],
[
'readHingeAngle',
(helper: FoldHelper) => helper.readHingeAngle(),
Expand All @@ -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'),
Expand Down
34 changes: 29 additions & 5 deletions packages/platform-apple/src/foldable/fold-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'>;
Expand Down Expand Up @@ -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,
);
},
Expand Down Expand Up @@ -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',
Expand Down
53 changes: 52 additions & 1 deletion packages/platform-apple/src/foldable/pose.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ vi.mock('./fold-helper.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('./fold-helper.ts')>();
return { ...actual, createFoldHelper: vi.fn(() => FOLD_HELPER) };
});
vi.mock('../core/config.ts', async (importOriginal) => ({
...(await importOriginal<typeof import('../core/config.ts')>()),
// 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<typeof import('@agent-device/host-kit/diagnostics')>();
return { ...actual, emitDiagnostic: vi.fn() };
Expand All @@ -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,
Expand Down Expand Up @@ -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]>([
Expand Down
Loading
Loading