Skip to content

Commit b3578cb

Browse files
thymikeeclaude
andcommitted
fix(ios): press Open again when the runner watchdog abandons the launch-URL accept
On a freshly started runner, the launch confirmation's Open press can time out on the runner's main-thread watchdog (MAIN_THREAD_TIMEOUT) while the "Open in" prompt stays up, and open then failed with launch_confirmation_unanswered with budget to spare. The answer now presses Open again while the same confirmation is still up, within a 25-second accept budget that holds a whole press. Any other accept failure, or a prompt that is gone, ends the answer as before. Fixes #3861 Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3537dc5 commit b3578cb

6 files changed

Lines changed: 132 additions & 8 deletions

File tree

‎packages/platform-apple/src/launch-confirmation.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { expect, test, vi } from 'vitest';
2+
import { DEFAULT_ALERT_TIMEOUT_MS } from '@agent-device/contracts/alert-contract';
23
import { awaitAppleAlert, readAppleAlert } from './alert.ts';
34
import { runAppleRunnerCommand } from './core/runner-client.ts';
45
import type { Interactor } from '@agent-device/contracts/interactor-types';
@@ -19,6 +20,10 @@ import {
1920
URL_OWNER_LOOKUP_TIMEOUT_MS,
2021
} from './launch-confirmation.ts';
2122
import { alertNotFound, CONFIRMATION } from './launch-confirmation.fixtures.ts';
23+
import {
24+
buildRunnerResponseError,
25+
MAIN_THREAD_TIMEOUT_RUNNER_CODE,
26+
} from './runner/runner-contract.ts';
2227

2328
vi.mock('./core/runner-client.ts', () => ({ runAppleRunnerCommand: vi.fn() }));
2429

@@ -579,3 +584,68 @@ test('a matching launch title with other buttons is left unanswered on the first
579584
expect(device.awaitAlert).toHaveBeenCalledOnce();
580585
expect(acceptAlert).not.toHaveBeenCalled();
581586
});
587+
588+
/** The accept as the runner answers it when its main-thread watchdog abandons the press (#3861). */
589+
function runnerMainThreadTimeout(): AppError {
590+
return buildRunnerResponseError({
591+
ok: false,
592+
error: { code: MAIN_THREAD_TIMEOUT_RUNNER_CODE, message: 'main thread execution timed out' },
593+
});
594+
}
595+
596+
test('an accept the runner watchdog abandoned is pressed again while the confirmation is up', async () => {
597+
const acceptAlert = vi
598+
.fn<() => Promise<unknown>>()
599+
.mockRejectedValueOnce(runnerMainThreadTimeout())
600+
.mockResolvedValueOnce({});
601+
const { port: device } = port(async () => CONFIRMATION, { acceptAlert });
602+
603+
await expect(answerLaunchConfirmation(device)).resolves.toEqual({ outcome: 'accepted' });
604+
expect(acceptAlert).toHaveBeenCalledTimes(2);
605+
});
606+
607+
test('the watchdog message without the runner code is not pressed again', async () => {
608+
const acceptAlert = vi.fn(async () => {
609+
throw new AppError('COMMAND_FAILED', 'main thread execution timed out');
610+
});
611+
const { port: device } = port(async () => CONFIRMATION, { acceptAlert });
612+
613+
await expect(answerLaunchConfirmation(device)).resolves.toEqual({
614+
outcome: 'unanswered',
615+
reason: 'alert-still-present',
616+
});
617+
expect(acceptAlert).toHaveBeenCalledOnce();
618+
});
619+
620+
test('an abandoned accept that removed the confirmation is not pressed again', async () => {
621+
const acceptAlert = vi.fn(async () => {
622+
throw runnerMainThreadTimeout();
623+
});
624+
const { port: device } = port(async () => CONFIRMATION, { acceptAlert });
625+
vi.mocked(device.readAlert).mockResolvedValue(undefined);
626+
627+
await expect(answerLaunchConfirmation(device)).resolves.toEqual({
628+
outcome: 'unreadable',
629+
step: 'alert-accept',
630+
});
631+
expect(acceptAlert).toHaveBeenCalledOnce();
632+
});
633+
634+
test('abandoned accepts stop once the answer budget cannot hold another press', async () => {
635+
vi.useFakeTimers({ toFake: ['Date'] });
636+
try {
637+
const acceptAlert = vi.fn(async () => {
638+
vi.advanceTimersByTime(DEFAULT_ALERT_TIMEOUT_MS);
639+
throw runnerMainThreadTimeout();
640+
});
641+
const { port: device } = port(async () => CONFIRMATION, { acceptAlert });
642+
643+
await expect(answerLaunchConfirmation(device)).resolves.toEqual({
644+
outcome: 'unanswered',
645+
reason: 'alert-still-present',
646+
});
647+
expect(acceptAlert).toHaveBeenCalledTimes(2);
648+
} finally {
649+
vi.useRealTimers();
650+
}
651+
});

