Skip to content

Commit 0e64832

Browse files
committed
fix(ios): bound simulator URL opens
1 parent 75810a1 commit 0e64832

6 files changed

Lines changed: 109 additions & 12 deletions

File tree

‎packages/platform-apple/src/core/__tests__/app-launch-url.test.ts‎

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { beforeEach, test, vi } from 'vitest';
22
import assert from 'node:assert/strict';
3+
import { AppError } from '@agent-device/kernel/errors';
34
import { IOS_TEST_SIMULATOR } from './apple-core-stub-helpers.ts';
4-
import { IOS_SIMULATOR_TERMINATE_TIMEOUT_MS } from '../config.ts';
5+
import { IOS_SIMULATOR_OPENURL_TIMEOUT_MS, IOS_SIMULATOR_TERMINATE_TIMEOUT_MS } from '../config.ts';
56

67
vi.mock('@agent-device/host-kit/command', async (importOriginal) => {
78
const actual = await importOriginal<typeof import('@agent-device/host-kit/command')>();
@@ -41,6 +42,62 @@ test('iOS simulator URL relaunch terminates the app before opening the URL', asy
4142
timeoutMs: IOS_SIMULATOR_TERMINATE_TIMEOUT_MS,
4243
},
4344
],
44-
['xcrun', ['simctl', 'openurl', 'sim-1', 'myapp://automation'], undefined],
45+
[
46+
'xcrun',
47+
['simctl', 'openurl', 'sim-1', 'myapp://automation'],
48+
{
49+
timeoutMs: IOS_SIMULATOR_OPENURL_TIMEOUT_MS,
50+
},
51+
],
4552
]);
4653
});
54+
55+
test('iOS simulator URL open times out a hanging provider with unknown dispatch', async () => {
56+
vi.useFakeTimers();
57+
try {
58+
mockRunCmd.mockImplementation(
59+
async (_cmd, _args, options) =>
60+
await new Promise((_resolve, reject) => {
61+
const timeoutMs = options?.timeoutMs ?? 0;
62+
setTimeout(() => {
63+
reject(
64+
new AppError('COMMAND_FAILED', 'xcrun timed out', {
65+
timeoutMs,
66+
}),
67+
);
68+
}, timeoutMs);
69+
}),
70+
);
71+
72+
const pending = openIosApp(IOS_TEST_SIMULATOR, 'MyApp', {
73+
appBundleId: 'com.example.app',
74+
url: 'myapp://automation',
75+
}).catch((error: unknown) => error);
76+
77+
await Promise.resolve();
78+
assert.equal(mockRunCmd.mock.calls[0]?.[2]?.timeoutMs, IOS_SIMULATOR_OPENURL_TIMEOUT_MS);
79+
await vi.advanceTimersByTimeAsync(IOS_SIMULATOR_OPENURL_TIMEOUT_MS);
80+
const failure = await pending;
81+
82+
assert.ok(failure instanceof AppError);
83+
assert.equal(failure.code, 'COMMAND_FAILED');
84+
assert.equal(failure.details?.reason, 'ios-simulator-openurl-timeout');
85+
assert.equal(failure.details?.dispatched, 'unknown');
86+
assert.equal(failure.details?.timeoutMs, IOS_SIMULATOR_OPENURL_TIMEOUT_MS);
87+
} finally {
88+
vi.useRealTimers();
89+
}
90+
});
91+
92+
test('iOS simulator URL open forwards the request signal to simctl openurl', async () => {
93+
const controller = new AbortController();
94+
95+
await openIosApp(IOS_TEST_SIMULATOR, 'MyApp', {
96+
appBundleId: 'com.example.app',
97+
runnerOptions: { signal: controller.signal },
98+
url: 'myapp://automation',
99+
});
100+
101+
assert.equal(mockRunCmd.mock.calls.length, 1);
102+
assert.equal(mockRunCmd.mock.calls[0]?.[2]?.signal, controller.signal);
103+
});

