From 3de249c47a626e87485d570222435b8ad107eb88 Mon Sep 17 00:00:00 2001 From: strzhao Date: Mon, 16 Nov 2026 08:12:57 +0100 Subject: [PATCH 1/4] fix(android): stop admitting orientation reads once the settle budget is spent The settle loop checked the deadline before its wait, then started another display read with the remaining budget clamped to a 1 ms floor. A rotation that never takes effect therefore died as a misleading adb timeout instead of reporting the last observed rotation. Admission is now rechecked after the wait, so the existing "did not take effect" fact wins and a read that fails inside its own budget stays a probe failure. Closes #4562 Co-authored-by: Apex by Callstack Co-authored-by: opencode --- .../src/__tests__/input-actions.test.ts | 156 +++++++++++++++++- .../platform-android/src/input-actions.ts | 5 + 2 files changed, 160 insertions(+), 1 deletion(-) diff --git a/packages/platform-android/src/__tests__/input-actions.test.ts b/packages/platform-android/src/__tests__/input-actions.test.ts index f013bc6ea0..b1c2f07db4 100644 --- a/packages/platform-android/src/__tests__/input-actions.test.ts +++ b/packages/platform-android/src/__tests__/input-actions.test.ts @@ -499,7 +499,39 @@ test('pressAndroid dispatches no failure suppression even when one is smuggled p }); // The orientation settle polls at its own interval; the clock is the assertion, not the wait. -vi.mock('@agent-device/host-kit/retry', () => ({ sleep: async () => {} })); +// A test arms `onSleep` to make the wait consume wall clock, as a real settle wait does. +const { orientationWait, orientationSleep } = vi.hoisted(() => { + const wait: { slept: number[]; onSleep: ((ms: number) => void) | undefined } = { + slept: [], + onSleep: undefined, + }; + return { + orientationWait: wait, + orientationSleep: async (ms: number) => { + wait.slept.push(ms); + wait.onSleep?.(ms); + }, + }; +}); +vi.mock('@agent-device/host-kit/retry', () => ({ sleep: orientationSleep })); + +/** + * Runs a settle with its wait consuming wall clock, as a real settle wait does, and hands the test + * the waits the loop took. + */ +async function withClockConsumingOrientationWait( + run: (slept: number[]) => Promise, +): Promise { + orientationWait.slept.length = 0; + orientationWait.onSleep = (ms) => { + vi.setSystemTime(Date.now() + ms); + }; + try { + return await run(orientationWait.slept); + } finally { + orientationWait.onSleep = undefined; + } +} const ORIENTATION_CALLS = [ ['shell', 'settings', 'put', 'system', 'accelerometer_rotation', '0'], @@ -559,6 +591,104 @@ test('setAndroidOrientation fails when the display never reports the requested r } }); +test('a wait that lands on the deadline ends the settle on the last rotation, not a floor-budget read', async () => { + // #4562: the deadline was checked only before the wait, so the loop woke at the deadline and + // started one more `dumpsys display` on the 1 ms floor of `remainingMs`. No real read answers + // inside that floor, and its adb timeout replaced the "did not take effect" fact a pinned + // foreground app should produce. Admission is rechecked after the wait, so the settle ends on the + // rotation the last in-budget read reported — here the one the display settled at, not the first + // one it saw — and no read ever runs on a starved budget. + vi.useFakeTimers({ now: 0, toFake: ['Date'] }); + const DISPLAY_ANSWER_MS = 120; + const LAST_ROTATION_FROM_READ = 15; + const probeBudgets: number[] = []; + let reads = 0; + try { + await withFakeAdb( + (args, options) => { + if (args[1] !== 'dumpsys') return undefined; + probeBudgets.push(options?.timeoutMs ?? -1); + if ((options?.timeoutMs ?? 0) < DISPLAY_ANSWER_MS) { + return new Error(`adb shell dumpsys display timed out after ${options?.timeoutMs}ms`); + } + reads += 1; + const rotation = reads >= LAST_ROTATION_FROM_READ ? 2 : 0; + return ` mCurrentOrientation=${rotation}\n`; + }, + async ({ calls, device }) => { + await withClockConsumingOrientationWait(async (slept) => { + await assert.rejects( + setAndroidOrientation(device, 'landscape-left'), + (error: unknown) => { + assert.ok(error instanceof Error); + assert.doesNotMatch(error.message, /could not confirm the display rotation/); + assert.match( + error.message, + /orientation landscape-left did not take effect: the display still reports rotation 2 after 15000ms/, + ); + const details = (error as { details?: Record }).details ?? {}; + assert.equal(details.requestedRotation, 1); + assert.equal(details.observedRotation, 2); + return true; + }, + ); + // Reads: the first plus one per 500 ms poll up to t = 14 500. The wait that landed on + // t = 15 000 bought no further read, so every read ran on its real budget. + assert.equal(calls.filter((call) => call[1] === 'dumpsys').length, 30); + assert.deepEqual( + probeBudgets, + Array.from({ length: 30 }, (_, index) => 15_000 - 500 * index), + ); + assert.equal(slept.length, 30); + assert.equal(Date.now(), 15_000); + }); + }, + ); + } finally { + vi.useRealTimers(); + } +}); + +test('a display read that fails on a real budget stays a probe failure after an answered read', async () => { + // Deadline admission refuses only a read that would have no budget left. Here the second read is + // admitted at t = 500 with a real 14 500 ms budget and fails inside it, so that failure is the + // fact — the rotation an earlier read saw must not turn it into "did not take effect". + vi.useFakeTimers({ now: 0, toFake: ['Date'] }); + let reads = 0; + try { + await withFakeAdb( + (args, options) => { + if (args[1] !== 'dumpsys') return undefined; + reads += 1; + if (reads > 1) { + vi.setSystemTime(Date.now() + (options?.timeoutMs ?? 0)); + return new Error('adb shell dumpsys display exited with code 1'); + } + return ' mCurrentOrientation=0\n'; + }, + async ({ calls, device }) => { + await withClockConsumingOrientationWait(async () => { + await assert.rejects( + setAndroidOrientation(device, 'landscape-left'), + (error: unknown) => { + assert.ok(error instanceof Error); + assert.doesNotMatch(error.message, /did not take effect/); + assert.match( + error.message, + /orientation landscape-left could not confirm the display rotation: adb shell dumpsys display exited with code 1/, + ); + return true; + }, + ); + assert.equal(calls.filter((call) => call[1] === 'dumpsys').length, 2); + }); + }, + ); + } finally { + vi.useRealTimers(); + } +}); + test('a display probe that hangs for the whole budget ends the settle as a failure', async () => { vi.useFakeTimers({ now: 0, toFake: ['Date'] }); try { @@ -612,6 +742,30 @@ test('setAndroidOrientation leaves a display that reports no rotation to the set }); }); +test('the target rotation reached by a later in-budget read ends the settle as success', async () => { + // The closest negative to the deadline cases: the display rotates at the last admitted poll, so + // the settle returns on that read and the next wait is never taken. + vi.useFakeTimers({ now: 0, toFake: ['Date'] }); + const display = displayReporting(['0', '0', '1']); + try { + await withFakeAdb( + (args) => { + if (args[1] === 'dumpsys') vi.setSystemTime(Date.now() + 400); + return display(args); + }, + async ({ calls, device }) => { + await withClockConsumingOrientationWait(async (slept) => { + await setAndroidOrientation(device, 'landscape-left'); + assert.equal(calls.filter((call) => call[1] === 'dumpsys').length, 3); + assert.deepEqual(slept, [500, 500]); + }); + }, + ); + } finally { + vi.useRealTimers(); + } +}); + test('unlockAndroidOrientation turns auto-rotate on and neither writes user_rotation nor polls', async () => { await withFakeAdb(displayReporting(['1']), async ({ calls, device }) => { await unlockAndroidOrientation(device); diff --git a/packages/platform-android/src/input-actions.ts b/packages/platform-android/src/input-actions.ts index 2d0b5656d9..15daaecdfd 100644 --- a/packages/platform-android/src/input-actions.ts +++ b/packages/platform-android/src/input-actions.ts @@ -166,6 +166,11 @@ async function settleAndroidOrientation( let observed = await readAndroidDisplayRotation(device, orientation, deadline); while (observed !== undefined && observed !== userRotation && Date.now() < deadline) { await sleep(Math.min(ORIENTATION_SETTLE_POLL_MS, remainingMs(deadline))); + // The wait can consume the rest of the budget. A read admitted at or after the deadline would + // run on `remainingMs`'s 1 ms floor, could never answer, and its adb timeout would replace the + // "did not take effect" fact below (#4562). Recheck the deadline after the wait and keep the + // rotation the last in-budget read reported. + if (Date.now() >= deadline) break; observed = await readAndroidDisplayRotation(device, orientation, deadline); } if (observed === undefined || observed === userRotation) return; From 67a44f542e8b5b1f601c4df94a790a12a1a92f9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 08:18:21 +0100 Subject: [PATCH 2/4] fix(android): reserve time before admitting orientation reads --- .../src/__tests__/input-actions.test.ts | 78 ++++++++++++++++++- .../platform-android/src/input-actions.ts | 29 ++++--- 2 files changed, 94 insertions(+), 13 deletions(-) diff --git a/packages/platform-android/src/__tests__/input-actions.test.ts b/packages/platform-android/src/__tests__/input-actions.test.ts index b1c2f07db4..8d361fc363 100644 --- a/packages/platform-android/src/__tests__/input-actions.test.ts +++ b/packages/platform-android/src/__tests__/input-actions.test.ts @@ -649,8 +649,84 @@ test('a wait that lands on the deadline ends the settle on the last rotation, no } }); +test('positive-cost orientation reads leave the last rotation when the next probe would be starved', async () => { + vi.useFakeTimers({ now: 0, toFake: ['Date'] }); + const probeBudgets: number[] = []; + let reads = 0; + try { + await withFakeAdb( + (args, options) => { + if (args[1] !== 'dumpsys') return undefined; + const budget = options?.timeoutMs ?? 0; + probeBudgets.push(budget); + const cost = reads === 0 ? 50 : 100; + reads += 1; + vi.setSystemTime(Date.now() + Math.min(cost, budget)); + if (budget < cost) return new Error(`dumpsys timed out after ${budget}ms`); + return ' mCurrentOrientation=0\n'; + }, + async ({ device }) => { + await withClockConsumingOrientationWait(async () => { + await assert.rejects( + setAndroidOrientation(device, 'landscape-left'), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.match(error.message, /did not take effect/); + assert.equal(error.details?.observedRotation, 0); + return true; + }, + ); + }); + assert.equal(reads, 25); + assert.equal(probeBudgets.at(-1), 650); + assert.equal(Date.now(), 14_950); + }, + ); + } finally { + vi.useRealTimers(); + } +}); + +for (const remaining of [299, 300]) { + test(`orientation probe admission after a delayed wait with ${remaining}ms left`, async () => { + vi.useFakeTimers({ now: 0, toFake: ['Date'] }); + const probeBudgets: number[] = []; + orientationWait.onSleep = () => vi.setSystemTime(15_000 - remaining); + try { + await withFakeAdb( + (args, options) => { + if (args[1] !== 'dumpsys') return undefined; + probeBudgets.push(options?.timeoutMs ?? 0); + vi.setSystemTime(Date.now() + 100); + return ` mCurrentOrientation=${probeBudgets.length === 1 ? 0 : 1}\n`; + }, + async ({ device }) => { + if (remaining === 300) { + await setAndroidOrientation(device, 'landscape-left'); + assert.deepEqual(probeBudgets, [15_000, 300]); + } else { + await assert.rejects( + setAndroidOrientation(device, 'landscape-left'), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.match(error.message, /did not take effect/); + assert.equal(error.details?.observedRotation, 0); + return true; + }, + ); + assert.deepEqual(probeBudgets, [15_000]); + } + }, + ); + } finally { + orientationWait.onSleep = undefined; + vi.useRealTimers(); + } + }); +} + test('a display read that fails on a real budget stays a probe failure after an answered read', async () => { - // Deadline admission refuses only a read that would have no budget left. Here the second read is + // Admission rejects starved reads. Here the second read is // admitted at t = 500 with a real 14 500 ms budget and fails inside it, so that failure is the // fact — the rotation an earlier read saw must not turn it into "did not take effect". vi.useFakeTimers({ now: 0, toFake: ['Date'] }); diff --git a/packages/platform-android/src/input-actions.ts b/packages/platform-android/src/input-actions.ts index 15daaecdfd..6ad01a0183 100644 --- a/packages/platform-android/src/input-actions.ts +++ b/packages/platform-android/src/input-actions.ts @@ -148,6 +148,8 @@ export async function unlockAndroidOrientation(device: DeviceInfo): Promise { const deadline = Date.now() + ORIENTATION_SETTLE_TIMEOUT_MS; - let observed = await readAndroidDisplayRotation(device, orientation, deadline); - while (observed !== undefined && observed !== userRotation && Date.now() < deadline) { + let observed = await readAndroidDisplayRotation(device, orientation, remainingMs(deadline)); + while ( + observed !== undefined && + observed !== userRotation && + hasOrientationReadBudget(remainingMs(deadline)) + ) { await sleep(Math.min(ORIENTATION_SETTLE_POLL_MS, remainingMs(deadline))); - // The wait can consume the rest of the budget. A read admitted at or after the deadline would - // run on `remainingMs`'s 1 ms floor, could never answer, and its adb timeout would replace the - // "did not take effect" fact below (#4562). Recheck the deadline after the wait and keep the - // rotation the last in-budget read reported. - if (Date.now() >= deadline) break; - observed = await readAndroidDisplayRotation(device, orientation, deadline); + const readBudgetMs = remainingMs(deadline); + if (!hasOrientationReadBudget(readBudgetMs)) break; + observed = await readAndroidDisplayRotation(device, orientation, readBudgetMs); } if (observed === undefined || observed === userRotation) return; throw new AppError( @@ -192,12 +195,10 @@ async function settleAndroidOrientation( async function readAndroidDisplayRotation( device: DeviceInfo, orientation: DeviceRotation, - deadline: number, + timeoutMs: number, ): Promise { try { - return ( - await readAndroidDisplayRotationIndices(device, { timeoutMs: remainingMs(deadline) }) - )[0]; + return (await readAndroidDisplayRotationIndices(device, { timeoutMs }))[0]; } catch (error) { throw new AppError( 'COMMAND_FAILED', @@ -207,6 +208,10 @@ async function readAndroidDisplayRotation( } } +function hasOrientationReadBudget(budgetMs: number): boolean { + return budgetMs >= MIN_ORIENTATION_READ_BUDGET_MS; +} + function remainingMs(deadline: number): number { return Math.max(1, deadline - Date.now()); } From 984b94ef3a680907abc228ee14c39d1c1e97ca14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 19:47:47 +0100 Subject: [PATCH 3/4] test(android): preserve orientation success-path latency --- .../src/__tests__/input-actions.test.ts | 38 ++++++++++++++++--- 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/platform-android/src/__tests__/input-actions.test.ts b/packages/platform-android/src/__tests__/input-actions.test.ts index 8d361fc363..e47411bae3 100644 --- a/packages/platform-android/src/__tests__/input-actions.test.ts +++ b/packages/platform-android/src/__tests__/input-actions.test.ts @@ -549,12 +549,38 @@ function displayReporting(rotations: string[]): (args: string[]) => string | und }; } -test('setAndroidOrientation locks auto-rotate, sets user rotation, and returns once the display rotated', async () => { - await withFakeAdb(displayReporting(['0', '0', '1']), async ({ calls, device }) => { - await setAndroidOrientation(device, 'landscape-left'); - assert.deepEqual(calls, [...ORIENTATION_CALLS, DISPLAY_READ, DISPLAY_READ, DISPLAY_READ]); - }); -}); +test.each([ + { name: 'already rotated', rotations: ['1'], waits: [] }, + { name: 'first poll', rotations: ['0', '1'], waits: [500] }, + { name: 'second poll', rotations: ['0', '0', '1'], waits: [500, 500] }, +])( + 'orientation latency: $name adds no quiet window or redundant probe', + async ({ rotations, waits }) => { + vi.useFakeTimers({ now: 0, toFake: ['Date'] }); + const answer = displayReporting(rotations); + try { + await withFakeAdb( + (args) => { + if (args[1] === 'dumpsys') vi.setSystemTime(Date.now() + 25); + return answer(args); + }, + async ({ calls, device }) => { + await withClockConsumingOrientationWait(async (slept) => { + await setAndroidOrientation(device, 'landscape-left'); + assert.deepEqual(calls, [...ORIENTATION_CALLS, ...rotations.map(() => DISPLAY_READ)]); + assert.deepEqual(slept, waits); + assert.equal( + Date.now(), + rotations.length * 25 + waits.reduce((sum, wait) => sum + wait, 0), + ); + }); + }, + ); + } finally { + vi.useRealTimers(); + } + }, +); test('setAndroidOrientation fails when the display never reports the requested rotation', async () => { vi.useFakeTimers({ now: 0, toFake: ['Date'] }); From 1404b7cfacaedc665054e8d42699b36ec1305a9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 23:09:48 +0100 Subject: [PATCH 4/4] refactor(android): settle orientation reads with one budget check per wait The loop checked the deadline in its condition and again after the wait, through a helper. Computing the time left once per iteration makes the shape smaller: break when it is below one read's reserve, and let the wait spend only what is above the reserve. The read keeps its deadline-based signature. The orientation tests shrink from about 270 lines to about 50. The three-case latency test.each passed without the fix, the later in-budget-read test repeated one of its cases, and the real-budget probe failure covered pre-existing behaviour, so they are gone. One regression test keeps the case the fix is about: display reads that cost real time must end the settle with the last rotation, never with a starved read's adb timeout. Co-authored-by: Apex by Callstack Co-authored-by: opencode --- .../src/__tests__/input-actions.test.ts | 277 +++--------------- .../platform-android/src/input-actions.ts | 32 +- 2 files changed, 48 insertions(+), 261 deletions(-) diff --git a/packages/platform-android/src/__tests__/input-actions.test.ts b/packages/platform-android/src/__tests__/input-actions.test.ts index e47411bae3..c31b6ff642 100644 --- a/packages/platform-android/src/__tests__/input-actions.test.ts +++ b/packages/platform-android/src/__tests__/input-actions.test.ts @@ -499,39 +499,12 @@ test('pressAndroid dispatches no failure suppression even when one is smuggled p }); // The orientation settle polls at its own interval; the clock is the assertion, not the wait. -// A test arms `onSleep` to make the wait consume wall clock, as a real settle wait does. -const { orientationWait, orientationSleep } = vi.hoisted(() => { - const wait: { slept: number[]; onSleep: ((ms: number) => void) | undefined } = { - slept: [], - onSleep: undefined, - }; - return { - orientationWait: wait, - orientationSleep: async (ms: number) => { - wait.slept.push(ms); - wait.onSleep?.(ms); - }, - }; -}); -vi.mock('@agent-device/host-kit/retry', () => ({ sleep: orientationSleep })); - -/** - * Runs a settle with its wait consuming wall clock, as a real settle wait does, and hands the test - * the waits the loop took. - */ -async function withClockConsumingOrientationWait( - run: (slept: number[]) => Promise, -): Promise { - orientationWait.slept.length = 0; - orientationWait.onSleep = (ms) => { - vi.setSystemTime(Date.now() + ms); - }; - try { - return await run(orientationWait.slept); - } finally { - orientationWait.onSleep = undefined; - } -} +// A fake clock makes the wait consume that clock, as a real wait does. +vi.mock('@agent-device/host-kit/retry', () => ({ + sleep: async (ms: number) => { + if (vi.isFakeTimers()) vi.setSystemTime(Date.now() + ms); + }, +})); const ORIENTATION_CALLS = [ ['shell', 'settings', 'put', 'system', 'accelerometer_rotation', '0'], @@ -549,38 +522,12 @@ function displayReporting(rotations: string[]): (args: string[]) => string | und }; } -test.each([ - { name: 'already rotated', rotations: ['1'], waits: [] }, - { name: 'first poll', rotations: ['0', '1'], waits: [500] }, - { name: 'second poll', rotations: ['0', '0', '1'], waits: [500, 500] }, -])( - 'orientation latency: $name adds no quiet window or redundant probe', - async ({ rotations, waits }) => { - vi.useFakeTimers({ now: 0, toFake: ['Date'] }); - const answer = displayReporting(rotations); - try { - await withFakeAdb( - (args) => { - if (args[1] === 'dumpsys') vi.setSystemTime(Date.now() + 25); - return answer(args); - }, - async ({ calls, device }) => { - await withClockConsumingOrientationWait(async (slept) => { - await setAndroidOrientation(device, 'landscape-left'); - assert.deepEqual(calls, [...ORIENTATION_CALLS, ...rotations.map(() => DISPLAY_READ)]); - assert.deepEqual(slept, waits); - assert.equal( - Date.now(), - rotations.length * 25 + waits.reduce((sum, wait) => sum + wait, 0), - ); - }); - }, - ); - } finally { - vi.useRealTimers(); - } - }, -); +test('setAndroidOrientation locks auto-rotate, sets user rotation, and returns once the display rotated', async () => { + await withFakeAdb(displayReporting(['0', '0', '1']), async ({ calls, device }) => { + await setAndroidOrientation(device, 'landscape-left'); + assert.deepEqual(calls, [...ORIENTATION_CALLS, DISPLAY_READ, DISPLAY_READ, DISPLAY_READ]); + }); +}); test('setAndroidOrientation fails when the display never reports the requested rotation', async () => { vi.useFakeTimers({ now: 0, toFake: ['Date'] }); @@ -617,65 +564,11 @@ test('setAndroidOrientation fails when the display never reports the requested r } }); -test('a wait that lands on the deadline ends the settle on the last rotation, not a floor-budget read', async () => { - // #4562: the deadline was checked only before the wait, so the loop woke at the deadline and - // started one more `dumpsys display` on the 1 ms floor of `remainingMs`. No real read answers - // inside that floor, and its adb timeout replaced the "did not take effect" fact a pinned - // foreground app should produce. Admission is rechecked after the wait, so the settle ends on the - // rotation the last in-budget read reported — here the one the display settled at, not the first - // one it saw — and no read ever runs on a starved budget. - vi.useFakeTimers({ now: 0, toFake: ['Date'] }); - const DISPLAY_ANSWER_MS = 120; - const LAST_ROTATION_FROM_READ = 15; - const probeBudgets: number[] = []; - let reads = 0; - try { - await withFakeAdb( - (args, options) => { - if (args[1] !== 'dumpsys') return undefined; - probeBudgets.push(options?.timeoutMs ?? -1); - if ((options?.timeoutMs ?? 0) < DISPLAY_ANSWER_MS) { - return new Error(`adb shell dumpsys display timed out after ${options?.timeoutMs}ms`); - } - reads += 1; - const rotation = reads >= LAST_ROTATION_FROM_READ ? 2 : 0; - return ` mCurrentOrientation=${rotation}\n`; - }, - async ({ calls, device }) => { - await withClockConsumingOrientationWait(async (slept) => { - await assert.rejects( - setAndroidOrientation(device, 'landscape-left'), - (error: unknown) => { - assert.ok(error instanceof Error); - assert.doesNotMatch(error.message, /could not confirm the display rotation/); - assert.match( - error.message, - /orientation landscape-left did not take effect: the display still reports rotation 2 after 15000ms/, - ); - const details = (error as { details?: Record }).details ?? {}; - assert.equal(details.requestedRotation, 1); - assert.equal(details.observedRotation, 2); - return true; - }, - ); - // Reads: the first plus one per 500 ms poll up to t = 14 500. The wait that landed on - // t = 15 000 bought no further read, so every read ran on its real budget. - assert.equal(calls.filter((call) => call[1] === 'dumpsys').length, 30); - assert.deepEqual( - probeBudgets, - Array.from({ length: 30 }, (_, index) => 15_000 - 500 * index), - ); - assert.equal(slept.length, 30); - assert.equal(Date.now(), 15_000); - }); - }, - ); - } finally { - vi.useRealTimers(); - } -}); - -test('positive-cost orientation reads leave the last rotation when the next probe would be starved', async () => { +test('positive-cost display reads end the settle on the last rotation, never on a starved read', async () => { + // #4562: main slept to the deadline and admitted one final read on the milliseconds left, so a + // real 100 ms `dumpsys display` overran it and its adb timeout replaced the "did not take + // effect" fact a pinned foreground app must see. The loop now keeps one read's reserve (300 ms) + // unspent by the wait: every admitted read can answer, and the last one gets exactly the reserve. vi.useFakeTimers({ now: 0, toFake: ['Date'] }); const probeBudgets: number[] = []; let reads = 0; @@ -683,109 +576,31 @@ test('positive-cost orientation reads leave the last rotation when the next prob await withFakeAdb( (args, options) => { if (args[1] !== 'dumpsys') return undefined; - const budget = options?.timeoutMs ?? 0; - probeBudgets.push(budget); - const cost = reads === 0 ? 50 : 100; + const budgetMs = options?.timeoutMs ?? 0; + probeBudgets.push(budgetMs); + const costMs = reads === 0 ? 50 : 100; reads += 1; - vi.setSystemTime(Date.now() + Math.min(cost, budget)); - if (budget < cost) return new Error(`dumpsys timed out after ${budget}ms`); + vi.setSystemTime(Date.now() + Math.min(costMs, budgetMs)); + if (budgetMs < costMs) + return new Error(`adb shell dumpsys display timed out after ${budgetMs}ms`); return ' mCurrentOrientation=0\n'; }, async ({ device }) => { - await withClockConsumingOrientationWait(async () => { - await assert.rejects( - setAndroidOrientation(device, 'landscape-left'), - (error: unknown) => { - assert.ok(error instanceof AppError); - assert.match(error.message, /did not take effect/); - assert.equal(error.details?.observedRotation, 0); - return true; - }, - ); - }); - assert.equal(reads, 25); - assert.equal(probeBudgets.at(-1), 650); - assert.equal(Date.now(), 14_950); - }, - ); - } finally { - vi.useRealTimers(); - } -}); - -for (const remaining of [299, 300]) { - test(`orientation probe admission after a delayed wait with ${remaining}ms left`, async () => { - vi.useFakeTimers({ now: 0, toFake: ['Date'] }); - const probeBudgets: number[] = []; - orientationWait.onSleep = () => vi.setSystemTime(15_000 - remaining); - try { - await withFakeAdb( - (args, options) => { - if (args[1] !== 'dumpsys') return undefined; - probeBudgets.push(options?.timeoutMs ?? 0); - vi.setSystemTime(Date.now() + 100); - return ` mCurrentOrientation=${probeBudgets.length === 1 ? 0 : 1}\n`; - }, - async ({ device }) => { - if (remaining === 300) { - await setAndroidOrientation(device, 'landscape-left'); - assert.deepEqual(probeBudgets, [15_000, 300]); - } else { - await assert.rejects( - setAndroidOrientation(device, 'landscape-left'), - (error: unknown) => { - assert.ok(error instanceof AppError); - assert.match(error.message, /did not take effect/); - assert.equal(error.details?.observedRotation, 0); - return true; - }, - ); - assert.deepEqual(probeBudgets, [15_000]); - } - }, - ); - } finally { - orientationWait.onSleep = undefined; - vi.useRealTimers(); - } - }); -} - -test('a display read that fails on a real budget stays a probe failure after an answered read', async () => { - // Admission rejects starved reads. Here the second read is - // admitted at t = 500 with a real 14 500 ms budget and fails inside it, so that failure is the - // fact — the rotation an earlier read saw must not turn it into "did not take effect". - vi.useFakeTimers({ now: 0, toFake: ['Date'] }); - let reads = 0; - try { - await withFakeAdb( - (args, options) => { - if (args[1] !== 'dumpsys') return undefined; - reads += 1; - if (reads > 1) { - vi.setSystemTime(Date.now() + (options?.timeoutMs ?? 0)); - return new Error('adb shell dumpsys display exited with code 1'); - } - return ' mCurrentOrientation=0\n'; - }, - async ({ calls, device }) => { - await withClockConsumingOrientationWait(async () => { - await assert.rejects( - setAndroidOrientation(device, 'landscape-left'), - (error: unknown) => { - assert.ok(error instanceof Error); - assert.doesNotMatch(error.message, /did not take effect/); - assert.match( - error.message, - /orientation landscape-left could not confirm the display rotation: adb shell dumpsys display exited with code 1/, - ); - return true; - }, + await assert.rejects(setAndroidOrientation(device, 'landscape-left'), (error: unknown) => { + assert.ok(error instanceof AppError); + assert.doesNotMatch(error.message, /could not confirm the display rotation/); + assert.match( + error.message, + /did not take effect: the display still reports rotation 0 after 15000ms/, ); - assert.equal(calls.filter((call) => call[1] === 'dumpsys').length, 2); + assert.equal(error.details?.observedRotation, 0); + return true; }); }, ); + assert.equal(reads, 26); + assert.equal(Math.min(...probeBudgets), 300); + assert.equal(probeBudgets.at(-1), 300); } finally { vi.useRealTimers(); } @@ -844,30 +659,6 @@ test('setAndroidOrientation leaves a display that reports no rotation to the set }); }); -test('the target rotation reached by a later in-budget read ends the settle as success', async () => { - // The closest negative to the deadline cases: the display rotates at the last admitted poll, so - // the settle returns on that read and the next wait is never taken. - vi.useFakeTimers({ now: 0, toFake: ['Date'] }); - const display = displayReporting(['0', '0', '1']); - try { - await withFakeAdb( - (args) => { - if (args[1] === 'dumpsys') vi.setSystemTime(Date.now() + 400); - return display(args); - }, - async ({ calls, device }) => { - await withClockConsumingOrientationWait(async (slept) => { - await setAndroidOrientation(device, 'landscape-left'); - assert.equal(calls.filter((call) => call[1] === 'dumpsys').length, 3); - assert.deepEqual(slept, [500, 500]); - }); - }, - ); - } finally { - vi.useRealTimers(); - } -}); - test('unlockAndroidOrientation turns auto-rotate on and neither writes user_rotation nor polls', async () => { await withFakeAdb(displayReporting(['1']), async ({ calls, device }) => { await unlockAndroidOrientation(device); diff --git a/packages/platform-android/src/input-actions.ts b/packages/platform-android/src/input-actions.ts index 6ad01a0183..37908f53d0 100644 --- a/packages/platform-android/src/input-actions.ts +++ b/packages/platform-android/src/input-actions.ts @@ -148,7 +148,8 @@ export async function unlockAndroidOrientation(device: DeviceInfo): Promise { const deadline = Date.now() + ORIENTATION_SETTLE_TIMEOUT_MS; - let observed = await readAndroidDisplayRotation(device, orientation, remainingMs(deadline)); - while ( - observed !== undefined && - observed !== userRotation && - hasOrientationReadBudget(remainingMs(deadline)) - ) { - await sleep(Math.min(ORIENTATION_SETTLE_POLL_MS, remainingMs(deadline))); - const readBudgetMs = remainingMs(deadline); - if (!hasOrientationReadBudget(readBudgetMs)) break; - observed = await readAndroidDisplayRotation(device, orientation, readBudgetMs); + let observed = await readAndroidDisplayRotation(device, orientation, deadline); + while (observed !== undefined && observed !== userRotation) { + // The wait spends only what is above one read's reserve, so every admitted read can answer. + const leftMs = deadline - Date.now(); + if (leftMs < MIN_ORIENTATION_READ_BUDGET_MS) break; + await sleep(Math.min(ORIENTATION_SETTLE_POLL_MS, leftMs - MIN_ORIENTATION_READ_BUDGET_MS)); + observed = await readAndroidDisplayRotation(device, orientation, deadline); } if (observed === undefined || observed === userRotation) return; throw new AppError( @@ -195,10 +193,12 @@ async function settleAndroidOrientation( async function readAndroidDisplayRotation( device: DeviceInfo, orientation: DeviceRotation, - timeoutMs: number, + deadline: number, ): Promise { try { - return (await readAndroidDisplayRotationIndices(device, { timeoutMs }))[0]; + return ( + await readAndroidDisplayRotationIndices(device, { timeoutMs: remainingMs(deadline) }) + )[0]; } catch (error) { throw new AppError( 'COMMAND_FAILED', @@ -208,10 +208,6 @@ async function readAndroidDisplayRotation( } } -function hasOrientationReadBudget(budgetMs: number): boolean { - return budgetMs >= MIN_ORIENTATION_READ_BUDGET_MS; -} - function remainingMs(deadline: number): number { return Math.max(1, deadline - Date.now()); } @@ -248,7 +244,7 @@ async function readAndroidDisplayRotationIndices( */ export async function probeAndroidDisplayRotation( device: DeviceInfo, - options: { timeoutMs: number; signal: AbortSignal }, + options: { timeoutMs: number; signal?: AbortSignal }, ): Promise { try { const indices = await readAndroidDisplayRotationIndices(device, options);