‎packages/platform-apple/src/launch-confirmation.ts‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
import { DEFAULT_ALERT_TIMEOUT_MS } from '@agent-device/contracts/alert-contract';
12
import type { Interactor } from '@agent-device/contracts/interactor-types';
23
import { invalidRuntimeContract } from '@agent-device/contracts/runtime-contract-error';
34
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
5+
import { Deadline } from '@agent-device/host-kit/retry';
46
import type { DeviceInfo } from '@agent-device/kernel/device';
57
import { AppError } from '@agent-device/kernel/errors';
68
import { alertIfPresent } from './alert.ts';
79
import { resolveIosSimulatorDeepLinkBundleId } from './core/app-resolution.ts';
10+
import { isRunnerMainThreadTimeoutError } from './runner/runner-error-classification.ts';
811

912
export const LAUNCH_CONFIRMATION_FOREIGN_APP_REASON = 'launch_confirmation_foreign_app';
1013

@@ -46,6 +49,15 @@ const LAUNCH_CONFIRMATION_TITLE = /^Open in [“"].+[”"]\?$/u;
4649
*/
4750
export const URL_OWNER_LOOKUP_TIMEOUT_MS = 10_000;
4851

52+
/**
53+
* How long one answer may keep pressing `Open` after the runner's main-thread watchdog abandoned a
54+
* press and the confirmation stayed up (#3861). A runner that has just started can stall its first
55+
* press and serve the next. Another press starts only while the budget still holds the press's own
56+
* runner bound, `DEFAULT_ALERT_TIMEOUT_MS`, so the presses end within the budget, well inside the
57+
* open's request envelope.
58+
*/
59+
const LAUNCH_CONFIRMATION_ACCEPT_BUDGET_MS = 25_000;
60+
4961
/** A custom-scheme launch URL SpringBoard may hold for the session app it was checked for. */
5062
export type LaunchConfirmationTarget = Readonly<{ url: string; appBundleId: string }>;
5163

@@ -101,9 +113,44 @@ export async function answerLaunchConfirmation(
101113
hint: `iOS is asking whether to open ${owner.owner}. Answer it with alert accept or alert dismiss, and pass a launch URL whose scheme belongs to the session app.`,
102114
});
103115
}
104-
return await port
105-
.acceptAlert()
106-
.then(accepted, async (error: unknown) => await verifyFailedAcceptance(port, alert, error));
116+
return await acceptConfirmation(
117+
port,
118+
alert,
119+
Deadline.fromTimeoutMs(LAUNCH_CONFIRMATION_ACCEPT_BUDGET_MS),
120+
);
121+
}
122+
123+
/**
124+
* Presses `Open` and verifies a failed press. Only a press the runner's watchdog abandoned, with the
125+
* same confirmation still up, is pressed again, while the budget holds another whole press. Any
126+
* other failure, and a confirmation that is gone, ends the answer at once.
127+
*/
128+
async function acceptConfirmation(
129+
port: LaunchConfirmationPort,
130+
original: Record<string, unknown>,
131+
budget: Deadline,
132+
): Promise<LaunchConfirmationAttempt> {
133+
for (;;) {
134+
const failure = await port.acceptAlert().then(
135+
() => undefined,
136+
(error: unknown) => ({ error }),
137+
);
138+
if (!failure) return accepted();
139+
const attempt = await verifyFailedAcceptance(port, original, failure.error);
140+
if (attempt.outcome !== 'unanswered') return attempt;
141+
if (
142+
!isRunnerMainThreadTimeoutError(failure.error) ||
143+
budget.remainingMs() < DEFAULT_ALERT_TIMEOUT_MS
144+
) {
145+
reportUnanswered('alert-still-present', {});
146+
return attempt;
147+
}
148+
emitDiagnostic({
149+
level: 'debug',
150+
phase: 'ios_launch_confirmation_reaccept',
151+
data: { reason: 'runner-main-thread-timeout', remainingMs: budget.remainingMs() },
152+
});
153+
}
107154
}
108155