‎packages/platform-apple/src/core/__tests__/apps.test.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import { screenshotIos } from '../screenshot.ts';
3232
import { withMockedMacOsHelper } from './macos-helper-test-utils.ts';
3333
import { quitMacOsApp, resolveMacOsHelperPackageRootFrom } from '../../os/macos/helper.ts';
3434
import { ensureBootedSimulator } from '../simulator.ts';
35-
import { IOS_SIMULATOR_TERMINATE_TIMEOUT_MS } from '../config.ts';
35+
import { IOS_SIMULATOR_OPENURL_TIMEOUT_MS, IOS_SIMULATOR_TERMINATE_TIMEOUT_MS } from '../config.ts';
3636
import type { DeviceInfo } from '@agent-device/kernel/device';
3737
import { runCmd } from '@agent-device/host-kit/command';
3838
import { retryWithPolicy } from '@agent-device/host-kit/retry';
@@ -407,7 +407,9 @@ test('openIosApp opens custom-scheme iOS simulator URLs directly when launch arg
407407
assert.deepEqual(mockRunCmd.mock.calls[0], [
408408
'xcrun',
409409
['simctl', 'openurl', 'sim-1', 'myapp://item/42'],
410-
undefined,
410+
{
411+
timeoutMs: IOS_SIMULATOR_OPENURL_TIMEOUT_MS,
412+
},
411413
]);
412414
});
413415

@@ -432,7 +434,9 @@ test('openIosApp launches iOS simulator app before opening custom-scheme URL wit
432434
assert.deepEqual(mockRunCmd.mock.calls[1], [
433435
'xcrun',
434436
['simctl', 'openurl', 'sim-1', 'myapp://item/42'],
435-
undefined,
437+
{
438+
timeoutMs: IOS_SIMULATOR_OPENURL_TIMEOUT_MS,
439+
},
436440
]);
437441
});
438442

@@ -457,7 +461,9 @@ test('openIosApp launches iOS simulator app before opening https URL with launch
457461
assert.deepEqual(mockRunCmd.mock.calls[1], [
458462
'xcrun',
459463
['simctl', 'openurl', 'sim-1', 'https://example.com/item/42'],
460-
undefined,
464+
{
465+
timeoutMs: IOS_SIMULATOR_OPENURL_TIMEOUT_MS,
466+
},
461467
]);
462468
});
463469

‎packages/platform-apple/src/core/app-launch.ts‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import path from 'node:path';
22
import { isIosFamily, isMacOs, type DeviceInfo } from '@agent-device/kernel/device';
33
import { AppError } from '@agent-device/kernel/errors';
4-
import { execFailureDetails } from '@agent-device/host-kit/command';
4+
import { execFailureDetails, isCommandTimeoutError } from '@agent-device/host-kit/command';
55
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
66
import { ensureHostDirectory, writeHostTextFile } from '@agent-device/host-kit/host-file';
77
import { Deadline, retryWithPolicy } from '@agent-device/host-kit/retry';
@@ -16,7 +16,11 @@ import {
1616
isWebUrl,
1717
resolveIosDeviceDeepLinkBundleId,
1818
} from '@agent-device/contracts/command';
19-
import { IOS_APP_LAUNCH_TIMEOUT_MS, IOS_SIMULATOR_TERMINATE_TIMEOUT_MS } from './config.ts';
19+
import {
20+
IOS_APP_LAUNCH_TIMEOUT_MS,
21+
IOS_SIMULATOR_OPENURL_TIMEOUT_MS,
22+
IOS_SIMULATOR_TERMINATE_TIMEOUT_MS,
23+
} from './config.ts';
2024
import { resolveIosPhysicalDeviceControl } from './physical-device-control.ts';
2125
import { runAppleRunnerCommand } from './runner-client.ts';
2226
import type { AppleRunnerCommandOptions } from '../runner/index.ts';
@@ -85,7 +89,7 @@ export async function openIosApp(
8589
await terminateIosSimulatorApp(device, bundleId);
8690
}
8791
}
88-
await openIosSimulatorUrl(device, explicitUrl, undefined);
92+
await openIosSimulatorUrl(device, explicitUrl, undefined, options?.runnerOptions?.signal);
8993
return;
9094
}
9195
const appBundleId = options?.appBundleId ?? (await resolveIosApp(device, app));
@@ -110,7 +114,7 @@ export async function openIosApp(
110114
throw new AppError('INVALID_ARGS', LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE);
111115
}
112116
if (device.kind === 'simulator') {
113-
await openIosSimulatorUrl(device, deepLinkTarget, launchArgs);
117+
await openIosSimulatorUrl(device, deepLinkTarget, launchArgs, options?.runnerOptions?.signal);
114118
return;
115119
}
116120
const bundleId = resolveIosDeviceDeepLinkBundleId(options?.appBundleId, deepLinkTarget);
@@ -148,12 +152,32 @@ async function openIosSimulatorUrl(
148152
device: DeviceInfo,
149153
url: string,
150154
launchArgs: string[] | undefined,
155+
signal: AbortSignal | undefined,
151156
): Promise<void> {
152157
if (launchArgs && launchArgs.length > 0) {
153158
throw new AppError('INVALID_ARGS', IOS_SIMULATOR_LAUNCH_ARGS_WITH_URL_MESSAGE);
154159
}
155160
await ensureBootedSimulator(device);
156-
await runSimctlForDevice(device, ['openurl', device.id, url]);
161+
try {
162+
await runSimctlForDevice(device, ['openurl', device.id, url], {
163+
timeoutMs: IOS_SIMULATOR_OPENURL_TIMEOUT_MS,
164+
...(signal ? { signal } : {}),
165+
});
166+
} catch (error) {
167+
if (!isCommandTimeoutError(error)) throw error;
168+
throw new AppError(
169+
'COMMAND_FAILED',
170+
`iOS Simulator URL open timed out after ${IOS_SIMULATOR_OPENURL_TIMEOUT_MS}ms`,
171+
{
172+
...error.details,
173+
reason: 'ios-simulator-openurl-timeout',
174+
dispatched: 'unknown',
175+
timeoutMs: IOS_SIMULATOR_OPENURL_TIMEOUT_MS,
176+
hint: 'CoreSimulator did not finish simctl openurl before the local bound; the URL may already have been delivered, so inspect the app state before retrying.',
177+
},
178+
error,
179+
);
180+
}
157181
}
158182

