Skip to content

Commit 10a68a9

Browse files
committed
fix(metro): replace stale bindings on fresh app opens
1 parent 22d9e8d commit 10a68a9

7 files changed

Lines changed: 78 additions & 27 deletions

File tree

‎packages/platform-apple/src/expo-dev-client-launch.test.ts‎

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { afterEach, expect, test, vi } from 'vitest';
22
import type { OpenApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime';
33
import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors';
4-
import type { DeviceInfo } from '@agent-device/kernel/device';
4+
import { openInput as lifecycleOpenInput, simulator as SIMULATOR } from './lifecycle.fixtures.ts';
55

66
vi.mock('./core/app-resolution.ts', () => ({
77
resolveIosSimulatorExpoDevClientScheme: vi.fn(),
@@ -15,28 +15,13 @@ import {
1515

1616
const resolveScheme = vi.mocked(resolveIosSimulatorExpoDevClientScheme);
1717

18-
const SIMULATOR: DeviceInfo = {
19-
platform: 'apple',
20-
id: 'sim-1',
21-
name: 'iPhone 17 Pro',
22-
kind: 'simulator',
23-
booted: true,
24-
};
25-
2618
function openInput(overrides: Partial<OpenApplicationInput> = {}): OpenApplicationInput {
2719
return {
28-
positionals: ['com.example.devclient'],
20+
...lifecycleOpenInput(),
2921
appBundleId: 'com.example.devclient',
30-
surface: 'app',
31-
hasExistingSession: false,
32-
relaunch: false,
33-
prewarmRunnerBeforeOpen: false,
34-
enableTestIme: false,
35-
stateDir: '/tmp/state',
3622
runtimeHints: { metroHost: '127.0.0.1', metroPort: '8085' },
37-
execution: {},
3823
...overrides,
39-
} as OpenApplicationInput;
24+
};
4025
}
4126

4227
afterEach(() => {

‎src/__tests__/client-metro.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,7 @@ test('metro reload targets the dev server bound by metro prepare in the same ses
808808
});
809809
assert.deepEqual(storedHints, {
810810
controlBaseUrl: `http://127.0.0.1:${metroPort}/`,
811+
deviceBaseUrls: [`http://127.0.0.1:${metroPort}/`],
811812
});
812813

813814
// No explicit --metro-host/--metro-port/--bundle-url: reload must resolve against the
@@ -909,6 +910,7 @@ test('metro prepare keeps a public Expo address separate from the local reload a
909910
});
910911
assert.deepEqual(storedHints, {
911912
controlBaseUrl: `http://127.0.0.1:${metroPort}/`,
913+
deviceBaseUrls: [`https://127.0.0.1:${metroPort}${publicBasePath}`],
912914
});
913915
} finally {
914916
process.env.PATH = previousPath;

‎src/agent-device-client.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -586,12 +586,21 @@ function metroSessionHintsScope(
586586
// The metro-sessions file is the session's dev-server binding; see MetroSessionHints.
587587
function persistMetroSessionHints(
588588
config: AgentDeviceClientConfig,
589-
result: Pick<MetroPrepareResult, 'statusUrl'>,
589+
result: Pick<MetroPrepareResult, 'statusUrl' | 'iosRuntime' | 'androidRuntime'>,
590590
): void {
591591
try {
592592
writeMetroSessionHints({
593593
...metroSessionHintsScope(config),
594-
hints: { controlBaseUrl: new URL('.', result.statusUrl).toString() },
594+
hints: {
595+
controlBaseUrl: new URL('.', result.statusUrl).toString(),
596+
deviceBaseUrls: [
597+
...new Set(
598+
[result.iosRuntime, result.androidRuntime]
599+
.map((runtime) => metroHintsFromRuntime(runtime)?.controlBaseUrl)
600+
.filter((url): url is string => url !== undefined),
601+
),
602+
],
603+
},
595604
});
596605
} catch {
597606
// Session-hint persistence is best-effort; reload still works with explicit flags.
@@ -634,7 +643,13 @@ function recordMetroSessionHintsAfterOpen(params: {
634643
const scope = metroSessionHintsScope(params.config, params.options);
635644
const hints = metroHintsFromRuntime(params.runtime);
636645
if (hints) {
637-
if (params.options.runtime === undefined && readMetroSessionHints(scope)) return;
646+
const binding =
647+
params.options.runtime === undefined ? readMetroSessionHints(scope) : undefined;
648+
if (
649+
binding &&
650+
(params.sessionReused || binding.deviceBaseUrls?.includes(hints.controlBaseUrl))
651+
)
652+
return;
638653
writeMetroSessionHints({ ...scope, hints });
639654
return;
640655
}

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, expect, test } from 'vitest';
22
import { randomUUID } from 'node:crypto';
33
import { mkdirSync, rmSync } from 'node:fs';
4+
import { createServer } from 'node:http';
45

56
import path from 'node:path';
67
import type { CliFlags } from '@agent-device/contracts/command';
@@ -10,6 +11,7 @@ import type { DaemonRequest, DaemonResponse } from '@agent-device/kernel/contrac
1011
import { readMetroSessionHints, writeMetroSessionHints } from '../../metro/metro-session-hints.ts';
1112
import { openCommandFacet } from './app.ts';
1213
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
14+
import { closeLoopbackServer, listenOnLoopback } from '../../__tests__/test-utils/loopback.ts';
1315

1416
function flags(overrides: Partial<CliFlags> = {}): CliFlags {
1517
return overrides as CliFlags;
@@ -65,6 +67,43 @@ describe('open startup budget', () => {
6567
});
6668

6769
describe('open command metro session hints', () => {
70+
test.each([false, true])(
71+
'config defaults replace a stale binding only on a fresh open (reused=%s)',
72+
async (sessionReused) => {
73+
const stateDir = tempStateDir();
74+
const previous = createServer((_req, res) => res.end('PREVIOUS'));
75+
const current = createServer((_req, res) => res.end('CURRENT'));
76+
try {
77+
const previousPort = await listenOnLoopback(previous);
78+
const currentPort = await listenOnLoopback(current);
79+
writeMetroSessionHints({
80+
stateDir,
81+
session: 'proj-a',
82+
hints: {
83+
controlBaseUrl: `http://127.0.0.1:${previousPort}/`,
84+
},
85+
});
86+
const client = createAgentDeviceClient(
87+
{
88+
stateDir,
89+
session: 'proj-a',
90+
runtime: { metroHost: '127.0.0.1', metroPort: currentPort },
91+
},
92+
{ transport: async () => ({ ok: true, data: { sessionReused } }) },
93+
);
94+
await client.apps.open({ app: 'MyApp' });
95+
const result = await client.metro.reload();
96+
expect(result.reloadUrl).toBe(
97+
`http://127.0.0.1:${sessionReused ? previousPort : currentPort}/reload`,
98+
);
99+
expect(result.body).toBe(sessionReused ? 'PREVIOUS' : 'CURRENT');
100+
} finally {
101+
await closeLoopbackServer(previous);
102+
await closeLoopbackServer(current);
103+
}
104+
},
105+
);
106+
68107
test('CLI parser accepts --metro-host/--metro-port/--bundle-url/--launch-url on open', () => {
69108
const parsed = parseArgs(
70109
[

‎src/commands/metro/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ export const metroCommandFacet = defineCommandFacet({
132132
text: {
133133
summary: 'Prepare the dev server or reload apps',
134134
cliDetail:
135-
"reload with no --metro-host/--metro-port/--bundle-url resolves against the dev server this session last bound via metro prepare or open's metro hint flags (falling back to localhost:8081 only when the session never bound one), so it never silently reloads a different project's server on the default port; pass an explicit flag to override the session hint for one call. After prepare, reload uses the local server address independently of the public or proxy address given to the device; that binding wins over client-config runtime defaults, while explicit reload flags override it. For open or an explicit bundle URL, the reload URL keeps the bundle URL mount prefix instead of collapsing to the host root, and when the server has no HTTP /reload route (Expo) the reload is broadcast over its /message websocket instead of trusting the app-page fallback. The binding is cleared when the session closes, and a fresh open without hint flags also clears any leftover binding from a previous same-name session. --kind expo (detected or forced) requests the virtual-entry bundle URL (.expo/.virtual-metro-entry.bundle) instead of index.bundle, since index.bundle 404s/500s against Expo dev servers in monorepos. Dependency install auto-detects the package manager from the nearest yarn.lock/pnpm-lock.yaml/bun.lock/bun.lockb/package-lock.json walking up from --project-root (bounded at the repo root), so Yarn/pnpm workspace monorepos with the lockfile at the repo root do not wrongly fall back to npm install (which fails on workspace: dependency specifiers); if install still fails, pass --no-install-deps when dependencies are already installed (for example via a monorepo root install).",
135+
"reload with no --metro-host/--metro-port/--bundle-url resolves against the dev server this session last bound via metro prepare or open's metro hint flags (falling back to localhost:8081 only when the session never bound one), so it never silently reloads a different project's server on the default port; pass an explicit flag to override the session hint for one call. After prepare, reload uses the local server address independently of the public or proxy address given to the device; a fresh open preserves it only when its client-config runtime points to the prepared device server, while explicit reload flags override it. For open or an explicit bundle URL, reload removes a .bundle/.jsbundle/.js entry filename and keeps the remaining path as the server mount, and when the server has no HTTP /reload route (Expo) the reload is broadcast over its /message websocket instead of trusting the app-page fallback. The binding is cleared when the session closes, and a fresh open without hint flags also clears any leftover binding from a previous same-name session. --kind expo (detected or forced) requests the virtual-entry bundle URL (.expo/.virtual-metro-entry.bundle) instead of index.bundle, since index.bundle 404s/500s against Expo dev servers in monorepos. Dependency install auto-detects the package manager from the nearest yarn.lock/pnpm-lock.yaml/bun.lock/bun.lockb/package-lock.json walking up from --project-root (bounded at the repo root), so Yarn/pnpm workspace monorepos with the lockfile at the repo root do not wrongly fall back to npm install (which fails on workspace: dependency specifiers); if install still fails, pass --no-install-deps when dependencies are already installed (for example via a monorepo root install).",
136136
mcpDetail:
137137
'The binding is cleared when the session closes, and a fresh open without runtime hints also clears any leftover binding from a previous same-name session.',
138138
},

‎src/metro/metro-session-hints.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@ import { resolveMetroServerUrl } from './metro-reload-endpoints.ts';
66
/**
77
* The session's local dev-server binding — the single store `metro reload` resolves against.
88
* Written by `metro prepare` and `open`'s metro hint flags; cleared on session close and on
9-
* hintless fresh-session opens. The daemon's SessionRuntimeHints only drive device-native
10-
* dev-server prefs.
9+
* hintless fresh-session opens. Prepared device addresses identify which app runtime may reuse
10+
* the local control address on a fresh open.
1111
*/
1212
export type MetroSessionHints = {
1313
controlBaseUrl: string;
14+
deviceBaseUrls?: string[];
1415
};
1516

1617
function metroSessionHintsPath(stateDir: string, session: string): string {
@@ -62,7 +63,16 @@ export function readMetroSessionHints(options: {
6263
? new URL(record.controlBaseUrl)
6364
: resolveMetroServerUrl({ runtime });
6465
return url.protocol === 'http:' || url.protocol === 'https:'
65-
? { controlBaseUrl: url.toString() }
66+
? {
67+
controlBaseUrl: url.toString(),
68+
...(Array.isArray(record.deviceBaseUrls)
69+
? {
70+
deviceBaseUrls: record.deviceBaseUrls.filter(
71+
(value): value is string => typeof value === 'string',
72+
),
73+
}
74+
: {}),
75+
}
6676
: undefined;
6777
} catch {
6878
return undefined;

‎website/docs/docs/commands.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -988,8 +988,8 @@ agent-device metro reload --bundle-url "http://localhost:8081/index.bundle?platf
988988
- Use it for React Native dev builds that are already connected to Metro when JS changes should be loaded without restarting the native app process.
989989
- A flagless `metro reload --session <s>` resolves against the dev server that session last bound — via `metro prepare` or `open`'s `--metro-host`/`--metro-port`/`--bundle-url` hint flags — so it never silently reloads a different project's server on the default port. Resolution priority is per-call flags, then that session's saved binding, then `http://localhost:8081/reload`; a host or port flag overrides only that field, while `--bundle-url` supplies the target bundle origin and route.
990990
- Session bindings are updated by each hinted `open` or `metro prepare`, cleared by `close`, and also cleared when a fresh same-name `open` has no Metro hint flags. This prevents a reused session name from reloading a previous project's dev server.
991-
- After `metro prepare`, reload uses the local server address, even when the device loads its bundle through a public or proxy URL. Explicit reload flags override that binding; the stored binding takes precedence over client-config runtime defaults. Opening with those defaults preserves an existing binding; explicit runtime hints on `open` replace it.
992-
- For a binding supplied through `open` or `--bundle-url`, the reload URL keeps the bundle URL's mount prefix instead of collapsing to the host root. This applies to both `index.bundle` and Expo's virtual entry: `http://host/tenant-42/.expo/.virtual-metro-entry.bundle` maps to `http://host/tenant-42/reload`.
991+
- After `metro prepare`, reload uses the local server address, even when the device loads its bundle through a public or proxy URL. Explicit reload flags override that binding. A fresh `open` with client-config runtime defaults preserves a prepared binding only when those defaults point to its device-facing server; otherwise it replaces the binding. An open that reuses the session keeps the binding unless given explicit runtime hints.
992+
- For a binding supplied through `open` or `--bundle-url`, the reload URL keeps the bundle URL's mount prefix instead of collapsing to the host root. It removes a `.bundle`, `.jsbundle`, or `.js` entry filename, including Expo's virtual entry: `http://host/tenant-42/.expo/.virtual-metro-entry.bundle` maps to `http://host/tenant-42/reload`. A path without an entry filename is the server mount: `http://host/tenant-42` maps to `http://host/tenant-42/reload`.
993993
- When the dev server has no HTTP `/reload` route and answers with the app page instead (Expo does this), `metro reload` broadcasts `{"version":2,"method":"reload"}` over the server's `/message` websocket — the channel the dev-server CLIs use for the `r` key — instead of reporting the app-page response as a successful reload. The result's `transport` field says which channel delivered the reload.
994994
- Fall back to `open <app> --relaunch` when the app is not connected to Metro, reload fails, or the native process itself must restart.
995995

0 commit comments

Comments
 (0)