109156
async function verifyFailedAcceptance(
@@ -118,7 +165,6 @@ async function verifyFailedAcceptance(
118165
isLaunchConfirmation(read.alert) &&
119166
read.alert['message'] === original['message']
120167
) {
121-
reportUnanswered('alert-still-present', {});
122168
return { outcome: 'unanswered', reason: 'alert-still-present' };
123169
}
124170
return unreadable('alert-accept')(error);

‎packages/platform-apple/src/open-policy.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,8 @@ export async function settleAppleOpen(
198198
* process is a launch that was lost, so the URL is handed over again and read once more.
199199
*
200200
* Every step keeps the bound it already had: `openurl` at `IOS_SIMULATOR_OPENURL_TIMEOUT_MS`, the
201-
* read and accept at the runner's alert timeouts, and the observation at the discovery deadline and
201+
* read and accept at the runner's alert timeouts (an accept the runner watchdog abandoned is pressed
202+
* again only within the answer's accept budget), and the observation at the discovery deadline and
202203
* the bridge's own launch-transition windows. Nothing here adds an unbounded wait.
203204
*/
204205
async function answerHeldLaunch(

‎packages/platform-apple/src/runner/runner-error-classification.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -663,7 +663,14 @@ export function isRetryableRunnerError(err: unknown): boolean {
663663
* `details.runnerErrorCode`), so family policy reads the typed detail rather than the message.
664664
*/
665665
export function isRunnerMainThreadOccupiedError(error: unknown): boolean {
666-
if (isRunnerBusyError(error)) return true;
666+
return isRunnerBusyError(error) || isRunnerMainThreadTimeoutError(error);
667+
}
668+
669+
/**
670+
* True when the runner's execution watchdog abandoned this command's main-thread work
671+
* (`MAIN_THREAD_TIMEOUT`). The command ran, so its effect is unknown, not refused.
672+
*/
673+
export function isRunnerMainThreadTimeoutError(error: unknown): boolean {
667674
return (
668675
error instanceof AppError && error.details?.runnerErrorCode === MAIN_THREAD_TIMEOUT_RUNNER_CODE
669676
);

‎src/commands/management/app.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ export const openCommandFacet = defineCommandFacet({
199199
text: {
200200
summary: 'Open an app, deep link or URL, save replays',
201201
cliDetail:
202-
'Use --platform to bind URL/deep-link opens to the target platform. For local iOS simulator initial stdout/stderr, put --launch-console <path> on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+<slug> scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in <App>?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than a translated launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. A recognized prompt still visible after a failed accept also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. Only the English prompt title with Cancel and Open buttons is recognized, so on a Simulator set to another language the prompt stays on screen. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait <ms> to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session.',
202+
'Use --platform to bind URL/deep-link opens to the target platform. For local iOS simulator initial stdout/stderr, put --launch-console <path> on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+<slug> scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in <App>?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than a translated launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again while a 25-second accept budget still holds a whole press. A recognized prompt still visible after a failed accept, or after that budget, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. Only the English prompt title with Cancel and Open buttons is recognized, so on a Simulator set to another language the prompt stays on screen. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait <ms> to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session.',
203203
mcpDetail:
204204
"metroHost, metroPort, and bundleUrl choose the app's Metro server and save its address for later reloads. launchUrl selects the app's launch URL and does not select the reload server. A fresh open without Metro hints clears an older same-name binding; close also clears it.",
205205
},

‎website/docs/docs/commands.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ iOS Simulator launch behavior:
111111
- When `open <app> --launch-url <url>` raises an `Open in "<App>"?` prompt and the URL's scheme belongs to the session app, `open` taps **Open** and returns `launchConfirmation: "accepted"`. If the app still never starts, `open` hands over the URL once more.
112112
- When that prompt stays unanswered, `open` returns `launchConfirmation: "unanswered"` with `launchConfirmationReason`: `alert-unrecognized` for a prompt it did not recognize (such as a non-English Simulator), or `url-owner-unresolved` when no single installed app owns the URL's scheme or that lookup failed. The prompt stays on screen; `warnings` name the next step. For `url-owner-unresolved`, answer the prompt with `alert accept`. For `alert-unrecognized`, read the alert with `alert get` first: it can be the app's own alert, such as a permission prompt, rather than a translated launch confirmation. Answer with `alert accept` only when it is the launch confirmation.
113113
- When `open` could not read whether a prompt is up at all (the alert read, the accept, or the runner itself failed), `open` succeeds with `launchConfirmationProbeFailure` set to `alert-read`, `alert-accept`, or `runner` and no `launchConfirmation`, plus a warning to check with `alert get` before retrying.
114-
- `details.reason: launch_confirmation_unanswered` means the app never started after the prompt was accepted, or the prompt stayed visible after a failed tap. Answer it with `alert accept` or `alert dismiss` before continuing.
114+
- `details.reason: launch_confirmation_unanswered` means the app never started after the prompt was accepted, or the prompt stayed visible after a failed tap. When the runner reports its main-thread timeout for the tap and the prompt is still up, `open` taps `Open` again for up to 25 seconds before it fails. Answer it with `alert accept` or `alert dismiss` before continuing.
115115
- `details.reason: launch_confirmation_foreign_app` means another installed app owns the scheme (`details.foreignAppBundleId`). Close the prompt with `alert dismiss` and pass a URL your app handles.
116116
- A prompt that appears after `open` has already seen the app is not reported and not answered; use `alert accept`.
117117

0 commit comments

Comments
 (0)