Skip to content

Commit b56fa11

Browse files
committed
fix(ios): launch expo-dev-client apps through their dev-client URL
On an iOS simulator, open writes the Metro runtime hint as bare React Native's RCT_jsLocation default, which an expo-dev-client ignores, so the app kept loading its own server or embedded bundle. When the app declares a single exp+<slug> URL scheme and is that scheme's only owner on the simulator, open now launches it through exp+<slug>://expo-development-client/?url=<server> using the existing launch-URL path, which also answers an Open-in prompt. Bare React Native apps, an explicit --launch-url and a probe that cannot prove the scheme keep the plain launch. metro reload is unchanged: it never touches the device and already reaches a connected dev client over /message. Closes #1245
1 parent c7b534f commit b56fa11

9 files changed

Lines changed: 456 additions & 10 deletions

File tree

‎examples/test-app/README.md‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -213,10 +213,15 @@ pnpm test-app:ios -- --device "<device name>" --port 8082
213213
pnpm test-app:android -- --device "$ANDROID_DEVICE" --port 8082
214214
```
215215

216-
After the development build is installed, keep using the same native app. The
217-
current `agent-device open` CLI does not accept `--metro-host` or `--metro-port`;
218-
open the app normally, then use the Metro command surface for Metro-specific
219-
actions:
216+
After the development build is installed, keep using the same native app. On an
217+
iOS simulator, `open` points this expo-dev-client at a Metro server through its
218+
`exp+agent-device-test-app://expo-development-client/?url=...` launch URL:
219+
220+
```bash
221+
agent-device open com.callstack.agentdevicelab --platform ios --metro-host 127.0.0.1 --metro-port 8082
222+
```
223+
224+
Use the Metro command surface for Metro-specific actions:
220225