159183
export async function openIosDevice(device: DeviceInfo): Promise<void> {

‎packages/platform-apple/src/core/config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ export const IOS_DEVICE_INSTALL_TIMEOUT_MS = 120_000;
1212

1313
export const IOS_SIMULATOR_FOCUS_TIMEOUT_MS = 10_000;
1414

15+
export const IOS_SIMULATOR_OPENURL_TIMEOUT_MS = 20_000;
16+
1517
export const IOS_SIMULATOR_TERMINATE_TIMEOUT_MS = 15_000;
1618

1719
export const IOS_SIMULATOR_SCREENSHOT_TIMEOUT_MS = 20_000;

‎src/commands/management/app.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,14 @@ function createOpenClient(params: { stateDir: string; session: string; sessionRe
4242
}
4343

4444
describe('open startup budget', () => {
45+
test('open help documents simulator URL dispatch timeout uncertainty', () => {
46+
expect(openCommandFacet.text.cliDetail).toContain('simctl openurl is bounded to 20s');
47+
expect(openCommandFacet.text.cliDetail).toContain(
48+
'details.reason ios-simulator-openurl-timeout',
49+
);
50+
expect(openCommandFacet.text.cliDetail).toContain('details.dispatched unknown');
51+
});
52+
4553
test('open --timeout projects the startup budget onto the daemon request', async () => {
4654
const parsed = parseArgs(['open', 'Settings', '--timeout', '600000'], { strictFlags: true });
4755
const stateDir = tempStateDir();

‎src/commands/management/app.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ export const openCommandFacet = defineCommandFacet({
195195
text: {
196196
summary: 'Open an app, deep link or URL, save replays',
197197
cliDetail:
198-
'Use --platform to bind URL/deep-link opens to the target platform. For 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/--launch-url set this session\'s Metro/debug runtime hints as part of open itself (applied to the app\'s dev-server prefs and recorded as the session\'s dev-server binding), so a fresh session has them before its first reload instead of needing a throwaway reload-first call just to seed hints; a later plain metro reload in the same session reuses whichever of these were set. A fresh open without these flags clears any leftover binding from a previous same-name session; close also clears it. 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 no single installed app owns the scheme, the prompt stays on screen and open returns as usual. Only the English prompt title 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.',
198+
'Use --platform to bind URL/deep-link opens to the target platform. For 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/--launch-url set this session\'s Metro/debug runtime hints as part of open itself (applied to the app\'s dev-server prefs and recorded as the session\'s dev-server binding), so a fresh session has them before its first reload instead of needing a throwaway reload-first call just to seed hints; a later plain metro reload in the same session reuses whichever of these were set. A fresh open without these flags clears any leftover binding from a previous same-name session; close also clears it. On an iOS Simulator, simctl openurl is bounded to 20s; if CoreSimulator stalls, open fails with details.reason ios-simulator-openurl-timeout and details.dispatched unknown because the URL may already have landed. 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 no single installed app owns the scheme, the prompt stays on screen and open returns as usual. Only the English prompt title 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.',
199199
mcpDetail:
200200
"Metro and debug runtime hints given here are recorded as the session's dev-server binding, so a later reload reuses them; a fresh open without them clears any binding left by a previous same-name session.",
201201
},

0 commit comments

Comments
 (0)