221226
```bash
222227
agent-device metro prepare --project-root examples/test-app --kind expo --port 8082 --public-base-url http://127.0.0.1:8082
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import { promises as fs } from 'node:fs';
2+
import path from 'node:path';
3+
import { test } from 'vitest';
4+
import assert from 'node:assert/strict';
5+
6+
import type { DeviceInfo } from '@agent-device/kernel/device';
7+
import { resolveIosSimulatorExpoDevClientScheme } from '../app-resolution.ts';
8+
import { withFakeAppleTool, type FakeAppleToolResponse } from '../../__tests__/fake-apple-tool.ts';
9+
import { mkdtempForTest } from '../../__tests__/tmp-dir.ts';
10+
import { IOS_TEST_SIMULATOR } from './apple-core-stub-helpers.ts';
11+
12+
const DEV_CLIENT_BUNDLE_ID = 'com.example.devclient';
13+
14+
type InstalledApps = Readonly<{
15+
listing: Record<string, unknown>;
16+
appPaths: Map<string, string>;
17+
schemesByPlist: Map<string, string[]>;
18+
}>;
19+
20+
async function installApps(apps: Record<string, string[]>): Promise<InstalledApps> {
21+
const root = await mkdtempForTest('expo-dev-client-schemes-');
22+
const listing: Record<string, unknown> = {};
23+
const appPaths = new Map<string, string>();
24+
const schemesByPlist = new Map<string, string[]>();
25+
for (const [bundleId, schemes] of Object.entries(apps)) {
26+
const appPath = path.join(root, `${bundleId}.app`);
27+
await fs.mkdir(appPath, { recursive: true });
28+
await fs.writeFile(path.join(appPath, 'Info.plist'), '');
29+
listing[bundleId] = { ApplicationType: 'User', CFBundleDisplayName: bundleId, Path: appPath };
30+
appPaths.set(bundleId, appPath);
31+
schemesByPlist.set(path.join(appPath, 'Info.plist'), schemes);
32+
}
33+
return { listing, appPaths, schemesByPlist };
34+
}
35+
36+
function answerContainer(installed: InstalledApps, bundleId: string | undefined, fails: boolean) {
37+
const appPath = bundleId === undefined ? undefined : installed.appPaths.get(bundleId);
38+
if (fails || appPath === undefined) return { exitCode: 2, stderr: 'no app' };
39+
return `${appPath}\n`;
40+
}
41+
42+
function answerSchemes(installed: InstalledApps, plistPath: string | undefined): string {
43+
const schemes = installed.schemesByPlist.get(plistPath ?? '') ?? [];
44+
return JSON.stringify({ CFBundleURLTypes: [{ CFBundleURLSchemes: schemes }] });
45+
}
46+
47+
/** Installs each app with the given URL schemes and answers the simctl/plutil probes for them. */
48+
async function createInstalledApps(
49+
apps: Record<string, string[]>,
50+
options: { containerFails?: boolean } = {},
51+
): Promise<(args: string[]) => FakeAppleToolResponse> {
52+
const installed = await installApps(apps);
53+
return (args) => {
54+
const [tool, command] = args;
55+
if (tool === 'simctl' && command === 'listapps') return JSON.stringify(installed.listing);
56+
if (tool === 'simctl' && command === 'get_app_container') {
57+
return answerContainer(installed, args[3], options.containerFails === true);
58+
}
59+
if (tool === 'plutil' && command === '-convert') return answerSchemes(installed, args[5]);
60+
return { stderr: `unexpected xcrun args: ${args.join(' ')}`, exitCode: 1 };
61+
};
62+
}
63+
64+
test('an expo-dev-client resolves to its exp+ scheme when it is the scheme’s only owner', async () => {
65+
const tool = await createInstalledApps({
66+
[DEV_CLIENT_BUNDLE_ID]: ['devclient', 'com.example.devclient', 'exp+dev-slug'],
67+
'com.example.other': ['other'],
68+
});
69+
70+
await withFakeAppleTool(tool, async () => {
71+
assert.equal(
72+
await resolveIosSimulatorExpoDevClientScheme(IOS_TEST_SIMULATOR, DEV_CLIENT_BUNDLE_ID),
73+
'exp+dev-slug',
74+
);
75+
});
76+
});
77+
78+
test.each([
79+
['a bare React Native app', { [DEV_CLIENT_BUNDLE_ID]: ['devclient'] }],
80+
['an app with two exp+ schemes', { [DEV_CLIENT_BUNDLE_ID]: ['exp+dev-slug', 'exp+other-slug'] }],
81+
[
82+
'a scheme another installed variant also owns',
83+
{
84+
[DEV_CLIENT_BUNDLE_ID]: ['exp+dev-slug'],
85+
'com.example.devclient.preview': ['exp+dev-slug'],
86+
},
87+
],
88+
['a bare exp+ prefix', { [DEV_CLIENT_BUNDLE_ID]: ['exp+'] }],
89+
])('%s has no dev-client scheme', async (_name, apps) => {
90+
const tool = await createInstalledApps(apps);
91+
92+
await withFakeAppleTool(tool, async () => {
93+
assert.equal(
94+
await resolveIosSimulatorExpoDevClientScheme(IOS_TEST_SIMULATOR, DEV_CLIENT_BUNDLE_ID),
95+
undefined,
96+
);
97+
});
98+
});
99+
100+
test('an app the simulator cannot locate has no dev-client scheme', async () => {
101+
const tool = await createInstalledApps(
102+
{ [DEV_CLIENT_BUNDLE_ID]: ['exp+dev-slug'] },
103+
{ containerFails: true },
104+
);
105+
106+
await withFakeAppleTool(tool, async () => {
107+
assert.equal(
108+
await resolveIosSimulatorExpoDevClientScheme(IOS_TEST_SIMULATOR, DEV_CLIENT_BUNDLE_ID),
109+
undefined,
110+
);
111+
});
112+
});
113+
114+
test('a physical device is never probed', async () => {
115+
const physical: DeviceInfo = { ...IOS_TEST_SIMULATOR, kind: 'device' };
116+
117+
await withFakeAppleTool(
118+
() => ({ stderr: 'must not run', exitCode: 1 }),
119+
async ({ calls }) => {
120+
assert.equal(
121+
await resolveIosSimulatorExpoDevClientScheme(physical, DEV_CLIENT_BUNDLE_ID),
122+
undefined,
123+
);
124+
assert.deepEqual(calls, []);
125+
},
126+
);
127+
});

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,44 @@ export async function resolveIosSimulatorDeepLinkBundleId(
205205
return matches.length === 1 ? matches[0]?.bundleId : undefined;
206206
}
207207

208+
const EXPO_DEV_CLIENT_SCHEME_PREFIX = 'exp+';
209+
210+
/**
211+
* The `exp+<slug>` scheme an installed expo-dev-client registers to receive its dev-server URL,
212+
* when the app declares exactly one and is that scheme's only owner on the simulator: with a
213+
* second owner, such as another build variant, `simctl openurl` could hand the URL to the wrong
214+
* app. Bare React Native apps and Expo Go declare none. `timeoutMs` is one deadline shared by
215+
* every probe.
216+
*/
217+
export async function resolveIosSimulatorExpoDevClientScheme(
218+
device: DeviceInfo,
219+
bundleId: string,
220+
options: SimulatorAppListOptions = {},
221+
): Promise<string | undefined> {
222+
if (!isIosFamily(device) || device.kind !== 'simulator') return undefined;
223+
const remaining = remainingLookupBudget(options);
224+
const container = await runSimctlForDevice(
225+
device,
226+
['get_app_container', device.id, bundleId, 'app'],
227+
{ allowFailure: true, ...remaining() },
228+
);
229+
const appPath = String(container.stdout).trim();
230+
if (container.exitCode !== 0 || !appPath) return undefined;
231+
const schemes = await readIosSimulatorAppUrlSchemes(
232+
path.join(appPath, 'Info.plist'),
233+
remaining(),
234+
);
235+
const devClientSchemes = [...schemes].filter(
236+
(scheme) =>
237+
scheme.startsWith(EXPO_DEV_CLIENT_SCHEME_PREFIX) &&
238+
scheme.length > EXPO_DEV_CLIENT_SCHEME_PREFIX.length,
239+
);
240+
if (devClientSchemes.length !== 1) return undefined;
241+
const scheme = devClientSchemes[0];
242+
const owner = await resolveIosSimulatorDeepLinkBundleId(device, `${scheme}://`, remaining());
243+
return owner === bundleId ? scheme : undefined;
244+
}
245+
208246
function remainingLookupBudget({
209247
timeoutMs,
210248
signal,
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
import { afterEach, expect, test, vi } from 'vitest';
2+
import type { OpenApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime';
3+
import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors';
4+
import type { DeviceInfo } from '@agent-device/kernel/device';
5+
6+
vi.mock('./core/app-resolution.ts', () => ({
7+
resolveIosSimulatorExpoDevClientScheme: vi.fn(),
8+
}));
9+
10+
import { resolveIosSimulatorExpoDevClientScheme } from './core/app-resolution.ts';
11+
import {
12+
buildExpoDevClientLaunchUrl,
13+
resolveExpoDevClientLaunchUrl,
14+
} from './expo-dev-client-launch.ts';
15+
16+
const resolveScheme = vi.mocked(resolveIosSimulatorExpoDevClientScheme);
17+
18+
const SIMULATOR: DeviceInfo = {
19+
platform: 'apple',
20+
id: 'sim-1',
21+
name: 'iPhone 17 Pro',
22+
kind: 'simulator',
23+
booted: true,
24+
};
25+
26+
function openInput(overrides: Partial<OpenApplicationInput> = {}): OpenApplicationInput {
27+
return {
28+
positionals: ['com.example.devclient'],
29+
appBundleId: 'com.example.devclient',
30+
surface: 'app',
31+
hasExistingSession: false,
32+
relaunch: false,
33+
prewarmRunnerBeforeOpen: false,
34+
enableTestIme: false,
35+
stateDir: '/tmp/state',
36+
runtimeHints: { metroHost: '127.0.0.1', metroPort: '8085' },
37+
execution: {},
38+
...overrides,
39+
} as OpenApplicationInput;
40+
}
41+
42+
afterEach(() => {
43+
vi.clearAllMocks();
44+
});
45+
46+
test.each([
47+
[
48+
'an http server',
49+
{ host: '127.0.0.1', port: 8085, scheme: 'http' as const },
50+
'exp+dev-slug://expo-development-client/?url=http%3A%2F%2F127.0.0.1%3A8085',
51+
],
52+
[
53+
'an https server',
54+
{ host: 'metro.example.test', port: 443, scheme: 'https' as const },
55+
'exp+dev-slug://expo-development-client/?url=https%3A%2F%2Fmetro.example.test%3A443',
56+
],
57+
[
58+
'an IPv6 host',
59+
{ host: '::1', port: 8081, scheme: 'http' as const },
60+
'exp+dev-slug://expo-development-client/?url=http%3A%2F%2F%5B%3A%3A1%5D%3A8081',
61+
],
62+
])('builds the dev-client launch URL for %s', (_name, transport, expected) => {
63+
expect(buildExpoDevClientLaunchUrl('exp+dev-slug', transport)).toBe(expected);
64+
});
65+
66+
test('points an expo-dev-client at the Metro host and port of the open', async () => {
67+
resolveScheme.mockResolvedValue('exp+dev-slug');
68+
69+
await expect(resolveExpoDevClientLaunchUrl(SIMULATOR, openInput())).resolves.toBe(
70+
'exp+dev-slug://expo-development-client/?url=http%3A%2F%2F127.0.0.1%3A8085',
71+
);
72+
expect(resolveScheme).toHaveBeenCalledWith(SIMULATOR, 'com.example.devclient', {
73+
timeoutMs: 3_000,
74+
});
75+
});
76+
77+
test('points at the server origin of a bundle URL, not at the bundle itself', async () => {
78+
resolveScheme.mockResolvedValue('exp+dev-slug');
79+
const input = openInput({
80+
runtimeHints: {
81+
bundleUrl: 'http://10.0.0.5:8090/.expo/.virtual-metro-entry.bundle?platform=ios&dev=true',
82+
},
83+
});
84+
85+
await expect(resolveExpoDevClientLaunchUrl(SIMULATOR, input)).resolves.toBe(
86+
'exp+dev-slug://expo-development-client/?url=http%3A%2F%2F10.0.0.5%3A8090',
87+
);
88+
});
89+
90+
test.each([
91+
['a bare React Native app', openInput(), undefined],
92+
[
93+
'an explicit --launch-url',
94+
openInput({ runtimeLaunchUrl: 'myapp://deep/link' }),
95+
'exp+dev-slug',
96+
],
97+
['an open without an app bundle id', openInput({ appBundleId: undefined }), 'exp+dev-slug'],
98+
['hints without a host and port', openInput({ runtimeHints: {} }), 'exp+dev-slug'],
99+
])('keeps the plain launch for %s', async (_name, input, scheme) => {
100+
resolveScheme.mockResolvedValue(scheme);
101+
102+
await expect(resolveExpoDevClientLaunchUrl(SIMULATOR, input)).resolves.toBeUndefined();
103+
});
104+
105+
test('keeps the plain launch when the scheme probe fails', async () => {
106+
resolveScheme.mockRejectedValue(new AppError('COMMAND_FAILED', 'xcrun timed out'));
107+
108+
await expect(resolveExpoDevClientLaunchUrl(SIMULATOR, openInput())).resolves.toBeUndefined();
109+
});
110+
111+
test('propagates a canceled request instead of falling back', async () => {
112+
const canceled = createRequestCanceledError();
113+
resolveScheme.mockRejectedValue(canceled);
114+
115+
await expect(resolveExpoDevClientLaunchUrl(SIMULATOR, openInput())).rejects.toBe(canceled);
116+
});
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import type { DeviceInfo } from '@agent-device/kernel/device';
2+
import { isRequestCanceledError } from '@agent-device/kernel/errors';
3+
import type { OpenApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime';
4+
import {
5+
resolveRuntimeTransportHints,
6+
type ResolvedRuntimeTransport,
7+
} from '@agent-device/host-kit/runtime-transport-hints';
8+
import { resolveIosSimulatorExpoDevClientScheme } from './core/app-resolution.ts';
9+
10+
/** Detection must stay well inside the 20 s `simctl openurl` bound of the launch it precedes. */
11+
const EXPO_DEV_CLIENT_PROBE_TIMEOUT_MS = 3_000;
12+
13+
/**
14+
* The launch URL that points an expo-dev-client at the open's Metro server. An expo-dev-client
15+
* reads its server from this deep link, not from React Native's `RCT_jsLocation` default, so the
16+
* runtime hint alone leaves it on its own bundle (#1245). Returns `undefined` for bare React Native
17+
* apps, an explicit `--launch-url`, or a probe that cannot prove the scheme, which keeps the plain
18+
* launch. CONSERVATIVE: a failed probe falls back instead of failing the open, because the hint
19+
* write already succeeded; revisit if a dev-client open must refuse when it cannot be pointed.
20+
*/
21+
export async function resolveExpoDevClientLaunchUrl(
22+
device: DeviceInfo,
23+
input: OpenApplicationInput,
24+
): Promise<string | undefined> {
25+
if (!input.appBundleId || input.runtimeLaunchUrl?.trim()) return undefined;
26+
const transport = resolveRuntimeTransportHints({
27+
metroHost: input.runtimeHints.metroHost,
28+
metroPort: input.runtimeHints.metroPort ? Number(input.runtimeHints.metroPort) : undefined,
29+
bundleUrl: input.runtimeHints.bundleUrl,
30+
});
31+
if (!transport) return undefined;
32+
let scheme: string | undefined;
33+
try {
34+
scheme = await resolveIosSimulatorExpoDevClientScheme(device, input.appBundleId, {
35+
timeoutMs: EXPO_DEV_CLIENT_PROBE_TIMEOUT_MS,
36+
});
37+
} catch (error) {
38+
if (isRequestCanceledError(error)) throw error;
39+
return undefined;
40+
}
41+
return scheme ? buildExpoDevClientLaunchUrl(scheme, transport) : undefined;
42+
}
43+
44+
export function buildExpoDevClientLaunchUrl(
45+
scheme: string,
46+
transport: ResolvedRuntimeTransport,
47+
): string {
48+
const host = transport.host.includes(':') ? `[${transport.host}]` : transport.host;
49+
const serverUrl = `${transport.scheme}://${host}:${transport.port}`;
50+
return `${scheme}://expo-development-client/?url=${encodeURIComponent(serverUrl)}`;
51+
}

0 commit comments

Comments
 (0)