From 21ef0b39679f28cddaca229093b7a99857dca197 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 10:27:59 +0100 Subject: [PATCH 01/10] fix(metro): reload the app's own dev server instead of assuming port 8081 A flagless metro reload resolved localhost:8081 whenever the session had bound no dev server, which reloaded whichever project owned that port, or failed as a bare fetch error. It now resolves in order: the session or explicit binding, the address the app itself stored (RCT_jsLocation in an iOS simulator's preferences), then a local dev server whose X-React-Native-Project-Root matches this directory. When nothing resolves, it fails with details.reason metro_dev_server_unresolved naming the address the fallback would have used. Only a session whose app runs on a local simulator or emulator runs the lookups; a remote or physical device keeps the previous default. Sessions that bind no address now record the app they opened so the reload has something to look that app's address up from. --- packages/client/src/index.ts | 70 +++- packages/command-surface/src/metro/index.ts | 2 +- .../src/daemon-client-lifecycle.ts | 18 +- .../daemon-contracts/src/daemon-resolution.ts | 34 ++ packages/react-native/src/index.ts | 9 + .../react-native/src/metro/client-metro.ts | 26 +- .../metro/metro-dev-server-discovery.test.ts | 170 +++++++++ .../src/metro/metro-dev-server-discovery.ts | 344 ++++++++++++++++++ .../src/metro/metro-reload-endpoints.ts | 28 +- .../src/metro/metro-session-hints.ts | 143 ++++++-- website/docs/docs/commands.md | 2 +- website/docs/docs/error-reasons.md | 6 + 12 files changed, 783 insertions(+), 69 deletions(-) create mode 100644 packages/react-native/src/metro/metro-dev-server-discovery.test.ts create mode 100644 packages/react-native/src/metro/metro-dev-server-discovery.ts diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 3690984da2..78d51cf5cb 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -63,8 +63,12 @@ import { } from '@agent-device/command-surface'; import type { CommandResult } from '@agent-device/command-registry/command-result'; import { createDaemonTransport, createRequestGuard } from '@agent-device/daemon-client'; -import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; +import { + daemonBaseUrlIsLocal, + resolveDaemonPaths, +} from '@agent-device/daemon-contracts/daemon-resolution'; import * as devServer from '@agent-device/react-native'; +import type { MetroAppTarget } from '@agent-device/react-native'; import { asOptionalRecord, readPresentedSurfaceFact, @@ -114,6 +118,8 @@ export function createAgentDeviceClient( ) => devServer.recordOpenedMetroSession(withHost(options), input); const readMetroSessionRuntime = (options: { session: string; stateDir?: string }) => devServer.readMetroSessionRuntime(withHost(options)); + const readMetroSessionAppTarget = (options: { session: string; stateDir?: string }) => + devServer.readMetroSessionAppTarget(withHost(options)); // A non-default responseLevel (digest/full) makes the daemon return a leveled // shape; the per-command client normalizers assume the default shape, so the @@ -336,17 +342,18 @@ export function createAgentDeviceClient( open: async (options: AppOpenOptions) => { const session = resolveRequestSession(options); const data = await executeCommand>('open', options); + const device = normalizeOpenDevice(data); + const appBundleId = readOptionalString(data, 'appBundleId'); + const appId = appBundleId; await recordOpenedMetroSession( { ...mergeClientOptions(config, options), session }, { explicitRuntime: options.runtime !== undefined, runtime: mergeClientOptions(config, options).runtime, sessionReused: data.sessionReused === true, + app: metroAppTargetFromOpen(device, appBundleId), }, ); - const device = normalizeOpenDevice(data); - const appBundleId = readOptionalString(data, 'appBundleId'); - const appId = appBundleId; return { session, ...readScriptDeliveryDisclosure(data), @@ -428,15 +435,26 @@ export function createAgentDeviceClient( ); return result; }, - reload: async (options = {}) => - await reloadMetro({ + reload: async (options = {}) => { + const session = resolveSessionName(config.session); + const sessionOptions = { ...config, session }; + // Discovery reads this machine: an app's stored address in a simulator container, and this + // host's listening ports. A client aimed at a non-loopback daemon drives devices on another + // machine, so its reload keeps the address its hints resolve to and probes nothing here. + if (!daemonIsLocal(config, host)) { + return await reloadMetro({ + ...options, + runtime: (await readMetroSessionRuntime(sessionOptions)) ?? config.runtime, + }); + } + return await reloadMetro({ ...options, - runtime: - (await readMetroSessionRuntime({ - ...config, - session: resolveSessionName(config.session), - })) ?? config.runtime, - }), + runtime: (await readMetroSessionRuntime(sessionOptions)) ?? config.runtime, + host, + projectRoot: config.cwd ?? host.cwd, + app: await readMetroSessionAppTarget(sessionOptions), + }); + }, }, capture: { snapshot: async (options: CaptureSnapshotOptions = {}) => { @@ -564,6 +582,34 @@ function centeredGestureInput( }; } +/** + * Whether this client talks to a daemon on this machine. Discovery in `metro reload` reads local + * state — a simulator container file, this host's listening ports — so it is only meaningful when + * the devices the session drives are hosted here too, which for a client is the daemon's machine. + */ +function daemonIsLocal(config: AgentDeviceClientConfig, host: HostEnvironment): boolean { + return daemonBaseUrlIsLocal(config.daemonBaseUrl ?? host.env.AGENT_DEVICE_DAEMON_BASE_URL); +} + +/** + * The app an `open` launched, in the shape the Metro reload discovery reads back. Only an iOS or + * Android app with a resolved device and bundle id is worth recording: anything else has no + * app-reported dev server to look up. + */ +function metroAppTargetFromOpen( + device: ReturnType, + appBundleId: string | undefined, +): MetroAppTarget | undefined { + if (!device || !appBundleId) return undefined; + if (device.platform !== 'ios' && device.platform !== 'android') return undefined; + return { + platform: device.platform, + deviceId: device.id, + ...(device.kind ? { deviceKind: device.kind } : {}), + appId: appBundleId, + }; +} + function normalizeSnapshotResult( data: Record, session: string | undefined, diff --git a/packages/command-surface/src/metro/index.ts b/packages/command-surface/src/metro/index.ts index cf1faf9d67..541db1c020 100644 --- a/packages/command-surface/src/metro/index.ts +++ b/packages/command-surface/src/metro/index.ts @@ -138,7 +138,7 @@ export const metroCommandFacet = defineCommandFacet({ summary: 'Prepare the dev server or reload apps', searchHint: 'bundler', cliDetail: - "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).", + "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. When the session never bound one and its app runs on a local simulator or emulator, reload then reads the dev-server address the app itself stored (RCT_jsLocation in the app's preferences on an iOS simulator) and, failing that, probes the ports a local process is listening on for a dev server whose X-React-Native-Project-Root matches this directory, so it never silently reloads a different project's server. When nothing resolves, reload fails with details.reason 'metro_dev_server_unresolved' naming the address it would have used, instead of calling localhost:8081, which belongs to whichever project owns that port. A physical or provider-hosted device is not this machine, so its sessions skip the local lookups and keep the default address. 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).", }, metadata: metroCommandMetadata, run: async (client, input): Promise => diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index b810c0017e..90de3f239f 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -5,7 +5,6 @@ import type { EnsureDaemonOptions, } from '@agent-device/contracts/client'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import net from 'node:net'; import { AppError, normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import { readReplayDivergenceResume } from '@agent-device/ad-replay/divergence'; @@ -16,6 +15,7 @@ import { type OwnedReplayStateDir, } from '@agent-device/daemon-contracts/daemon-registration-owner'; import { + isLoopbackHostname, resolveDaemonPaths, resolveDaemonServerMode, resolveDaemonTransportPreference, @@ -72,11 +72,6 @@ export type EnsuredDaemon = { startedByClient: boolean; }; -const LOOPBACK_BLOCK_LIST = new net.BlockList(); -LOOPBACK_BLOCK_LIST.addSubnet('127.0.0.0', 8, 'ipv4'); -LOOPBACK_BLOCK_LIST.addAddress('::1', 'ipv6'); -LOOPBACK_BLOCK_LIST.addSubnet('::ffff:127.0.0.0', 104, 'ipv6'); - /** * Whether a timed-out request may retire the daemon it was waiting on. An attach client never may: the * daemon is not its to kill, and `ensureDaemon` reuses a compatible daemon that accepts a connection @@ -546,17 +541,6 @@ function validateRemoteDaemonTrust( ); } -function isLoopbackHostname(hostname: string): boolean { - const normalized = hostname - .trim() - .toLowerCase() - .replace(/^\[(.*)\]$/, '$1'); - if (normalized === 'localhost') return true; - if (net.isIPv4(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv4'); - if (net.isIPv6(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv6'); - return false; -} - export function attachSessionAddressHints( response: DaemonResponse, req: Omit, diff --git a/packages/daemon-contracts/src/daemon-resolution.ts b/packages/daemon-contracts/src/daemon-resolution.ts index 91898fc8be..aab05c7113 100644 --- a/packages/daemon-contracts/src/daemon-resolution.ts +++ b/packages/daemon-contracts/src/daemon-resolution.ts @@ -1,5 +1,6 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; +import net from 'node:net'; import path from 'node:path'; import { admitPrivateRoot, @@ -258,6 +259,39 @@ export function resolveDaemonServerMode(raw: string | undefined): DaemonServerMo return 'socket'; } +const LOOPBACK_BLOCK_LIST = new net.BlockList(); +LOOPBACK_BLOCK_LIST.addSubnet('127.0.0.0', 8, 'ipv4'); +LOOPBACK_BLOCK_LIST.addAddress('::1', 'ipv6'); +LOOPBACK_BLOCK_LIST.addSubnet('::ffff:127.0.0.0', 104, 'ipv6'); + +/** + * Whether a daemon base URL addresses this machine. A caller on a non-loopback daemon drives devices + * hosted elsewhere, so it must not read this machine's state to answer a question about them. + */ +export function daemonBaseUrlIsLocal(raw: string | undefined): boolean { + if (!raw) return true; + let hostname: string; + try { + hostname = new URL(raw).hostname; + } catch { + // An unusable base URL is refused when the transport resolves it; treat it as remote here. + return false; + } + return isLoopbackHostname(hostname); +} + +/** Whether an address names this machine: `localhost` or a loopback literal. */ +export function isLoopbackHostname(hostname: string): boolean { + const normalized = hostname + .trim() + .toLowerCase() + .replace(/^\[(.*)\]$/, '$1'); + if (normalized === 'localhost') return true; + if (net.isIPv4(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv4'); + if (net.isIPv6(normalized)) return LOOPBACK_BLOCK_LIST.check(normalized, 'ipv6'); + return false; +} + export function resolveDaemonTransportPreference( raw: string | undefined, ): DaemonTransportPreference { diff --git a/packages/react-native/src/index.ts b/packages/react-native/src/index.ts index 747ebba33b..e9738eea27 100644 --- a/packages/react-native/src/index.ts +++ b/packages/react-native/src/index.ts @@ -1,4 +1,5 @@ import type { MetroSessionOptions, MetroSessionOpenInput } from './metro/metro-session-hints.ts'; +import type { MetroAppTarget } from './metro/metro-dev-server-discovery.ts'; import type { SessionRuntimeHints } from '@agent-device/kernel/contracts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { resolveRuntimeTransportHints } from '@agent-device/host-kit/runtime-transport-hints'; @@ -10,6 +11,7 @@ import type { ReactDevtoolsOutput } from './react-devtools/react-devtools-output export type { PrepareMetroRuntimeOptions, ReloadMetroOptions } from './metro/client-metro.ts'; export type { PrepareMetroRuntimeResult, ReloadMetroResult } from '@agent-device/contracts/remote'; +export type { MetroAppTarget } from './metro/metro-dev-server-discovery.ts'; export type { MetroBridgeDescriptor } from './metro/metro-types.ts'; export type { ReactDevtoolsCommandOptions } from './react-devtools/react-devtools-connection.ts'; export type { ReactDevtoolsOutput } from './react-devtools/react-devtools-output.ts'; @@ -96,6 +98,13 @@ export async function readMetroSessionRuntime( return session.readMetroSessionRuntime(options); } +export async function readMetroSessionAppTarget( + options: MetroSessionOptions, +): Promise { + const session = await import('./metro/metro-session-hints.ts'); + return session.readMetroSessionAppTarget(options); +} + export async function clearMetroSessionHintsQuietly(options: MetroSessionOptions): Promise { const session = await import('./metro/metro-session-hints.ts'); session.clearMetroSessionHintsQuietly(options); diff --git a/packages/react-native/src/metro/client-metro.ts b/packages/react-native/src/metro/client-metro.ts index 910806576d..b0725f7e77 100644 --- a/packages/react-native/src/metro/client-metro.ts +++ b/packages/react-native/src/metro/client-metro.ts @@ -52,10 +52,12 @@ import { normalizeBaseUrl } from './base-url.ts'; import { buildBundleUrl } from './bundle-url.ts'; import { EXPO_VIRTUAL_ENTRY_BUNDLE_PATH, + buildMetroReloadEndpoints, parsePort, resolveMetroReloadEndpoints, + type MetroReloadEndpoints, } from './metro-reload-endpoints.ts'; - +import { resolveMetroReloadServerUrl, type MetroAppTarget } from './metro-dev-server-discovery.ts'; const DEV_SERVER_STATUS_READY_TEXT = 'packager-status:running'; const METRO_TERM_TIMEOUT_MS = 1_000; const METRO_KILL_TIMEOUT_MS = 1_000; @@ -89,6 +91,12 @@ export type ReloadMetroOptions = { bundleUrl?: string; runtime?: MetroRuntimeHints; timeoutMs?: number | string; + /** The host the reload runs on: where a local dev server, or a simulator's app, gets read. */ + host?: HostEnvironment; + /** The session's app, when the caller knows it: the signal a local reload checks first. */ + app?: MetroAppTarget; + /** The project whose dev server a local search matches; defaults to the host's working directory. */ + projectRoot?: string; }; function normalizeOptionalBaseUrl(input: unknown): string { @@ -1044,9 +1052,23 @@ async function broadcastReloadOverMessageSocket( }); } +async function resolveReloadEndpoints(input: ReloadMetroOptions): Promise { + if (!input.host) return resolveMetroReloadEndpoints(input); + const resolved = await resolveMetroReloadServerUrl({ + metroHost: input.metroHost, + metroPort: input.metroPort, + bundleUrl: input.bundleUrl, + runtime: input.runtime, + app: input.app, + host: input.host, + projectRoot: input.projectRoot, + }); + return buildMetroReloadEndpoints(resolved.serverUrl); +} + export async function reloadMetro(input: ReloadMetroOptions = {}): Promise { const timeoutMs = parseTimeout(input.timeoutMs, 10_000, 1_000); - const { reloadUrl, messageSocketUrl } = resolveMetroReloadEndpoints(input); + const { reloadUrl, messageSocketUrl } = await resolveReloadEndpoints(input); const response = await fetchText(reloadUrl, timeoutMs); if (response.ok && !looksLikeHtmlDocumentBody(response.body)) { return { diff --git a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts new file mode 100644 index 0000000000..51f2ac70f7 --- /dev/null +++ b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts @@ -0,0 +1,170 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { AppError } from '@agent-device/kernel/errors'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { + METRO_RELOAD_REASONS, + canDiscoverForDeviceKind, + discoverLocalMetroServer, + metroDevServerUnresolvedError, + resolveMetroReloadServerUrl, + type LocalMetroServer, + type MetroAppTarget, +} from './metro-dev-server-discovery.ts'; + +const host: HostEnvironment = { env: {}, cwd: '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/app/project' }; +const simulatorApp: MetroAppTarget = { + platform: 'ios', + deviceKind: 'simulator', + deviceId: 'UDID-1', + appId: 'com.example.app', +}; + +function serverAt(port: number, projectRoot?: string): LocalMetroServer { + return { + serverUrl: new URL(`http://127.0.0.1:${port}`), + ...(projectRoot ? { projectRoot } : {}), + }; +} + +function probeReturning( + servers: LocalMetroServer[], + recorded: { appRead: number; portsRead: number } = { appRead: 0, portsRead: 0 }, +) { + const byUrl = new Map(servers.map((server) => [server.serverUrl.origin, server])); + return { + record: recorded, + probe: { + listListeningPorts: async () => { + recorded.portsRead += 1; + return servers.map((server) => Number(server.serverUrl.port)); + }, + probeServer: async (url: URL) => byUrl.get(url.origin), + readAppReportedServerUrl: async () => { + recorded.appRead += 1; + return undefined; + }, + }, + }; +} + +test('a binding is the answer: neither the app nor the local ports are consulted', async () => { + const probe = probeReturning([serverAt(8096, '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/app/project')]); + const explicit = await resolveMetroReloadServerUrl({ + metroPort: 9100, + host, + app: simulatorApp, + probe: probe.probe, + }); + assert.equal(explicit.resolvedBy, 'binding'); + assert.equal(explicit.serverUrl.port, '9100'); + + const bound = await resolveMetroReloadServerUrl({ + runtime: { metroHost: '127.0.0.1', metroPort: 8082 }, + host, + app: simulatorApp, + probe: probe.probe, + }); + assert.equal(bound.resolvedBy, 'binding'); + assert.equal(bound.serverUrl.port, '8082'); + assert.deepEqual(probe.record, { appRead: 0, portsRead: 0 }); +}); + +test('with no binding, the address the app itself stored wins over a local search', async () => { + const probe = probeReturning([serverAt(8096, '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/app/project')]); + const resolved = await resolveMetroReloadServerUrl({ + host, + app: simulatorApp, + probe: { + ...probe.probe, + readAppReportedServerUrl: async () => new URL('http://127.0.0.1:8096'), + }, + }); + assert.equal(resolved.resolvedBy, 'app-reported'); + assert.equal(resolved.serverUrl.port, '8096'); + assert.equal(probe.record.portsRead, 0); +}); + +test('an app address with no server behind it falls through to the local search', async () => { + const resolved = await resolveMetroReloadServerUrl({ + host, + app: simulatorApp, + probe: { + listListeningPorts: async () => [8096], + probeServer: async (url: URL) => + url.port === '8096' ? serverAt(8096, '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/app/project') : undefined, + readAppReportedServerUrl: async () => new URL('http://127.0.0.1:8097'), + }, + }); + assert.equal(resolved.resolvedBy, 'local-project-root'); + assert.equal(resolved.serverUrl.port, '8096'); +}); + +test("the local search matches the project root and never picks another project's server", async () => { + const matching = await discoverLocalMetroServer({ + projectRoots: ['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/app/project'], + listListeningPorts: async () => [8081, 8096], + probeServer: async (url: URL) => + url.port === '8096' + ? serverAt(8096, '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/app/project/packages/mobile') + : serverAt(8081, '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/other/project'), + }); + assert.equal(matching?.serverUrl.port, '8096'); + + const foreign = await discoverLocalMetroServer({ + projectRoots: ['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/app/project'], + listListeningPorts: async () => [8081], + probeServer: async () => serverAt(8081, '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/other/project'), + }); + assert.equal(foreign, undefined); +}); + +test("a running server that reports no project root is not this project's dev server", async () => { + const probe = probeReturning([serverAt(8096)]); + await assert.rejects( + () => resolveMetroReloadServerUrl({ host, app: simulatorApp, probe: probe.probe }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, METRO_RELOAD_REASONS.devServerUnresolved.reason); + return true; + }, + ); +}); + +test('nothing found fails typed and names the address the fallback would have used', async () => { + const probe = probeReturning([]); + await assert.rejects( + () => resolveMetroReloadServerUrl({ host, app: simulatorApp, probe: probe.probe }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.equal(error.details?.reason, METRO_RELOAD_REASONS.devServerUnresolved.reason); + assert.equal(error.details?.triedUrl, 'http://localhost:8081/'); + assert.match(String(error.details?.hint), /--metro-port /); + assert.match(error.message, /http:\/\/localhost:8081/); + return true; + }, + ); +}); + +test('a device this machine does not host keeps the previous address instead of probing ports', async () => { + for (const deviceKind of ['device', undefined] as const) { + const probe = probeReturning([serverAt(8096, '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/app/project')]); + const resolved = await resolveMetroReloadServerUrl({ + host, + app: { ...simulatorApp, deviceKind }, + probe: probe.probe, + }); + assert.equal(resolved.resolvedBy, 'default'); + assert.equal(resolved.serverUrl.toString(), 'http://localhost:8081/'); + assert.deepEqual(probe.record, { appRead: 0, portsRead: 0 }); + } + assert.equal(canDiscoverForDeviceKind('device'), false); + assert.equal(canDiscoverForDeviceKind('simulator'), true); + assert.equal(canDiscoverForDeviceKind('emulator'), true); +}); + +test('the typed failure reads as its own reason', () => { + const error = metroDevServerUnresolvedError(); + assert.equal(error.details?.reason, 'metro_dev_server_unresolved'); +}); diff --git a/packages/react-native/src/metro/metro-dev-server-discovery.ts b/packages/react-native/src/metro/metro-dev-server-discovery.ts new file mode 100644 index 0000000000..2fe9cce1e2 --- /dev/null +++ b/packages/react-native/src/metro/metro-dev-server-discovery.ts @@ -0,0 +1,344 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { runCmd } from '@agent-device/host-kit/command'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { + DEFAULT_METRO_HOST, + DEFAULT_METRO_PORT, + isMetroTargetBound, + resolveMetroServerUrl, + type MetroReloadTargetInput, +} from './metro-reload-endpoints.ts'; + +/** + * The session's app, as `open` recorded it: the one thing a sessionless reload can still ask about + * on the machine that hosts the device. + */ +export type MetroAppTarget = Readonly<{ + platform: 'ios' | 'android'; + deviceKind?: 'simulator' | 'emulator' | 'device'; + deviceId: string; + appId?: string; +}>; + +/** How a reload reached the dev server it is about to call. */ +export type MetroServerResolutionSource = + | 'binding' + | 'app-reported' + | 'local-project-root' + | 'default'; + +/** A running local dev server, with the project root it reports. */ +export type LocalMetroServer = Readonly<{ + serverUrl: URL; + projectRoot?: string; +}>; + +export type ResolvedMetroReloadServer = Readonly<{ + serverUrl: URL; + resolvedBy: MetroServerResolutionSource; +}>; + +export const METRO_RELOAD_REASONS = { + // No dev server is bound to the session and none was found for its app; nothing was reloaded. + devServerUnresolved: { reason: 'metro_dev_server_unresolved' }, +} as const satisfies ReasonTable<'metro reload'>; + +const IOS_JS_LOCATION_KEY = 'RCT_jsLocation'; +const IOS_PACKAGER_SCHEME_KEY = 'RCT_packager_scheme'; +const SIMULATOR_DEVICES_ROOT = 'Library/Developer/CoreSimulator/Devices'; +const METRO_STATUS_READY_TEXT = 'packager-status:running'; +const METRO_PROJECT_ROOT_HEADER = 'x-react-native-project-root'; +const HOST_READ_TIMEOUT_MS = 1_500; +const STATUS_PROBE_TIMEOUT_MS = 800; +const MAX_CONCURRENT_STATUS_PROBES = 32; + +/** The host reads a reload can make, injectable so the resolution order is testable without a host. */ +export type MetroDevServerProbe = Readonly<{ + /** Ports a local process is listening on. */ + listListeningPorts?: () => Promise; + /** The dev server at an address, when one answers there. */ + probeServer?: (serverUrl: URL, timeoutMs: number) => Promise; + /** What the session's app itself stored as its dev-server address. */ + readAppReportedServerUrl?: ( + app: MetroAppTarget, + host: HostEnvironment, + ) => Promise; +}>; + +export type ResolveMetroReloadServerInput = MetroReloadTargetInput & + Readonly<{ + app?: MetroAppTarget; + host: HostEnvironment; + projectRoot?: string; + probe?: MetroDevServerProbe; + }>; + +/** + * Resolves the dev server a reload should call, in this order: + * + * 1. The binding: `--metro-host`/`--metro-port`/`--bundle-url`, or the address the session bound + * through `metro prepare` or `open`'s Metro hint flags. The caller's answer is never second-guessed. + * 2. What the app itself reports — on an iOS simulator, the dev-server address React Native keeps in + * the app's preferences. The app cannot be wrong about the server it loads its bundle from. + * 3. A local dev server that serves the current project. + * + * Only a session whose app runs on a local simulator or emulator reaches steps 2 and 3: a remote + * device's host is not this machine, so its sessions keep their existing behavior, including the + * default address. With no signal at all, this fails typed rather than calling `localhost:8081`, + * which in an unbound session belongs to whichever project happens to own that port. + */ +export async function resolveMetroReloadServerUrl( + input: ResolveMetroReloadServerInput, +): Promise { + if (isMetroTargetBound(input)) { + return { serverUrl: resolveMetroServerUrl(input), resolvedBy: 'binding' }; + } + + const app = input.app; + if (!app || !canDiscoverForDeviceKind(app.deviceKind)) { + // Nothing to discover from: no recorded app, or a device this machine does not host. The + // address the caller's hints resolve to, default included, stays what it always was. + return { serverUrl: resolveMetroServerUrl(input), resolvedBy: 'default' }; + } + + const host = input.host; + const probe = input.probe ?? {}; + const projectRoot = input.projectRoot ?? host.cwd; + const reported = await (probe.readAppReportedServerUrl ?? readAppReportedMetroServerUrl)( + app, + host, + ).catch(() => undefined); + if (reported) { + // The app cannot be wrong about the server it loads from, but its stored address can outlive that + // server. On loopback, where this host can answer for it, one bounded probe settles it. + if (!isLoopbackUrl(reported) || (await probeIsRunningDevServer(reported, probe))) { + return { serverUrl: reported, resolvedBy: 'app-reported' }; + } + } + + const discovered = await discoverLocalMetroServer({ + projectRoots: [projectRoot, host.cwd], + listListeningPorts: probe.listListeningPorts ?? listLocalListeningPorts, + probeServer: probe.probeServer ?? probeLocalMetroServer, + }); + if (discovered) { + return { serverUrl: discovered.serverUrl, resolvedBy: 'local-project-root' }; + } + + throw metroDevServerUnresolvedError(); +} + +/** + * Whether reload may look for a dev server on this machine for a session's device. A physical or + * provider-hosted device runs somewhere else: its dev server is not a local port, so probing here + * would answer a question nobody asked. + */ +export function canDiscoverForDeviceKind(kind: MetroAppTarget['deviceKind']): boolean { + return kind === 'simulator' || kind === 'emulator'; +} + +/** + * What the app itself reports: React Native keeps `RCT_jsLocation` in the app's own preferences + * plist — the same key `open --metro-host/--metro-port` writes — and the simulator host reads that + * file from the device container without a device round-trip. A physical device, an Android app, or + * an app that never stored an address reports nothing. + */ +async function readAppReportedMetroServerUrl( + app: MetroAppTarget, + host: HostEnvironment, +): Promise { + if (app.platform !== 'ios' || app.deviceKind !== 'simulator' || !app.appId) return undefined; + const home = host.env.HOME; + if (!home) return undefined; + const plist = path.join( + home, + SIMULATOR_DEVICES_ROOT, + app.deviceId, + 'data', + 'Library', + 'Preferences', + `${app.appId}.plist`, + ); + if (!fileExists(plist)) return undefined; + const result = await runCmd('plutil', ['-convert', 'json', '-o', '-', plist], { + allowFailure: true, + timeoutMs: HOST_READ_TIMEOUT_MS, + }); + if (result.exitCode !== 0) return undefined; + const settings = parseJsonObject(result.stdout); + const reported = asNonEmptyString(settings?.[IOS_JS_LOCATION_KEY]); + if (!reported) return undefined; + const scheme = settings?.[IOS_PACKAGER_SCHEME_KEY] === 'https' ? 'https' : 'http'; + return parseHostAndPort(reported, scheme); +} + +/** + * The local dev server that serves this project: a listening port whose `/status` answers + * `packager-status:running` and whose `X-React-Native-Project-Root` contains or is contained by one + * of the project roots (a monorepo server serves from the repo root). Ports come from what a local + * process actually listens on, each probe is short, and they run concurrently, so a miss costs one + * bounded sweep rather than a reload timeout. A project-root match always wins, and a server that + * names a different project never counts, so another project's Metro is not reloaded by accident. + */ +export async function discoverLocalMetroServer( + input: Readonly<{ + projectRoots: string[]; + listListeningPorts: () => Promise; + probeServer: (serverUrl: URL, timeoutMs: number) => Promise; + probeTimeoutMs?: number; + }>, +): Promise { + const ports = await input.listListeningPorts().catch(() => [] as number[]); + const timeoutMs = input.probeTimeoutMs ?? STATUS_PROBE_TIMEOUT_MS; + const probes = ports + .slice(0, MAX_CONCURRENT_STATUS_PROBES) + .map((port) => input.probeServer(new URL(`http://127.0.0.1:${port}`), timeoutMs)); + const candidates = (await Promise.allSettled(probes)) + .filter( + (settled): settled is PromiseFulfilledResult => + settled.status === 'fulfilled', + ) + .map((settled) => settled.value) + .filter((candidate): candidate is LocalMetroServer => candidate !== undefined); + if (candidates.length === 0) return undefined; + + const roots = candidateProjectRoots(input.projectRoots); + // Only a server that names one of these projects (or one of their parents or children, as a + // monorepo server reports the repo root) counts. A running server for another project, or one that + // reports no root at all, is not this session's dev server, and reloading it would act on the + // wrong app. + return candidates.find((candidate) => + candidate.projectRoot + ? roots.some((root) => projectRootsOverlap(root, normalizeRealPath(candidate.projectRoot!))) + : false, + ); +} + +async function probeIsRunningDevServer( + serverUrl: URL, + probe: MetroDevServerProbe, +): Promise { + const probeServer = probe.probeServer ?? probeLocalMetroServer; + const confirmed = await probeServer(serverUrl, STATUS_PROBE_TIMEOUT_MS).catch(() => undefined); + return confirmed !== undefined; +} + +async function listLocalListeningPorts(): Promise { + const result = await runCmd('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-Fn'], { + allowFailure: true, + timeoutMs: HOST_READ_TIMEOUT_MS, + }); + if (result.exitCode !== 0) return []; + const ports = new Set(); + for (const line of result.stdout.split('\n')) { + if (!line.startsWith('n')) continue; + const port = readPortFromSocketName(line.slice(1)); + if (port !== undefined) ports.add(port); + } + return [...ports].sort((left, right) => left - right); +} + +/** One bounded `/status` read of a loopback address: running dev server, plus its project root. */ +async function probeLocalMetroServer( + serverUrl: URL, + timeoutMs: number, +): Promise { + try { + const response = await fetch(new URL('status', serverUrl), { + signal: AbortSignal.timeout(timeoutMs), + }); + if (!response.ok) return undefined; + const body = await response.text(); + if (!body.includes(METRO_STATUS_READY_TEXT)) return undefined; + const projectRoot = response.headers.get(METRO_PROJECT_ROOT_HEADER); + return { serverUrl, ...(projectRoot ? { projectRoot } : {}) }; + } catch { + return undefined; + } +} + +/** + * The typed answer for the case the silent fallback used to swallow: nothing binds this session to a + * dev server, so the address the fallback would have reached belongs to somebody else. + */ +export function metroDevServerUnresolvedError(): AppError { + const triedUrl = new URL(`http://${DEFAULT_METRO_HOST}:${DEFAULT_METRO_PORT}`); + return new AppError( + 'COMMAND_FAILED', + `React Native dev server is not bound to this session and none was found for its app, so nothing was reloaded. The address the fallback would have used is ${triedUrl.origin}.`, + { + reason: METRO_RELOAD_REASONS.devServerUnresolved.reason, + triedUrl: triedUrl.toString(), + hint: + 'Pass --metro-port (with --metro-host when it is not localhost) for one call, ' + + 'or run metro prepare, or open with --metro-host/--metro-port so the session keeps the binding.', + }, + ); +} + +function readPortFromSocketName(name: string): number | undefined { + const separator = name.lastIndexOf(':'); + if (separator <= 0) return undefined; + const port = Number.parseInt(name.slice(separator + 1), 10); + return Number.isInteger(port) && port > 0 && port <= 65_535 ? port : undefined; +} + +function isLoopbackUrl(url: URL): boolean { + return ['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0'].includes(url.hostname); +} + +function projectRootsOverlap(left: string, right: string): boolean { + return left === right || left.startsWith(`${right}/`) || right.startsWith(`${left}/`); +} + +function candidateProjectRoots(projectRoots: string[]): string[] { + const resolved = projectRoots.map((root) => normalizeRealPath(root)); + return [...new Set(resolved)]; +} + +function normalizeRealPath(input: string): string { + try { + return fs.realpathSync(input); + } catch { + return path.resolve(input); + } +} + +function fileExists(filePath: string): boolean { + try { + fs.accessSync(filePath, fs.constants.F_OK); + return true; + } catch { + return false; + } +} + +function parseJsonObject(text: string): Record | undefined { + try { + const parsed: unknown = JSON.parse(text); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) + ? (parsed as Record) + : undefined; + } catch { + return undefined; + } +} + +function asNonEmptyString(value: unknown): string | undefined { + return typeof value === 'string' && value.trim() ? value.trim() : undefined; +} + +function parseHostAndPort(value: string, scheme: 'http' | 'https'): URL | undefined { + const separator = value.lastIndexOf(':'); + if (separator <= 0) return undefined; + const host = value.slice(0, separator); + const port = Number.parseInt(value.slice(separator + 1), 10); + if (!host || !Number.isInteger(port) || port < 1 || port > 65_535) return undefined; + try { + return new URL(`${scheme}://${host}:${port}`); + } catch { + return undefined; + } +} diff --git a/packages/react-native/src/metro/metro-reload-endpoints.ts b/packages/react-native/src/metro/metro-reload-endpoints.ts index 60691104e5..59fa3fe0aa 100644 --- a/packages/react-native/src/metro/metro-reload-endpoints.ts +++ b/packages/react-native/src/metro/metro-reload-endpoints.ts @@ -5,9 +5,8 @@ import { trimRuntimeValue, } from '@agent-device/host-kit/runtime-transport-hints'; -const DEFAULT_METRO_HOST = 'localhost'; -const DEFAULT_METRO_PORT = 8081; - +export const DEFAULT_METRO_HOST = 'localhost'; +export const DEFAULT_METRO_PORT = 8081; // Expo apps load JS through this virtual entry; index.bundle fails on Expo dev servers. export const EXPO_VIRTUAL_ENTRY_BUNDLE_PATH = '.expo/.virtual-metro-entry.bundle'; @@ -34,6 +33,23 @@ export function parsePort(value: number | string | undefined, fallback: number): return parsed; } +/** + * Whether the caller or the session already names a dev server: a bundle URL, a host, or a port from + * either. When this is false, nothing is bound, and resolving a reload target needs a discovery step + * rather than a default address. + */ +export function isMetroTargetBound(input: MetroReloadTargetInput): boolean { + const explicit = + trimRuntimeValue(input.bundleUrl) !== undefined || + trimRuntimeValue(input.metroHost) !== undefined || + input.metroPort !== undefined; + const session = + trimRuntimeValue(input.runtime?.bundleUrl) !== undefined || + trimRuntimeValue(input.runtime?.metroHost) !== undefined || + input.runtime?.metroPort !== undefined; + return explicit || session; +} + // Explicit flags win over session runtime hints, which win over localhost:8081. export function resolveMetroServerUrl(input: MetroReloadTargetInput): URL { const explicitBundleUrl = trimRuntimeValue(input.bundleUrl); @@ -58,7 +74,11 @@ export function resolveMetroServerUrl(input: MetroReloadTargetInput): URL { } export function resolveMetroReloadEndpoints(input: MetroReloadTargetInput): MetroReloadEndpoints { - const serverUrl = resolveMetroServerUrl(input); + return buildMetroReloadEndpoints(resolveMetroServerUrl(input)); +} + +/** The reload control endpoints of one dev-server address, keeping its mount prefix. */ +export function buildMetroReloadEndpoints(serverUrl: URL): MetroReloadEndpoints { const prefix = serverUrl.pathname.replace(/\/+$/, ''); const reloadUrl = new URL(serverUrl); reloadUrl.pathname = `${prefix}/reload`; diff --git a/packages/react-native/src/metro/metro-session-hints.ts b/packages/react-native/src/metro/metro-session-hints.ts index d9260cdbca..649c7c6558 100644 --- a/packages/react-native/src/metro/metro-session-hints.ts +++ b/packages/react-native/src/metro/metro-session-hints.ts @@ -6,11 +6,15 @@ import path from 'node:path'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { safeSessionName } from '@agent-device/host-kit/session-paths'; import { resolveMetroServerUrl, type MetroReloadTargetInput } from './metro-reload-endpoints.ts'; +import type { MetroAppTarget } from './metro-dev-server-discovery.ts'; -/** Reload control and the prepared device addresses that may reuse it on a fresh open. */ +/** Reload control, the prepared device addresses that may reuse it, and the app the session opened. */ export type MetroSessionHints = { - controlBaseUrl: string; + /** Absent when the session opened an app without any dev-server hint to bind. */ + controlBaseUrl?: string; deviceBaseUrls?: string[]; + /** The app this session opened, so a reload can ask that app's host about it. */ + app?: MetroAppTarget; }; export type MetroSessionScope = { stateDir: string; session: string }; @@ -45,7 +49,15 @@ export function writeMetroSessionHints( fs.writeFileSync(filePath, `${JSON.stringify(options.hints, null, 2)}\n`, 'utf8'); } -export function readMetroSessionHints(options: MetroSessionScope): MetroSessionHints | undefined { +/** The stored session record: the control address, the device addresses, and the app it opened. */ +type MetroSessionRecord = { + raw: Record; + controlBaseUrl?: string; + deviceBaseUrls?: string[]; + app?: MetroAppTarget; +}; + +function readMetroSessionRecord(options: MetroSessionScope): MetroSessionRecord | undefined { const filePath = metroSessionHintsPath(options.stateDir, options.session); let raw: string; try { @@ -61,38 +73,92 @@ export function readMetroSessionHints(options: MetroSessionScope): MetroSessionH } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined; const record = parsed as Record; + const app = readStoredAppTarget(record.app); + const deviceBaseUrls = Array.isArray(record.deviceBaseUrls) + ? record.deviceBaseUrls.filter((value): value is string => typeof value === 'string') + : undefined; + const controlBaseUrl = + typeof record.controlBaseUrl === 'string' ? record.controlBaseUrl : undefined; + return { + raw: record, + ...(controlBaseUrl ? { controlBaseUrl } : {}), + ...(deviceBaseUrls ? { deviceBaseUrls } : {}), + ...(app ? { app } : {}), + }; +} + +function readStoredAppTarget(value: unknown): MetroAppTarget | undefined { + if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined; + const record = value as Record; + const platform = + record.platform === 'ios' || record.platform === 'android' ? record.platform : undefined; + const deviceId = typeof record.deviceId === 'string' ? record.deviceId : undefined; + if (!platform || !deviceId) return undefined; + const deviceKind = + record.deviceKind === 'simulator' || + record.deviceKind === 'emulator' || + record.deviceKind === 'device' + ? record.deviceKind + : undefined; + return { + platform, + deviceId, + ...(deviceKind ? { deviceKind } : {}), + ...(typeof record.appId === 'string' ? { appId: record.appId } : {}), + }; +} + +/** The app a session opened, even when the session never bound a dev server. */ +export function readMetroSessionAppTarget( + options: MetroSessionOptions, +): MetroAppTarget | undefined { + let scope: MetroSessionScope; try { - const runtime = { - metroHost: typeof record.metroHost === 'string' ? record.metroHost : undefined, - metroPort: typeof record.metroPort === 'number' ? record.metroPort : undefined, - bundleUrl: typeof record.bundleUrl === 'string' ? record.bundleUrl : undefined, + scope = resolveMetroSessionScope(options); + } catch { + return undefined; + } + return readMetroSessionRecord(scope)?.app; +} + +export function readMetroSessionHints(options: MetroSessionScope): MetroSessionHints | undefined { + const stored = readMetroSessionRecord(options); + if (!stored) return undefined; + // An app-only record binds no address: reload discovers the dev server instead of resolving one. + if (!stored.controlBaseUrl && !hasStoredRuntimeHints(stored.raw)) return undefined; + try { + const url = stored.controlBaseUrl + ? new URL(stored.controlBaseUrl) + : resolveMetroServerUrl({ runtime: readStoredRuntimeHints(stored.raw) }); + if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined; + return { + controlBaseUrl: url.toString(), + ...(stored.deviceBaseUrls ? { deviceBaseUrls: stored.deviceBaseUrls } : {}), + ...(stored.app ? { app: stored.app } : {}), }; - if ( - typeof record.controlBaseUrl !== 'string' && - Object.values(runtime).every((value) => value === undefined) - ) - return undefined; - const url = - typeof record.controlBaseUrl === 'string' - ? new URL(record.controlBaseUrl) - : resolveMetroServerUrl({ runtime }); - return url.protocol === 'http:' || url.protocol === 'https:' - ? { - controlBaseUrl: url.toString(), - ...(Array.isArray(record.deviceBaseUrls) - ? { - deviceBaseUrls: record.deviceBaseUrls.filter( - (value): value is string => typeof value === 'string', - ), - } - : {}), - } - : undefined; } catch { return undefined; } } +type LegacyRuntimeHintRecord = Record; + +function hasStoredRuntimeHints(record: LegacyRuntimeHintRecord): boolean { + return Object.values(readStoredRuntimeHints(record)).some((value) => value !== undefined); +} + +function readStoredRuntimeHints(record: LegacyRuntimeHintRecord): { + metroHost?: string; + metroPort?: number; + bundleUrl?: string; +} { + return { + metroHost: typeof record.metroHost === 'string' ? record.metroHost : undefined, + metroPort: typeof record.metroPort === 'number' ? record.metroPort : undefined, + bundleUrl: typeof record.bundleUrl === 'string' ? record.bundleUrl : undefined, + }; +} + export function clearMetroSessionHints(options: MetroSessionScope): void { fs.rmSync(metroSessionHintsPath(options.stateDir, options.session), { force: true }); } @@ -113,8 +179,8 @@ export function resolveSessionMetroServerUrl( function readScopedMetroSessionRuntime(scope: MetroSessionScope): SessionRuntimeHints | undefined { try { - const binding = readMetroSessionHints(scope); - return binding ? { bundleUrl: binding.controlBaseUrl } : undefined; + const controlBaseUrl = readMetroSessionHints(scope)?.controlBaseUrl; + return controlBaseUrl ? { bundleUrl: controlBaseUrl } : undefined; } catch { return undefined; } @@ -166,6 +232,8 @@ export type MetroSessionOpenInput = { runtime: SessionRuntimeHints | undefined; explicitRuntime: boolean; sessionReused: boolean; + /** The app the open launched, so a later reload can ask its host for the app's own address. */ + app?: MetroAppTarget; }; export function recordOpenedMetroSession( @@ -178,8 +246,19 @@ export function recordOpenedMetroSession( if (url) { const binding = input.explicitRuntime ? undefined : readMetroSessionHints(scope); if (binding && (input.sessionReused || binding.deviceBaseUrls?.includes(url))) return; - writeMetroSessionHints({ ...scope, hints: { controlBaseUrl: url } }); - } else if (!input.sessionReused) clearMetroSessionHints(scope); + writeMetroSessionHints({ + ...scope, + hints: { controlBaseUrl: url, ...(input.app ? { app: input.app } : {}) }, + }); + return; + } + // No dev-server hint came with the open, so no address is bound. A fresh session still records + // the app it opened: that is what a later reload looks the app's own address up from. A reused + // session keeps whatever its first open recorded. + if (!input.sessionReused) { + if (input.app) writeMetroSessionHints({ ...scope, hints: { app: input.app } }); + else clearMetroSessionHints(scope); + } } catch {} } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 16d33c8ffa..6714402b5b 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2179,7 +2179,7 @@ agent-device metro reload --bundle-url "http://localhost:8081/index.bundle?platf ``` - `metro reload` asks connected React Native dev builds to reload JavaScript without restarting the native process, like pressing `r` in the Metro terminal. -- Without flags, it reloads the dev server the session bound through `metro prepare` or `open`'s Metro hints, then `localhost:8081`. A reused session name never reloads a previous project's server. +- Without flags, it reloads the dev server the session bound through `metro prepare` or `open`'s Metro hints. When no session bound one and the app runs on a local simulator or emulator, it next uses the dev-server address the app itself stored, then a local dev server that serves this directory. Otherwise it fails with `details.reason: 'metro_dev_server_unresolved'` instead of calling `localhost:8081`, which belongs to whichever project owns that port. A reused session name never reloads a previous project's server. - Use `open --relaunch` instead when the app is not connected to Metro, the reload fails, or the native process must restart. See `agent-device help metro` for the binding rules. ## Media and logs diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 692fcc8dbf..2ac1c0fbe2 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -832,6 +832,12 @@ These reasons can come from more than one command. | `event_creation_failed` | macOS could not create the keyboard or mouse event to post. | | `missing_button` | No button on the alert fits the requested accept or dismiss. | +### Metro reload + +| Reason | Meaning | +| --- | --- | +| `metro_dev_server_unresolved` | No dev server is bound to the session and none was found for its app; nothing was reloaded. | + ### Platform runtime | Reason | Meaning | From 7351ef4d95947d46d9fec5c693c505dace4257f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 11:29:58 +0100 Subject: [PATCH 02/10] test(metro): cover discovery branches and refuse a foreign app-reported server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Splits the pure reads out of dev-server discovery — lsof and netstat port tables, the app's stored preferences, the project-root header, host:port, and root overlap — so each branch is tested without a process or a socket, and the I/O wrappers stay thin. Gates local lookups on the app being recorded as hosted here, refuses an app-reported server whose root names another project, batches port probes instead of dropping ports past the 32nd, falls back to netstat where lsof is missing, treats a blank metroPort as no binding, and replaces the recorded app on every open. Co-authored-by: Apex --- .../index-metro-reload-discovery.test.ts | 271 ++++++++++++++++++ packages/client/src/index.ts | 26 +- packages/command-surface/src/metro/index.ts | 2 +- .../src/daemon-resolution-loopback.test.ts | 28 ++ .../src/metro-reload-local-discovery.test.ts | 156 ++++++++++ .../react-native/src/metro/client-metro.ts | 6 + .../metro/metro-dev-server-discovery.test.ts | 164 ++++++++++- .../src/metro/metro-dev-server-discovery.ts | 253 ++++++++-------- .../metro/metro-dev-server-host-io.test.ts | 247 ++++++++++++++++ .../metro/metro-dev-server-parsing.test.ts | 135 +++++++++ .../src/metro/metro-dev-server-parsing.ts | 150 ++++++++++ .../src/metro/metro-reload-endpoints.test.ts | 26 +- .../src/metro/metro-reload-endpoints.ts | 21 +- .../src/metro/metro-session-hints.test.ts | 172 +++++++++++ .../src/metro/metro-session-hints.ts | 25 +- .../test-kit/src/metro-session.fixtures.ts | 14 +- website/docs/docs/commands.md | 2 +- 17 files changed, 1541 insertions(+), 157 deletions(-) create mode 100644 packages/client/src/__tests__/index-metro-reload-discovery.test.ts create mode 100644 packages/daemon-contracts/src/daemon-resolution-loopback.test.ts create mode 100644 packages/react-native/src/metro-reload-local-discovery.test.ts create mode 100644 packages/react-native/src/metro/metro-dev-server-host-io.test.ts create mode 100644 packages/react-native/src/metro/metro-dev-server-parsing.test.ts create mode 100644 packages/react-native/src/metro/metro-dev-server-parsing.ts diff --git a/packages/client/src/__tests__/index-metro-reload-discovery.test.ts b/packages/client/src/__tests__/index-metro-reload-discovery.test.ts new file mode 100644 index 0000000000..f20e0a418c --- /dev/null +++ b/packages/client/src/__tests__/index-metro-reload-discovery.test.ts @@ -0,0 +1,271 @@ +import { test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import path from 'node:path'; +import { createAgentDeviceClient } from '../index.ts'; +import { AppError } from '@agent-device/kernel/errors'; +import { + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + writeMetroSessionFixture, +} from '@agent-device/test-kit'; +import type { MetroAppTarget } from '@agent-device/react-native'; + +// `metro reload` may look a dev server up on this machine only when the client's daemon is local and +// the session's app is recorded as hosted here. These pin that decision through the real client path. +// The port listing is answered from a table, so a test sweeps its own ports instead of the machine's, +// and never reaches the default port a refused search would otherwise call. + +const listing = vi.hoisted(() => ({ ports: [] as number[], commands: [] as string[] })); + +vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({ + ...(await importOriginal()), + runCmd: async (cmd: string) => { + listing.commands.push(cmd); + return cmd === 'lsof' + ? { + stdout: listing.ports.map((port) => `n127.0.0.1:${port}`).join('\n'), + stderr: '', + exitCode: 0, + } + : { stdout: '', stderr: '', exitCode: 1 }; + }, +})); + +const localApp = { + platform: 'android', + deviceKind: 'emulator', + deviceId: 'emulator-5554', + appId: 'com.example.app', + hostedLocally: true, +} as const satisfies MetroAppTarget; + +function devServer(projectRoot: string) { + const requests: string[] = []; + const server = createServer((req, res) => { + const url = req.url ?? ''; + requests.push(url); + if (url.startsWith('/status')) { + res.setHeader('x-react-native-project-root', projectRoot); + res.end('packager-status:running'); + return; + } + if (url.startsWith('/reload')) { + res.end('RELOADED'); + return; + } + res.statusCode = 404; + res.end('not found'); + }); + return { server, requests }; +} + +function workspace(name: string) { + const root = mkdtempForTestSync(`agent-device-client-reload-${name}`); + const projectRoot = path.join(root, 'project'); + mkdirSync(projectRoot, { recursive: true }); + writeFileSync(path.join(projectRoot, 'package.json'), '{"name":"p","private":true}'); + return { stateDir: path.join(root, 'state'), projectRoot }; +} + +/** A client whose daemon is local unless `daemonBaseUrl` says otherwise, and that never gets a command. */ +function clientFor(options: { stateDir: string; projectRoot: string; daemonBaseUrl: string }) { + return createAgentDeviceClient( + { + session: 'qa', + stateDir: options.stateDir, + cwd: options.projectRoot, + daemonBaseUrl: options.daemonBaseUrl, + }, + { + transport: async () => { + throw new Error('flagless metro reload must stay local and never call the daemon'); + }, + host: { env: {}, cwd: options.projectRoot }, + }, + ); +} + +async function withDevServer( + projectRoot: string, + ports: boolean, + run: (port: number, requests: string[]) => Promise, +): Promise { + const { server, requests } = devServer(projectRoot); + const port = await listenOnLoopback(server); + listing.ports = ports ? [port] : []; + listing.commands = []; + try { + return await run(port, requests); + } finally { + listing.ports = []; + listing.commands = []; + await closeLoopbackServer(server); + } +} + +test('a local daemon reload reloads the local dev server that serves this project', async () => { + const { stateDir, projectRoot } = workspace('local-found'); + writeMetroSessionFixture({ stateDir, session: 'qa', hints: { app: localApp } }); + try { + await withDevServer(projectRoot, true, async (port, requests) => { + const client = clientFor({ + stateDir, + projectRoot, + daemonBaseUrl: `http://127.0.0.1:${port}`, + }); + const result = await client.metro.reload(); + assert.equal(result.reloadUrl, `http://127.0.0.1:${port}/reload`); + assert.equal(result.body, 'RELOADED'); + assert.deepEqual(listing.commands, ['lsof']); + assert.ok(requests.some((url) => url.startsWith('/status'))); + }); + } finally { + rmSync(path.dirname(stateDir), { recursive: true, force: true }); + } +}); + +test('a local daemon reload refuses another project’s server and fails typed', async () => { + const { stateDir, projectRoot } = workspace('local-foreign'); + writeMetroSessionFixture({ stateDir, session: 'qa', hints: { app: localApp } }); + try { + await withDevServer('/someone/else/project', true, async (port, requests) => { + const client = clientFor({ + stateDir, + projectRoot, + daemonBaseUrl: `http://127.0.0.1:${port}`, + }); + await assert.rejects( + () => client.metro.reload(), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, 'metro_dev_server_unresolved'); + return true; + }, + ); + // The foreign server was probed and refused — never reloaded. + assert.equal( + requests.some((url) => url.startsWith('/reload')), + false, + ); + }); + } finally { + rmSync(path.dirname(stateDir), { recursive: true, force: true }); + } +}); + +test('a bound session address is used as given, with no search of this machine', async () => { + const { stateDir, projectRoot } = workspace('local-bound'); + writeMetroSessionFixture({ + stateDir, + session: 'qa', + hints: { app: localApp, controlBaseUrl: 'http://127.0.0.1:1/' }, + }); + try { + await withDevServer(projectRoot, true, async (port) => { + const client = clientFor({ + stateDir, + projectRoot, + daemonBaseUrl: `http://127.0.0.1:${port}`, + }); + // The bound address is unreachable, so the reload fails — but only after the client committed to + // it without probing this machine's ports, which is what the caller asked for. + await client.metro.reload().catch(() => undefined); + assert.deepEqual(listing.commands, []); + }); + } finally { + rmSync(path.dirname(stateDir), { recursive: true, force: true }); + } +}); + +/** + * Answers every HTTP call reload makes from a table: records the address, serves `/status` as this + * project's dev server, and `/reload` as a reload. Used by the cases that must prove *which* address + * reload settled on, including the default one, without a server on that port. + */ +function recordFetchCalls(run: () => Promise, projectRoot: string) { + const calls: string[] = []; + const originalFetch = globalThis.fetch; + globalThis.fetch = (async (input: URL | string) => { + const url = new URL(String(input)); + calls.push(url.toString()); + if (url.pathname === '/status') { + return new Response('packager-status:running', { + headers: { 'x-react-native-project-root': projectRoot }, + }); + } + return new Response('RELOADED'); + }) as typeof globalThis.fetch; + return run() + .catch(() => undefined) + .then(() => { + globalThis.fetch = originalFetch; + return calls; + }); +} + +test('a client aimed at a remote daemon does not offer this machine’s dev servers', async () => { + const { stateDir, projectRoot } = workspace('remote-daemon'); + writeMetroSessionFixture({ stateDir, session: 'qa', hints: { app: localApp } }); + listing.ports = [8081]; + listing.commands = []; + try { + const client = clientFor({ + stateDir, + projectRoot, + daemonBaseUrl: 'https://fleet.example.test', + }); + const calls = await recordFetchCalls(() => client.metro.reload(), projectRoot); + // The devices a remote daemon drives are not on this machine, so reload stays on the address the + // session's own hints resolve to and never sweeps these ports. + assert.deepEqual(listing.commands, []); + assert.deepEqual(calls, ['http://localhost:8081/reload']); + } finally { + listing.ports = []; + listing.commands = []; + rmSync(path.dirname(stateDir), { recursive: true, force: true }); + } +}); + +test('a session whose app this machine does not host skips the local search', async () => { + const { stateDir, projectRoot } = workspace('remote-device'); + writeMetroSessionFixture({ + stateDir, + session: 'qa', + hints: { app: { ...localApp, deviceKind: 'device', hostedLocally: false } }, + }); + listing.ports = [8081]; + listing.commands = []; + try { + const client = clientFor({ + stateDir, + projectRoot, + daemonBaseUrl: 'http://127.0.0.1:1', + }); + const calls = await recordFetchCalls(() => client.metro.reload(), projectRoot); + assert.deepEqual(listing.commands, []); + assert.deepEqual(calls, ['http://localhost:8081/reload']); + } finally { + listing.ports = []; + listing.commands = []; + rmSync(path.dirname(stateDir), { recursive: true, force: true }); + } +}); + +test('a session with no recorded app skips the local search', async () => { + const { stateDir, projectRoot } = workspace('no-app'); + listing.ports = [8081]; + listing.commands = []; + try { + const client = clientFor({ stateDir, projectRoot, daemonBaseUrl: 'http://127.0.0.1:1' }); + const calls = await recordFetchCalls(() => client.metro.reload(), projectRoot); + assert.deepEqual(listing.commands, []); + assert.deepEqual(calls, ['http://localhost:8081/reload']); + } finally { + listing.ports = []; + listing.commands = []; + rmSync(path.dirname(stateDir), { recursive: true, force: true }); + } +}); diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 78d51cf5cb..026e012747 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -30,6 +30,7 @@ import type { } from '@agent-device/contracts/client'; import type { AgentArtifactsResult } from '@agent-device/contracts/observability'; import type { MetroPrepareOptions } from '@agent-device/contracts/remote'; +import type { DeviceSelectionMetadata } from '@agent-device/contracts/client'; import { isNonDefaultResponseLevel, type ResponseLevel } from '@agent-device/kernel/contracts'; import { AppError, throwDaemonError } from '@agent-device/kernel/errors'; import { createRequestId } from '@agent-device/host-kit/diagnostics'; @@ -345,13 +346,18 @@ export function createAgentDeviceClient( const device = normalizeOpenDevice(data); const appBundleId = readOptionalString(data, 'appBundleId'); const appId = appBundleId; + const selection = normalizeDeviceSelection(data.selection); await recordOpenedMetroSession( { ...mergeClientOptions(config, options), session }, { explicitRuntime: options.runtime !== undefined, runtime: mergeClientOptions(config, options).runtime, sessionReused: data.sessionReused === true, - app: metroAppTargetFromOpen(device, appBundleId), + app: metroAppTargetFromOpen( + device, + appBundleId, + appHostedLocally(config, host, selection), + ), }, ); return { @@ -364,7 +370,7 @@ export function createAgentDeviceClient( appName: readOptionalString(data, 'appName'), appBundleId, appId, - selection: normalizeDeviceSelection(data.selection), + selection, startup: normalizeStartupSample(data.startup), runtime: normalizeRuntimeHints(data.runtime), device, @@ -591,6 +597,20 @@ function daemonIsLocal(config: AgentDeviceClientConfig, host: HostEnvironment): return daemonBaseUrlIsLocal(config.daemonBaseUrl ?? host.env.AGENT_DEVICE_DAEMON_BASE_URL); } +/** + * Whether `open` proved the session's device runs on this machine: the daemon answers here, and it + * resolved the device from this host's own inventory. A provider device, a device inherited from an + * earlier request, or a daemon on another machine leaves it unproven, and reload then skips the local + * lookups instead of reading unrelated state. + */ +function appHostedLocally( + config: AgentDeviceClientConfig, + host: HostEnvironment, + selection: DeviceSelectionMetadata | undefined, +): boolean { + return daemonIsLocal(config, host) && selection?.source === 'local'; +} + /** * The app an `open` launched, in the shape the Metro reload discovery reads back. Only an iOS or * Android app with a resolved device and bundle id is worth recording: anything else has no @@ -599,6 +619,7 @@ function daemonIsLocal(config: AgentDeviceClientConfig, host: HostEnvironment): function metroAppTargetFromOpen( device: ReturnType, appBundleId: string | undefined, + hostedLocally: boolean, ): MetroAppTarget | undefined { if (!device || !appBundleId) return undefined; if (device.platform !== 'ios' && device.platform !== 'android') return undefined; @@ -607,6 +628,7 @@ function metroAppTargetFromOpen( deviceId: device.id, ...(device.kind ? { deviceKind: device.kind } : {}), appId: appBundleId, + ...(hostedLocally ? { hostedLocally: true } : {}), }; } diff --git a/packages/command-surface/src/metro/index.ts b/packages/command-surface/src/metro/index.ts index 541db1c020..ef756f4d09 100644 --- a/packages/command-surface/src/metro/index.ts +++ b/packages/command-surface/src/metro/index.ts @@ -138,7 +138,7 @@ export const metroCommandFacet = defineCommandFacet({ summary: 'Prepare the dev server or reload apps', searchHint: 'bundler', cliDetail: - "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. When the session never bound one and its app runs on a local simulator or emulator, reload then reads the dev-server address the app itself stored (RCT_jsLocation in the app's preferences on an iOS simulator) and, failing that, probes the ports a local process is listening on for a dev server whose X-React-Native-Project-Root matches this directory, so it never silently reloads a different project's server. When nothing resolves, reload fails with details.reason 'metro_dev_server_unresolved' naming the address it would have used, instead of calling localhost:8081, which belongs to whichever project owns that port. A physical or provider-hosted device is not this machine, so its sessions skip the local lookups and keep the default address. 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).", + "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. When the session never bound one and open recorded its app as hosted on this machine, on a simulator or emulator, reload then reads the dev-server address the app itself stored (RCT_jsLocation in the app's preferences; iOS simulators only) and accepts it when a running dev server there reports a project root that is this project's root or a parent or child of it. Failing that, it probes the ports a local process is listening on for a dev server whose X-React-Native-Project-Root is this project's root or a parent or child of it (a monorepo server reports the repo root), so it never silently reloads a different project's server. When nothing resolves, reload fails with details.reason 'metro_dev_server_unresolved' naming the address it would have used, instead of calling localhost:8081, which belongs to whichever project owns that port. A session whose device this machine does not host — a physical or provider-hosted device, or an app-less session — skips the local lookups and keeps the default address. 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).", }, metadata: metroCommandMetadata, run: async (client, input): Promise => diff --git a/packages/daemon-contracts/src/daemon-resolution-loopback.test.ts b/packages/daemon-contracts/src/daemon-resolution-loopback.test.ts new file mode 100644 index 0000000000..287033ae19 --- /dev/null +++ b/packages/daemon-contracts/src/daemon-resolution-loopback.test.ts @@ -0,0 +1,28 @@ +import { expect, test } from 'vitest'; +import { daemonBaseUrlIsLocal, isLoopbackHostname } from './daemon-resolution.ts'; + +test('a daemon base URL on loopback addresses this machine', () => { + expect(daemonBaseUrlIsLocal(undefined)).toBe(true); + expect(daemonBaseUrlIsLocal('')).toBe(true); + expect(daemonBaseUrlIsLocal('http://localhost:4560')).toBe(true); + expect(daemonBaseUrlIsLocal('http://127.0.0.1:4560/rpc')).toBe(true); + expect(daemonBaseUrlIsLocal('http://[::1]:4560')).toBe(true); +}); + +test('a daemon base URL off loopback addresses another machine', () => { + expect(daemonBaseUrlIsLocal('https://fleet.example.test')).toBe(false); + expect(daemonBaseUrlIsLocal('http://10.0.0.7:4560')).toBe(false); + // An unusable base URL is refused when the transport resolves it; here it is treated as remote. + expect(daemonBaseUrlIsLocal('not a url')).toBe(false); +}); + +test('loopback hostnames are recognized in each spelling a base URL carries', () => { + expect(isLoopbackHostname('LocalHost ')).toBe(true); + expect(isLoopbackHostname('127.0.0.1')).toBe(true); + expect(isLoopbackHostname('[::1]')).toBe(true); + expect(isLoopbackHostname('::ffff:127.0.0.1')).toBe(true); + expect(isLoopbackHostname('0.0.0.0')).toBe(false); + expect(isLoopbackHostname('127.1.2.3')).toBe(true); + expect(isLoopbackHostname('localhost.example.test')).toBe(false); + expect(isLoopbackHostname('')).toBe(false); +}); diff --git a/packages/react-native/src/metro-reload-local-discovery.test.ts b/packages/react-native/src/metro-reload-local-discovery.test.ts new file mode 100644 index 0000000000..8f7e326b41 --- /dev/null +++ b/packages/react-native/src/metro-reload-local-discovery.test.ts @@ -0,0 +1,156 @@ +import { test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import path from 'node:path'; +import { reloadMetro } from './index.ts'; +import { AppError } from '@agent-device/kernel/errors'; +import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import type { MetroAppTarget } from './metro/metro-dev-server-discovery.ts'; + +// These run the whole local reload path against a loopback dev server: the session record's app, the +// host's listening ports, the real `/status` probe, and the real reload call. Only the port listing is +// answered from a table, so a test does not sweep whatever else this machine listens on. + +const portListing = vi.hoisted(() => ({ ports: [] as number[] })); + +vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({ + ...(await importOriginal()), + runCmd: async (cmd: string) => + cmd === 'lsof' + ? { + stdout: portListing.ports.map((port) => `n127.0.0.1:${port}`).join('\n'), + stderr: '', + exitCode: 0, + } + : { stdout: '', stderr: '', exitCode: 1 }, +})); + +const app: MetroAppTarget = { + platform: 'android', + deviceKind: 'emulator', + deviceId: 'emulator-5554', + appId: 'com.example.app', + hostedLocally: true, +}; + +function answerStatus(projectRoot: string) { + const requests: string[] = []; + const server = createServer((req, res) => { + const url = req.url ?? ''; + requests.push(url); + if (url.startsWith('/status')) { + res.setHeader('x-react-native-project-root', projectRoot); + res.end('packager-status:running'); + return; + } + if (url.startsWith('/reload')) { + res.end('RELOADED'); + return; + } + res.statusCode = 404; + res.end('not found'); + }); + return { server, requests }; +} + +function projectDir(name: string): string { + const root = mkdtempForTestSync(`agent-device-metro-reload-${name}`); + const projectRoot = path.join(root, 'project'); + mkdirSync(projectRoot, { recursive: true }); + writeFileSync(path.join(projectRoot, 'package.json'), '{"name":"p","private":true}'); + return projectRoot; +} + +test('a local reload with no binding reloads the dev server that serves this project', async () => { + const projectRoot = projectDir('match'); + const { server, requests } = answerStatus(projectRoot); + const port = await listenOnLoopback(server); + portListing.ports = [port]; + try { + const result = await reloadMetro({ + host: { env: {}, cwd: projectRoot }, + projectRoot, + app, + }); + assert.equal(result.reloadUrl, `http://127.0.0.1:${port}/reload`); + assert.equal(result.body, 'RELOADED'); + assert.ok(requests.some((url) => url.startsWith('/status'))); + } finally { + portListing.ports = []; + await closeLoopbackServer(server); + rmSync(projectRoot, { recursive: true, force: true }); + } +}); + +test('a local reload never picks another project’s dev server and fails typed instead', async () => { + const projectRoot = projectDir('foreign'); + const { server, requests } = answerStatus('/someone/else/project'); + const port = await listenOnLoopback(server); + portListing.ports = [port]; + try { + await assert.rejects( + () => reloadMetro({ host: { env: {}, cwd: projectRoot }, projectRoot, app }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, 'metro_dev_server_unresolved'); + assert.equal(error.details?.triedUrl, 'http://localhost:8081/'); + return true; + }, + ); + // The foreign server was probed and refused — never reloaded. + assert.ok(requests.some((url) => url.startsWith('/status'))); + assert.equal( + requests.some((url) => url.startsWith('/reload')), + false, + ); + } finally { + portListing.ports = []; + await closeLoopbackServer(server); + rmSync(projectRoot, { recursive: true, force: true }); + } +}); + +test('an explicit target is never second-guessed: discovery does not run for a bound reload', async () => { + const projectRoot = projectDir('bound'); + const { server, requests } = answerStatus('/someone/else/project'); + const port = await listenOnLoopback(server); + portListing.ports = [port]; + try { + const result = await reloadMetro({ + metroHost: '127.0.0.1', + metroPort: port, + host: { env: {}, cwd: projectRoot }, + projectRoot, + app, + }); + assert.equal(result.reloadUrl, `http://127.0.0.1:${port}/reload`); + assert.equal(result.body, 'RELOADED'); + assert.equal( + requests.some((url) => url.startsWith('/status')), + false, + ); + } finally { + portListing.ports = []; + await closeLoopbackServer(server); + rmSync(projectRoot, { recursive: true, force: true }); + } +}); + +test('reload without a host keeps the pre-discovery default address', async () => { + const { server, requests } = answerStatus('/someone/else/project'); + const port = await listenOnLoopback(server); + portListing.ports = [port]; + try { + // No `host`: no machine was named to look a dev server up on, so the hints resolve as before. + const result = await reloadMetro({ metroHost: '127.0.0.1', metroPort: port }); + assert.equal(result.reloadUrl, `http://127.0.0.1:${port}/reload`); + assert.equal( + requests.some((url) => url.startsWith('/status')), + false, + ); + } finally { + portListing.ports = []; + await closeLoopbackServer(server); + } +}); diff --git a/packages/react-native/src/metro/client-metro.ts b/packages/react-native/src/metro/client-metro.ts index b0725f7e77..7790b69585 100644 --- a/packages/react-native/src/metro/client-metro.ts +++ b/packages/react-native/src/metro/client-metro.ts @@ -1052,6 +1052,12 @@ async function broadcastReloadOverMessageSocket( }); } +/** + * Resolves the reload endpoints. With a `host`, an unbound target goes through discovery, which fails + * typed rather than calling `localhost:8081`. Without one, this stays the pre-discovery behavior: the + * address the flags and runtime hints resolve to, the default included, because a caller that names + * no host has named no machine to look a dev server up on. + */ async function resolveReloadEndpoints(input: ReloadMetroOptions): Promise { if (!input.host) return resolveMetroReloadEndpoints(input); const resolved = await resolveMetroReloadServerUrl({ diff --git a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts index 51f2ac70f7..8a7e6d136d 100644 --- a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts @@ -4,20 +4,23 @@ import { AppError } from '@agent-device/kernel/errors'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { METRO_RELOAD_REASONS, - canDiscoverForDeviceKind, + canDiscoverForApp, discoverLocalMetroServer, metroDevServerUnresolvedError, resolveMetroReloadServerUrl, type LocalMetroServer, type MetroAppTarget, + type MetroDevServerProbe, } from './metro-dev-server-discovery.ts'; const host: HostEnvironment = { env: {}, cwd: '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/app/project' }; +// The trait `open` records when it resolved the device from this machine's own inventory. const simulatorApp: MetroAppTarget = { platform: 'ios', deviceKind: 'simulator', deviceId: 'UDID-1', appId: 'com.example.app', + hostedLocally: true, }; function serverAt(port: number, projectRoot?: string): LocalMetroServer { @@ -44,7 +47,7 @@ function probeReturning( recorded.appRead += 1; return undefined; }, - }, + } satisfies MetroDevServerProbe, }; } @@ -70,6 +73,27 @@ test('a binding is the answer: neither the app nor the local ports are consulted assert.deepEqual(probe.record, { appRead: 0, portsRead: 0 }); }); +test('a blank port is no binding: an empty --metro-port reaches discovery, not the default', async () => { + const probe = probeReturning([serverAt(8096, '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/app/project')]); + const resolved = await resolveMetroReloadServerUrl({ + metroPort: '', + host, + app: simulatorApp, + probe: probe.probe, + }); + assert.equal(resolved.resolvedBy, 'local-project-root'); + assert.equal(resolved.serverUrl.port, '8096'); + + // A session hint that carries no host name is no binding either. + const sessionHost = await resolveMetroReloadServerUrl({ + runtime: { metroHost: ' ' }, + host, + app: simulatorApp, + probe: probe.probe, + }); + assert.equal(sessionHost.resolvedBy, 'local-project-root'); +}); + test('with no binding, the address the app itself stored wins over a local search', async () => { const probe = probeReturning([serverAt(8096, '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/app/project')]); const resolved = await resolveMetroReloadServerUrl({ @@ -85,6 +109,74 @@ test('with no binding, the address the app itself stored wins over a local searc assert.equal(probe.record.portsRead, 0); }); +test('an app-reported server for another project is refused, not reloaded', async () => { + // The app's stored port now holds a different project's Metro: neither the app-reported step nor the + // local sweep may accept it, so reload refuses rather than restarting an unrelated app. + const probe = probeReturning([serverAt(8096, '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/other/project')]); + await assert.rejects( + () => + resolveMetroReloadServerUrl({ + host, + app: simulatorApp, + projectRoot: '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/app/project', + probe: { + ...probe.probe, + readAppReportedServerUrl: async () => new URL('http://127.0.0.1:8096'), + }, + }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, METRO_RELOAD_REASONS.devServerUnresolved.reason); + return true; + }, + ); +}); + +test('a server that runs and reports no project root is still the address the app named', async () => { + const probe = probeReturning([serverAt(8096)]); + const resolved = await resolveMetroReloadServerUrl({ + host, + app: simulatorApp, + probe: { + ...probe.probe, + readAppReportedServerUrl: async () => new URL('http://127.0.0.1:8096'), + }, + }); + assert.equal(resolved.resolvedBy, 'app-reported'); + assert.equal(resolved.serverUrl.port, '8096'); +}); + +test('an app-reported address that is not loopback is taken without probing this host', async () => { + const probe = probeReturning([]); + const resolved = await resolveMetroReloadServerUrl({ + host, + app: simulatorApp, + probe: { + ...probe.probe, + readAppReportedServerUrl: async () => new URL('http://10.0.0.5:19000'), + }, + }); + assert.equal(resolved.resolvedBy, 'app-reported'); + assert.equal(resolved.serverUrl.origin, 'http://10.0.0.5:19000'); +}); + +test('an app-reported address whose probe fails is refused instead of trusted', async () => { + const resolved = await resolveMetroReloadServerUrl({ + host, + app: simulatorApp, + probe: { + listListeningPorts: async () => [8096, 8097], + probeServer: async (url: URL) => { + if (url.port === '8097') throw new Error('ECONNREFUSED'); + return serverAt(8096, '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/app/project'); + }, + readAppReportedServerUrl: async () => new URL('http://127.0.0.1:8097'), + }, + }); + assert.equal(resolved.resolvedBy, 'local-project-root'); + assert.equal(resolved.serverUrl.port, '8096'); +}); + test('an app address with no server behind it falls through to the local search', async () => { const resolved = await resolveMetroReloadServerUrl({ host, @@ -119,6 +211,46 @@ test("the local search matches the project root and never picks another project' assert.equal(foreign, undefined); }); +test('a port lister that fails, or finds nothing, yields no server', async () => { + const failing = await discoverLocalMetroServer({ + projectRoots: ['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/app/project'], + listListeningPorts: async () => { + throw new Error('lsof not found in PATH'); + }, + probeServer: async () => serverAt(8081, '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/app/project'), + }); + assert.equal(failing, undefined); + + const empty = await discoverLocalMetroServer({ + projectRoots: ['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/app/project'], + listListeningPorts: async () => [], + probeServer: async () => serverAt(8081, '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/app/project'), + }); + assert.equal(empty, undefined); +}); + +test('every listening port is probed, in bounded batches rather than at once', async () => { + const ports = Array.from({ length: 100 }, (_, index) => 20_000 + index); + let inFlight = 0; + let peakInFlight = 0; + const matching = await discoverLocalMetroServer({ + projectRoots: ['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/app/project'], + listListeningPorts: async () => ports, + probeServer: async (url: URL) => { + inFlight += 1; + peakInFlight = Math.max(peakInFlight, inFlight); + await Promise.resolve(); + inFlight -= 1; + return Number(url.port) === ports[ports.length - 1] + ? serverAt(ports[ports.length - 1]!, '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/app/project') + : undefined; + }, + }); + // The 100th port is a real candidate: truncating at the concurrency limit would miss it. + assert.equal(matching?.serverUrl.port, String(ports[ports.length - 1])); + assert.ok(peakInFlight <= 32, `peak in-flight was ${peakInFlight}`); +}); + test("a running server that reports no project root is not this project's dev server", async () => { const probe = probeReturning([serverAt(8096)]); await assert.rejects( @@ -147,21 +279,29 @@ test('nothing found fails typed and names the address the fallback would have us ); }); -test('a device this machine does not host keeps the previous address instead of probing ports', async () => { - for (const deviceKind of ['device', undefined] as const) { +test('an app whose host is not proven local keeps the previous address instead of probing', async () => { + for (const app of [ + { ...simulatorApp, hostedLocally: false }, + { ...simulatorApp, hostedLocally: undefined }, + { ...simulatorApp, deviceKind: 'device' as const }, + { ...simulatorApp, deviceKind: undefined }, + undefined, + ]) { const probe = probeReturning([serverAt(8096, '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/app/project')]); - const resolved = await resolveMetroReloadServerUrl({ - host, - app: { ...simulatorApp, deviceKind }, - probe: probe.probe, - }); + const resolved = await resolveMetroReloadServerUrl({ host, app, probe: probe.probe }); assert.equal(resolved.resolvedBy, 'default'); assert.equal(resolved.serverUrl.toString(), 'http://localhost:8081/'); assert.deepEqual(probe.record, { appRead: 0, portsRead: 0 }); } - assert.equal(canDiscoverForDeviceKind('device'), false); - assert.equal(canDiscoverForDeviceKind('simulator'), true); - assert.equal(canDiscoverForDeviceKind('emulator'), true); +}); + +test('discovery is allowed only for an app proven to be hosted here on a virtual target', () => { + assert.equal(canDiscoverForApp(simulatorApp), true); + assert.equal(canDiscoverForApp({ ...simulatorApp, deviceKind: 'emulator' }), true); + assert.equal(canDiscoverForApp({ ...simulatorApp, deviceKind: 'device' }), false); + assert.equal(canDiscoverForApp({ ...simulatorApp, hostedLocally: false }), false); + assert.equal(canDiscoverForApp({ ...simulatorApp, hostedLocally: undefined }), false); + assert.equal(canDiscoverForApp(undefined), false); }); test('the typed failure reads as its own reason', () => { diff --git a/packages/react-native/src/metro/metro-dev-server-discovery.ts b/packages/react-native/src/metro/metro-dev-server-discovery.ts index 2fe9cce1e2..1118eb72e8 100644 --- a/packages/react-native/src/metro/metro-dev-server-discovery.ts +++ b/packages/react-native/src/metro/metro-dev-server-discovery.ts @@ -10,16 +10,26 @@ import { resolveMetroServerUrl, type MetroReloadTargetInput, } from './metro-reload-endpoints.ts'; +import { + isMetroStatusBody, + parseAppReportedServerUrl, + parseLsofListeningPorts, + parseMetroProjectRootHeader, + parseNetstatListeningPorts, + projectRootsOverlap, +} from './metro-dev-server-parsing.ts'; /** - * The session's app, as `open` recorded it: the one thing a sessionless reload can still ask about - * on the machine that hosts the device. + * The session's app, as `open` recorded it. `hostedLocally` is the trait `open` observed — the + * session's device runs on the machine that hosts the record — so a reload knows whether it may read + * this machine's simulator containers and listening ports at all. */ export type MetroAppTarget = Readonly<{ platform: 'ios' | 'android'; deviceKind?: 'simulator' | 'emulator' | 'device'; deviceId: string; appId?: string; + hostedLocally?: boolean; }>; /** How a reload reached the dev server it is about to call. */ @@ -45,10 +55,7 @@ export const METRO_RELOAD_REASONS = { devServerUnresolved: { reason: 'metro_dev_server_unresolved' }, } as const satisfies ReasonTable<'metro reload'>; -const IOS_JS_LOCATION_KEY = 'RCT_jsLocation'; -const IOS_PACKAGER_SCHEME_KEY = 'RCT_packager_scheme'; const SIMULATOR_DEVICES_ROOT = 'Library/Developer/CoreSimulator/Devices'; -const METRO_STATUS_READY_TEXT = 'packager-status:running'; const METRO_PROJECT_ROOT_HEADER = 'x-react-native-project-root'; const HOST_READ_TIMEOUT_MS = 1_500; const STATUS_PROBE_TIMEOUT_MS = 800; @@ -81,13 +88,14 @@ export type ResolveMetroReloadServerInput = MetroReloadTargetInput & * 1. The binding: `--metro-host`/`--metro-port`/`--bundle-url`, or the address the session bound * through `metro prepare` or `open`'s Metro hint flags. The caller's answer is never second-guessed. * 2. What the app itself reports — on an iOS simulator, the dev-server address React Native keeps in - * the app's preferences. The app cannot be wrong about the server it loads its bundle from. + * the app's preferences. The app cannot be wrong about the server it loads its bundle from, but a + * live server at that address still has to serve this project to count. * 3. A local dev server that serves the current project. * - * Only a session whose app runs on a local simulator or emulator reaches steps 2 and 3: a remote - * device's host is not this machine, so its sessions keep their existing behavior, including the - * default address. With no signal at all, this fails typed rather than calling `localhost:8081`, - * which in an unbound session belongs to whichever project happens to own that port. + * Only a session whose app runs on a simulator or emulator reaches steps 2 and 3: a physical device's + * host is not this machine, so its sessions keep their existing behavior, including the default + * address. With no signal at all, this fails typed rather than calling `localhost:8081`, which in an + * unbound session belongs to whichever project happens to own that port. */ export async function resolveMetroReloadServerUrl( input: ResolveMetroReloadServerInput, @@ -97,29 +105,28 @@ export async function resolveMetroReloadServerUrl( } const app = input.app; - if (!app || !canDiscoverForDeviceKind(app.deviceKind)) { - // Nothing to discover from: no recorded app, or a device this machine does not host. The + if (!app || !canDiscoverForApp(app)) { + // Nothing to discover from: no recorded app, or an app whose host this machine cannot prove. The // address the caller's hints resolve to, default included, stays what it always was. return { serverUrl: resolveMetroServerUrl(input), resolvedBy: 'default' }; } const host = input.host; const probe = input.probe ?? {}; - const projectRoot = input.projectRoot ?? host.cwd; + const projectRoots = candidateProjectRoots([input.projectRoot ?? host.cwd, host.cwd]); const reported = await (probe.readAppReportedServerUrl ?? readAppReportedMetroServerUrl)( app, host, ).catch(() => undefined); - if (reported) { - // The app cannot be wrong about the server it loads from, but its stored address can outlive that - // server. On loopback, where this host can answer for it, one bounded probe settles it. - if (!isLoopbackUrl(reported) || (await probeIsRunningDevServer(reported, probe))) { - return { serverUrl: reported, resolvedBy: 'app-reported' }; - } + if (reported && (await servesProjectRoot(reported, projectRoots, probe))) { + // The app cannot be wrong about the server it loads from, but its stored address can outlive + // that server, and somebody else's Metro can take the port. On loopback, where this host can + // answer for it, one bounded probe settles both questions. + return { serverUrl: reported, resolvedBy: 'app-reported' }; } const discovered = await discoverLocalMetroServer({ - projectRoots: [projectRoot, host.cwd], + projectRoots, listListeningPorts: probe.listListeningPorts ?? listLocalListeningPorts, probeServer: probe.probeServer ?? probeLocalMetroServer, }); @@ -131,12 +138,33 @@ export async function resolveMetroReloadServerUrl( } /** - * Whether reload may look for a dev server on this machine for a session's device. A physical or - * provider-hosted device runs somewhere else: its dev server is not a local port, so probing here - * would answer a question nobody asked. + * Whether reload may look for a dev server on this machine for a session's app. It may, only when + * `open` recorded the app as hosted here: a provider-hosted or physical device runs somewhere else, + * so its dev server is not one of this machine's ports, and probing here would answer a question + * nobody asked. */ -export function canDiscoverForDeviceKind(kind: MetroAppTarget['deviceKind']): boolean { - return kind === 'simulator' || kind === 'emulator'; +export function canDiscoverForApp(app: MetroAppTarget | undefined): boolean { + if (!app || app.hostedLocally !== true) return false; + return app.deviceKind === 'simulator' || app.deviceKind === 'emulator'; +} + +/** + * Confirms an app-reported address against the project it must serve. A server that is not running, + * or one that names a project unrelated to this session, is refused. A server that reports no root at + * all is accepted: the app named this address itself, and older dev servers send no root header. + */ +async function servesProjectRoot( + serverUrl: URL, + projectRoots: string[], + probe: MetroDevServerProbe, +): Promise { + if (!isLoopbackUrl(serverUrl)) return true; + const probeServer = probe.probeServer ?? probeLocalMetroServer; + const running = await probeServer(serverUrl, STATUS_PROBE_TIMEOUT_MS).catch(() => undefined); + // The app named this address itself, so a server that answers and names no root stays what it + // reported. Only a root that names a different project refuses it. + if (!running) return false; + return running.projectRoot === undefined || matchesProjectRoot(running, projectRoots); } /** @@ -145,13 +173,22 @@ export function canDiscoverForDeviceKind(kind: MetroAppTarget['deviceKind']): bo * file from the device container without a device round-trip. A physical device, an Android app, or * an app that never stored an address reports nothing. */ -async function readAppReportedMetroServerUrl( +export async function readAppReportedMetroServerUrl( app: MetroAppTarget, host: HostEnvironment, ): Promise { if (app.platform !== 'ios' || app.deviceKind !== 'simulator' || !app.appId) return undefined; const home = host.env.HOME; if (!home) return undefined; + const settingsJson = await readSimulatorAppPreferences(app, home); + return settingsJson === undefined ? undefined : parseAppReportedServerUrl(settingsJson); +} + +/** The app's preferences plist as JSON, or undefined when the host cannot answer for it. */ +async function readSimulatorAppPreferences( + app: MetroAppTarget, + home: string, +): Promise { const plist = path.join( home, SIMULATOR_DEVICES_ROOT, @@ -165,21 +202,17 @@ async function readAppReportedMetroServerUrl( const result = await runCmd('plutil', ['-convert', 'json', '-o', '-', plist], { allowFailure: true, timeoutMs: HOST_READ_TIMEOUT_MS, - }); - if (result.exitCode !== 0) return undefined; - const settings = parseJsonObject(result.stdout); - const reported = asNonEmptyString(settings?.[IOS_JS_LOCATION_KEY]); - if (!reported) return undefined; - const scheme = settings?.[IOS_PACKAGER_SCHEME_KEY] === 'https' ? 'https' : 'http'; - return parseHostAndPort(reported, scheme); + }).catch(() => undefined); + if (!result || result.exitCode !== 0) return undefined; + return result.stdout; } /** * The local dev server that serves this project: a listening port whose `/status` answers - * `packager-status:running` and whose `X-React-Native-Project-Root` contains or is contained by one - * of the project roots (a monorepo server serves from the repo root). Ports come from what a local - * process actually listens on, each probe is short, and they run concurrently, so a miss costs one - * bounded sweep rather than a reload timeout. A project-root match always wins, and a server that + * `packager-status:running` and whose `X-React-Native-Project-Root` is one of the project roots or a + * parent or child of one (a monorepo server serves from the repo root). Ports come from what a local + * process actually listens on, each probe is short, and they run bounded in parallel, so a miss costs + * one bounded sweep rather than a reload timeout. A project-root match always wins, and a server that * names a different project never counts, so another project's Metro is not reloaded by accident. */ export async function discoverLocalMetroServer( @@ -192,56 +225,69 @@ export async function discoverLocalMetroServer( ): Promise { const ports = await input.listListeningPorts().catch(() => [] as number[]); const timeoutMs = input.probeTimeoutMs ?? STATUS_PROBE_TIMEOUT_MS; - const probes = ports - .slice(0, MAX_CONCURRENT_STATUS_PROBES) - .map((port) => input.probeServer(new URL(`http://127.0.0.1:${port}`), timeoutMs)); - const candidates = (await Promise.allSettled(probes)) - .filter( - (settled): settled is PromiseFulfilledResult => - settled.status === 'fulfilled', - ) - .map((settled) => settled.value) - .filter((candidate): candidate is LocalMetroServer => candidate !== undefined); - if (candidates.length === 0) return undefined; - + const servers = await probePorts(ports, input.probeServer, timeoutMs); const roots = candidateProjectRoots(input.projectRoots); - // Only a server that names one of these projects (or one of their parents or children, as a - // monorepo server reports the repo root) counts. A running server for another project, or one that - // reports no root at all, is not this session's dev server, and reloading it would act on the - // wrong app. - return candidates.find((candidate) => - candidate.projectRoot - ? roots.some((root) => projectRootsOverlap(root, normalizeRealPath(candidate.projectRoot!))) - : false, - ); + return servers.find((candidate) => matchesProjectRoot(candidate, roots)); } -async function probeIsRunningDevServer( - serverUrl: URL, - probe: MetroDevServerProbe, -): Promise { - const probeServer = probe.probeServer ?? probeLocalMetroServer; - const confirmed = await probeServer(serverUrl, STATUS_PROBE_TIMEOUT_MS).catch(() => undefined); - return confirmed !== undefined; +/** Probes every port, at most MAX_CONCURRENT_STATUS_PROBES at a time, keeping probe failures quiet. */ +async function probePorts( + ports: number[], + probeServer: (serverUrl: URL, timeoutMs: number) => Promise, + timeoutMs: number, +): Promise { + const servers: LocalMetroServer[] = []; + for (let start = 0; start < ports.length; start += MAX_CONCURRENT_STATUS_PROBES) { + const batch = ports + .slice(start, start + MAX_CONCURRENT_STATUS_PROBES) + .map((port) => probeServer(new URL(`http://127.0.0.1:${port}`), timeoutMs)); + for (const settled of await Promise.allSettled(batch)) { + if (settled.status === 'fulfilled' && settled.value) servers.push(settled.value); + } + } + return servers; +} + +function matchesProjectRoot(candidate: LocalMetroServer, projectRoots: string[]): boolean { + if (!candidate.projectRoot) return false; + const serverRoot = normalizeRealPath(candidate.projectRoot); + return projectRoots.some((root) => projectRootsOverlap(root, serverRoot)); +} + +function normalizeRealPath(input: string): string { + try { + return fs.realpathSync(input); + } catch { + return path.resolve(input); + } } -async function listLocalListeningPorts(): Promise { - const result = await runCmd('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-Fn'], { +/** + * The ports this host's processes listen on: what `lsof` reports, or, where `lsof` is not installed, + * what `netstat` reports. A host with neither tool yields no ports, and reload answers with the typed + * failure rather than a crash or a guess. + */ +export async function listLocalListeningPorts(): Promise { + const lsof = await runHostCommand('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-Fn']); + if (lsof !== undefined) { + const ports = parseLsofListeningPorts(lsof); + if (ports.length > 0) return ports; + } + const netstat = await runHostCommand('netstat', ['-an', '-p', 'tcp']); + return netstat === undefined ? [] : parseNetstatListeningPorts(netstat); +} + +/** A host command's stdout, or undefined when it is missing, fails, or times out. */ +async function runHostCommand(command: string, args: string[]): Promise { + const result = await runCmd(command, args, { allowFailure: true, timeoutMs: HOST_READ_TIMEOUT_MS, - }); - if (result.exitCode !== 0) return []; - const ports = new Set(); - for (const line of result.stdout.split('\n')) { - if (!line.startsWith('n')) continue; - const port = readPortFromSocketName(line.slice(1)); - if (port !== undefined) ports.add(port); - } - return [...ports].sort((left, right) => left - right); + }).catch(() => undefined); + return result && result.exitCode === 0 ? result.stdout : undefined; } /** One bounded `/status` read of a loopback address: running dev server, plus its project root. */ -async function probeLocalMetroServer( +export async function probeLocalMetroServer( serverUrl: URL, timeoutMs: number, ): Promise { @@ -251,8 +297,10 @@ async function probeLocalMetroServer( }); if (!response.ok) return undefined; const body = await response.text(); - if (!body.includes(METRO_STATUS_READY_TEXT)) return undefined; - const projectRoot = response.headers.get(METRO_PROJECT_ROOT_HEADER); + if (!isMetroStatusBody(body)) return undefined; + const projectRoot = parseMetroProjectRootHeader( + response.headers.get(METRO_PROJECT_ROOT_HEADER), + ); return { serverUrl, ...(projectRoot ? { projectRoot } : {}) }; } catch { return undefined; @@ -278,34 +326,15 @@ export function metroDevServerUnresolvedError(): AppError { ); } -function readPortFromSocketName(name: string): number | undefined { - const separator = name.lastIndexOf(':'); - if (separator <= 0) return undefined; - const port = Number.parseInt(name.slice(separator + 1), 10); - return Number.isInteger(port) && port > 0 && port <= 65_535 ? port : undefined; -} - function isLoopbackUrl(url: URL): boolean { return ['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0'].includes(url.hostname); } -function projectRootsOverlap(left: string, right: string): boolean { - return left === right || left.startsWith(`${right}/`) || right.startsWith(`${left}/`); -} - function candidateProjectRoots(projectRoots: string[]): string[] { const resolved = projectRoots.map((root) => normalizeRealPath(root)); return [...new Set(resolved)]; } -function normalizeRealPath(input: string): string { - try { - return fs.realpathSync(input); - } catch { - return path.resolve(input); - } -} - function fileExists(filePath: string): boolean { try { fs.accessSync(filePath, fs.constants.F_OK); @@ -314,31 +343,3 @@ function fileExists(filePath: string): boolean { return false; } } - -function parseJsonObject(text: string): Record | undefined { - try { - const parsed: unknown = JSON.parse(text); - return parsed && typeof parsed === 'object' && !Array.isArray(parsed) - ? (parsed as Record) - : undefined; - } catch { - return undefined; - } -} - -function asNonEmptyString(value: unknown): string | undefined { - return typeof value === 'string' && value.trim() ? value.trim() : undefined; -} - -function parseHostAndPort(value: string, scheme: 'http' | 'https'): URL | undefined { - const separator = value.lastIndexOf(':'); - if (separator <= 0) return undefined; - const host = value.slice(0, separator); - const port = Number.parseInt(value.slice(separator + 1), 10); - if (!host || !Number.isInteger(port) || port < 1 || port > 65_535) return undefined; - try { - return new URL(`${scheme}://${host}:${port}`); - } catch { - return undefined; - } -} diff --git a/packages/react-native/src/metro/metro-dev-server-host-io.test.ts b/packages/react-native/src/metro/metro-dev-server-host-io.test.ts new file mode 100644 index 0000000000..8bf43fab97 --- /dev/null +++ b/packages/react-native/src/metro/metro-dev-server-host-io.test.ts @@ -0,0 +1,247 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import type { Server } from 'node:http'; +import { createServer } from 'node:http'; +import path from 'node:path'; +import { withCommandExecutorOverride } from '@agent-device/host-kit/command'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { + listLocalListeningPorts, + probeLocalMetroServer, + readAppReportedMetroServerUrl, + type MetroAppTarget, +} from './metro-dev-server-discovery.ts'; +import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; + +const simulatorApp: MetroAppTarget = { + platform: 'ios', + deviceKind: 'simulator', + deviceId: 'UDID-1', + appId: 'com.example.app', + hostedLocally: true, +}; + +function hostWithHome(home: string): HostEnvironment { + return { env: { HOME: home }, cwd: home }; +} + +/** A simulator container holding this app's preferences file, as `open` leaves it. */ +function simulatorHomeWithPreferences(udid: string, appId: string): string { + const home = mkdtempForTestSync('agent-device-metro-plist-'); + const preferences = path.join( + home, + 'Library/Developer/CoreSimulator/Devices', + udid, + 'data/Library/Preferences', + ); + mkdirSync(preferences, { recursive: true }); + writeFileSync(path.join(preferences, `${appId}.plist`), 'binary plist', 'utf8'); + return home; +} + +test('the app-reported address is read from the preferences the simulator host converts', async () => { + const home = simulatorHomeWithPreferences('UDID-1', 'com.example.app'); + try { + let convertedPath = ''; + const reported = await withCommandExecutorOverride( + (command, args) => { + assert.equal(command, 'plutil'); + assert.deepEqual(args.slice(0, 4), ['-convert', 'json', '-o', '-']); + convertedPath = args[4] ?? ''; + return Promise.resolve({ + stdout: '{"RCT_jsLocation":"127.0.0.1:8096"}', + stderr: '', + exitCode: 0, + }); + }, + async () => await readAppReportedMetroServerUrl(simulatorApp, hostWithHome(home)), + ); + assert.equal(reported?.toString(), 'http://127.0.0.1:8096/'); + assert.equal(convertedPath.endsWith(path.join('com.example.app.plist')), true); + } finally { + rmSync(home, { recursive: true, force: true }); + } +}); + +test('an app reports nothing when its preferences, HOME, or the converter is unavailable', async () => { + const home = simulatorHomeWithPreferences('UDID-1', 'com.example.app'); + try { + // Another app's container has no preferences file for this app. + assert.equal( + await readAppReportedMetroServerUrl( + { ...simulatorApp, appId: 'com.other.app' }, + hostWithHome(home), + ), + undefined, + ); + + // No HOME means no simulator tree to read, and nothing is even spawned. + const spawnedWithoutHome: string[] = []; + assert.equal( + await withCommandExecutorOverride( + (command) => { + spawnedWithoutHome.push(command); + return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }); + }, + async () => await readAppReportedMetroServerUrl(simulatorApp, { env: {}, cwd: home }), + ), + undefined, + ); + assert.deepEqual(spawnedWithoutHome, []); + + // `plutil` refusing to convert is a host that cannot answer for the app. + assert.equal( + await withCommandExecutorOverride( + () => Promise.resolve({ stdout: '', stderr: 'plutil: conversion failed', exitCode: 1 }), + async () => await readAppReportedMetroServerUrl(simulatorApp, hostWithHome(home)), + ), + undefined, + ); + + // A host without `plutil` at all: the spawn itself fails, and reload must not crash on it. + assert.equal( + await withCommandExecutorOverride( + () => Promise.reject(new Error('plutil ENOENT')), + async () => await readAppReportedMetroServerUrl(simulatorApp, hostWithHome(home)), + ), + undefined, + ); + + // Anything that is not an iOS simulator app has no stored address to read. + for (const app of [ + { ...simulatorApp, platform: 'android' as const }, + { ...simulatorApp, deviceKind: 'device' as const }, + { ...simulatorApp, deviceKind: undefined }, + { ...simulatorApp, appId: undefined }, + ]) { + assert.equal(await readAppReportedMetroServerUrl(app, hostWithHome(home)), undefined); + } + } finally { + rmSync(home, { recursive: true, force: true }); + } +}); + +test('ports come from lsof when it is installed', async () => { + const spawned: string[] = []; + const ports = await withCommandExecutorOverride( + (command) => { + spawned.push(command); + return Promise.resolve({ + stdout: command === 'lsof' ? 'p1\nn127.0.0.1:8081\nn*:8096\n' : '', + stderr: '', + exitCode: 0, + }); + }, + async () => await listLocalListeningPorts(), + ); + assert.deepEqual(ports, [8081, 8096]); + // netstat is only asked where lsof could not answer. + assert.deepEqual(spawned, ['lsof']); +}); + +test('ports fall back to netstat on a host without lsof', async () => { + const spawned: string[] = []; + const ports = await withCommandExecutorOverride( + (command) => { + spawned.push(command); + if (command === 'lsof') return Promise.reject(new Error('lsof ENOENT')); + return Promise.resolve({ + stdout: 'tcp4 0 0 127.0.0.1.8081 *.* LISTEN\ntcp4 0 0 127.0.0.1.9999 *.* ESTABLISHED\n', + stderr: '', + exitCode: 0, + }); + }, + async () => await listLocalListeningPorts(), + ); + assert.deepEqual(ports, [8081]); + assert.deepEqual(spawned, ['lsof', 'netstat']); +}); + +test('a host with neither lsof nor netstat reports no ports instead of failing', async () => { + const ports = await withCommandExecutorOverride( + (command) => Promise.reject(new Error(`${command} ENOENT`)), + async () => await listLocalListeningPorts(), + ); + assert.deepEqual(ports, []); +}); + +test('a tool that answers with an empty success still lets the other tool answer', async () => { + const ports = await withCommandExecutorOverride( + (command) => + command === 'lsof' + ? Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }) + : Promise.resolve({ + stdout: 'tcp4 0 0 127.0.0.1:8081 0.0.0.0:* LISTEN', + stderr: '', + exitCode: 0, + }), + async () => await listLocalListeningPorts(), + ); + assert.deepEqual(ports, [8081]); +}); + +test('a /status that says the packager is running reports the server and its project root', async () => { + const server = answerStatusServer({ + body: 'packager-status:running', + projectRoot: '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/app/project', + }); + const port = await listenOnLoopback(server); + try { + const running = await probeLocalMetroServer(new URL(`http://127.0.0.1:${port}`), 2_000); + assert.equal(running?.serverUrl.port, String(port)); + assert.equal(running?.projectRoot, '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/app/project'); + } finally { + await closeLoopbackServer(server); + } +}); + +test('a server without a project-root header is reported without one', async () => { + const server = answerStatusServer({ body: 'packager-status:running' }); + const port = await listenOnLoopback(server); + try { + const running = await probeLocalMetroServer(new URL(`http://127.0.0.1:${port}`), 2_000); + assert.equal(running?.projectRoot, undefined); + } finally { + await closeLoopbackServer(server); + } +}); + +test('a /status that is not Metro, or is not there at all, reports no server', async () => { + const notMetro = answerStatusServer({ body: '

Nothing here

' }); + const notMetroPort = await listenOnLoopback(notMetro); + const unavailable = answerStatusServer({ + body: 'packager-status:running', + statusCode: 503, + }); + const unavailablePort = await listenOnLoopback(unavailable); + try { + assert.equal( + await probeLocalMetroServer(new URL(`http://127.0.0.1:${notMetroPort}`), 2_000), + undefined, + ); + assert.equal( + await probeLocalMetroServer(new URL(`http://127.0.0.1:${unavailablePort}`), 2_000), + undefined, + ); + // A port nothing listens on: a connection error, not a crash. + assert.equal(await probeLocalMetroServer(new URL('http://127.0.0.1:1'), 500), undefined); + } finally { + await closeLoopbackServer(notMetro); + await closeLoopbackServer(unavailable); + } +}); + +function answerStatusServer(answer: { + body: string; + projectRoot?: string; + statusCode?: number; +}): Server { + return createServer((_req, res) => { + if (answer.projectRoot) { + res.setHeader('x-react-native-project-root', answer.projectRoot); + } + res.statusCode = answer.statusCode ?? 200; + res.end(answer.body); + }); +} diff --git a/packages/react-native/src/metro/metro-dev-server-parsing.test.ts b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts new file mode 100644 index 0000000000..a0cac676ae --- /dev/null +++ b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts @@ -0,0 +1,135 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { + isMetroStatusBody, + parseAppReportedServerUrl, + parseLsofListeningPorts, + parseMetroProjectRootHeader, + parseNetstatListeningPorts, + parsePortFromSocketName, + projectRootsOverlap, +} from './metro-dev-server-parsing.ts'; + +test('a /status body counts as a running dev server only when it names the packager', () => { + assert.equal(isMetroStatusBody('packager-status:running'), true); + assert.equal(isMetroStatusBody('packager-status:running'), true); + assert.equal(isMetroStatusBody('packager-status:not-running'), false); + assert.equal(isMetroStatusBody('

Not Found

'), false); +}); + +test('the project-root header is kept plain, percent-decoded, or dropped when empty', () => { + assert.equal(parseMetroProjectRootHeader('/home/dev/app'), '/home/dev/app'); + assert.equal(parseMetroProjectRootHeader(' /home/dev/app '), '/home/dev/app'); + assert.equal( + parseMetroProjectRootHeader('C%3A%5CUsers%5Cdev%5Cproyecto%20n%E2%80%99%C3%AD'), + 'C:\\Users\\dev\\proyecto n’í', + ); + assert.equal(parseMetroProjectRootHeader('/app/%E2%80%'), '/app/%E2%80%'); + assert.equal(parseMetroProjectRootHeader(''), undefined); + assert.equal(parseMetroProjectRootHeader(' '), undefined); + assert.equal(parseMetroProjectRootHeader(null), undefined); +}); + +test('lsof field output yields each listening port once, ascending', () => { + assert.deepEqual( + parseLsofListeningPorts('p956\nf9\nn*:7000\nn127.0.0.1:8081\np12\nn[::1]:8081\n'), + [7000, 8081], + ); +}); + +test('lsof lines that name no socket or no numeric port are skipped', () => { + assert.deepEqual(parseLsofListeningPorts('p956\nf9\ncTCP\n'), []); + assert.deepEqual(parseLsofListeningPorts('nlocalhost:http-alt\nn:8081\nn127.0.0.1:0\n'), []); +}); + +test('netstat output yields only tcp rows in LISTEN state, deduplicated and ascending', () => { + assert.deepEqual( + parseNetstatListeningPorts( + [ + 'tcp4 0 0 127.0.0.1.8081 *.* LISTEN', + 'tcp4 0 0 127.0.0.1.8081 127.0.0.1.55121 ESTABLISHED', + 'tcp6 0 0 ::1.8096 *.* LISTEN', + 'tcp4 0 0 127.0.0.1.8081 *.* LISTEN', + 'udp4 0 0 127.0.0.1.5353 *.*', + ].join('\n'), + ), + [8081, 8096], + ); +}); + +test('both netstat address spellings name their port, and a wildcard still names none', () => { + // Linux prints `127.0.0.1:8081`; macOS prints `127.0.0.1.8081`. + assert.deepEqual(parseNetstatListeningPorts('tcp4 0 0 127.0.0.1:8081 0.0.0.0:* LISTEN'), [8081]); + assert.deepEqual(parseNetstatListeningPorts('tcp4 0 0 *.8081 *.* LISTEN'), [8081]); + assert.deepEqual(parseNetstatListeningPorts('tcp4 0 0 *.*.* LISTEN'), []); +}); + +test('the port a socket name ends with is read only when it is a real port', () => { + assert.equal(parsePortFromSocketName('127.0.0.1:8081'), 8081); + assert.equal(parsePortFromSocketName('[::1]:8096'), 8096); + assert.equal(parsePortFromSocketName('127.0.0.1:8081junk'), undefined); + assert.equal(parsePortFromSocketName('127.0.0.1:70000'), undefined); + assert.equal(parsePortFromSocketName('127.0.0.1:0'), undefined); + assert.equal(parsePortFromSocketName('8081'), undefined); + assert.equal(parsePortFromSocketName(':8081'), undefined); +}); + +test('the app-reported server URL is what RCT_jsLocation names, with the stored scheme', () => { + assert.equal( + parseAppReportedServerUrl('{"RCT_jsLocation":"127.0.0.1:8096"}')?.toString(), + 'http://127.0.0.1:8096/', + ); + assert.equal( + parseAppReportedServerUrl( + '{"RCT_jsLocation":"10.0.0.5:19000","RCT_packager_scheme":"https"}', + )?.toString(), + 'https://10.0.0.5:19000/', + ); +}); + +test('the app-reported server URL is refused for unusable settings', () => { + for (const json of [ + 'not json', + '[]', + '"a string"', + '{}', + '{"RCT_jsLocation":""}', + '{"RCT_jsLocation":" "}', + '{"RCT_jsLocation":8096}', + '{"RCT_jsLocation":"127.0.0.1"}', + '{"RCT_jsLocation":"127.0.0.1:8081junk"}', + '{"RCT_jsLocation":":8081"}', + '{"RCT_jsLocation":"127.0.0.1:70000"}', + ]) { + assert.equal(parseAppReportedServerUrl(json), undefined, json); + } +}); + +test('a stored https scheme that is not exactly "https" still reads as http', () => { + assert.equal( + parseAppReportedServerUrl('{"RCT_jsLocation":"127.0.0.1:8081","RCT_packager_scheme":"HTTPS"}') + ?.protocol, + 'http:', + ); +}); + +test('project roots overlap when one is the other, a parent, or a child', () => { + assert.equal(projectRootsOverlap('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/app/project', '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/app/project'), true); + assert.equal(projectRootsOverlap('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/app/project', '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/app/project/packages/mobile'), true); + assert.equal(projectRootsOverlap('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/app/project/packages/mobile', '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/app/project'), true); +}); + +test('a shared path prefix is not a shared project root', () => { + assert.equal(projectRootsOverlap('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/app/project', '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/app/project-two'), false); + assert.equal(projectRootsOverlap('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/app/project', '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/other/project'), false); + assert.equal(projectRootsOverlap('/app', '/opt/app'), false); +}); + +test('project-root overlap compares path segments, not characters', () => { + // The check is expressed with path.relative, so it follows the platform's own separator. + const root = path.join('a', 'b'); + const sibling = path.join('a', 'bc'); + assert.equal(projectRootsOverlap(root, sibling), false); + assert.equal(projectRootsOverlap(root, path.join(root, 'c')), true); +}); diff --git a/packages/react-native/src/metro/metro-dev-server-parsing.ts b/packages/react-native/src/metro/metro-dev-server-parsing.ts new file mode 100644 index 0000000000..88ea586494 --- /dev/null +++ b/packages/react-native/src/metro/metro-dev-server-parsing.ts @@ -0,0 +1,150 @@ +import path from 'node:path'; + +/** + * The pure reads behind dev-server discovery: what a host's command output, an app's stored + * settings, or a `/status` response says. Each function takes text and answers one question, so the + * decision branches are testable without a process, a file, or a socket. + */ + +const IOS_JS_LOCATION_KEY = 'RCT_jsLocation'; +const IOS_PACKAGER_SCHEME_KEY = 'RCT_packager_scheme'; +const MAX_PORT = 65_535; +const NETSTAT_LISTEN_STATE = 'LISTEN'; + +/** The body a running React Native dev server answers on `/status`. */ +export const METRO_STATUS_READY_TEXT = 'packager-status:running'; + +export function isMetroStatusBody(text: string): boolean { + return text.includes(METRO_STATUS_READY_TEXT); +} + +/** + * The project root a dev server reports in `X-React-Native-Project-Root`. Expo percent-encodes the + * value and the React Native CLI does not, so an encoded value is decoded and a malformed one kept. + */ +export function parseMetroProjectRootHeader(value: string | null): string | undefined { + const trimmed = value?.trim(); + if (!trimmed) return undefined; + if (!trimmed.includes('%')) return trimmed; + try { + return decodeURIComponent(trimmed) || undefined; + } catch { + return trimmed; + } +} + +/** + * The listening ports `lsof -nP -iTCP -sTCP:LISTEN -Fn` reports, deduplicated and ascending. A line + * that names no socket, or a name whose port is not a plain number, is not a listening TCP socket. + */ +export function parseLsofListeningPorts(stdout: string): number[] { + const ports = new Set(); + for (const line of stdout.split('\n')) { + if (!line.startsWith('n')) continue; + const port = parsePortFromSocketName(line.slice(1)); + if (port !== undefined) ports.add(port); + } + return [...ports].sort((left, right) => left - right); +} + +/** + * The listening ports `netstat -an -p tcp` reports, deduplicated and ascending. Linux and macOS + * number the same columns: local address fourth, state sixth. Their address formats differ — Linux + * writes `127.0.0.1:8081`, macOS `127.0.0.1.8081` — so either trailing separator names the port. + */ +export function parseNetstatListeningPorts(stdout: string): number[] { + const ports = new Set(); + for (const line of stdout.split('\n')) { + const columns = line.trim().split(/\s+/); + if (!columns[0]?.startsWith('tcp')) continue; + if (columns[5] !== NETSTAT_LISTEN_STATE) continue; + const port = parsePortFromNetstatAddress(columns[3] ?? ''); + if (port !== undefined) ports.add(port); + } + return [...ports].sort((left, right) => left - right); +} + +/** The port a socket name such as `127.0.0.1:8081` ends with. */ +export function parsePortFromSocketName(name: string): number | undefined { + const separator = name.lastIndexOf(':'); + if (separator <= 0) return undefined; + return parsePortToken(name.slice(separator + 1)); +} + +/** + * The port a `netstat` local address ends with, after either separator the two platforms use. A + * wildcard address such as `*.*` names no port. + */ +export function parsePortFromNetstatAddress(address: string): number | undefined { + const withoutBrackets = address.replace(/\]$/, ''); + const separator = Math.max(withoutBrackets.lastIndexOf(':'), withoutBrackets.lastIndexOf('.')); + if (separator <= 0) return undefined; + return parsePortToken(withoutBrackets.slice(separator + 1)); +} + +/** + * The dev server an iOS app stored in its own preferences: `RCT_jsLocation` as `host:port`, with + * `RCT_packager_scheme` selecting `https` when it says so. Anything else — no settings, no key, an + * empty key, a non-string value, or a host:port whose port is not a plain number — is no server. + */ +export function parseAppReportedServerUrl(settingsJson: string): URL | undefined { + const settings = parseJsonObject(settingsJson); + if (!settings) return undefined; + const reported = asNonEmptyString(settings[IOS_JS_LOCATION_KEY]); + if (!reported) return undefined; + const scheme = settings[IOS_PACKAGER_SCHEME_KEY] === 'https' ? 'https' : 'http'; + return parseHostAndPort(reported, scheme); +} + +/** + * A `host:port` address, as React Native stores it. The port token must be plain digits: + * `127.0.0.1:8081junk` is a broken value, not a hint to reload port 8081. + */ +export function parseHostAndPort(value: string, scheme: 'http' | 'https'): URL | undefined { + const separator = value.lastIndexOf(':'); + if (separator <= 0) return undefined; + const host = value.slice(0, separator); + const port = parsePortToken(value.slice(separator + 1)); + if (!host || port === undefined) return undefined; + try { + return new URL(`${scheme}://${host}:${port}`); + } catch { + return undefined; + } +} + +/** Whether two project roots name the same directory, or one holds the other. */ +export function projectRootsOverlap(left: string, right: string): boolean { + return isSameOrInsidePath(left, right) || isSameOrInsidePath(right, left); +} + +function isSameOrInsidePath(root: string, candidate: string): boolean { + const relative = path.relative(root, candidate); + return ( + relative === '' || + (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) + ); +} + +/** A port token that is plain digits and names a real port. */ +function parsePortToken(token: string): number | undefined { + const trimmed = token.trim(); + if (!/^\d+$/.test(trimmed)) return undefined; + const port = Number(trimmed); + return port >= 1 && port <= MAX_PORT ? port : undefined; +} + +export function parseJsonObject(text: string): Record | undefined { + try { + const parsed: unknown = JSON.parse(text); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) + ? (parsed as Record) + : undefined; + } catch { + return undefined; + } +} + +function asNonEmptyString(value: unknown): string | undefined { + return typeof value === 'string' && value.trim() ? value.trim() : undefined; +} diff --git a/packages/react-native/src/metro/metro-reload-endpoints.test.ts b/packages/react-native/src/metro/metro-reload-endpoints.test.ts index a4958bc8ea..d70bf3b624 100644 --- a/packages/react-native/src/metro/metro-reload-endpoints.test.ts +++ b/packages/react-native/src/metro/metro-reload-endpoints.test.ts @@ -1,6 +1,10 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; -import { parsePort, resolveMetroReloadEndpoints } from './metro-reload-endpoints.ts'; +import { + isMetroTargetBound, + parsePort, + resolveMetroReloadEndpoints, +} from './metro-reload-endpoints.ts'; test('a Metro port is a whole number from 1 to 65535', () => { assert.equal(parsePort('8082', 8081), 8082); @@ -10,6 +14,26 @@ test('a Metro port is a whole number from 1 to 65535', () => { } }); +test('nothing named counts as no binding, a blank value included', () => { + assert.equal(isMetroTargetBound({}), false); + assert.equal(isMetroTargetBound({ runtime: {} }), false); + // `parsePort` reads an empty port as absent, and so does this: an empty flag must reach discovery + // rather than resolving to the default address. + assert.equal(isMetroTargetBound({ metroPort: '' }), false); + assert.equal(isMetroTargetBound({ metroPort: ' ' }), false); + assert.equal(isMetroTargetBound({ metroHost: ' ' }), false); + assert.equal(isMetroTargetBound({ bundleUrl: '' }), false); +}); + +test('any one named address is a binding, from a flag or from the session', () => { + assert.equal(isMetroTargetBound({ metroPort: 8082 }), true); + assert.equal(isMetroTargetBound({ metroPort: '8082' }), true); + assert.equal(isMetroTargetBound({ metroHost: '10.0.0.5' }), true); + assert.equal(isMetroTargetBound({ bundleUrl: 'http://10.0.0.5:8082/index.bundle' }), true); + assert.equal(isMetroTargetBound({ runtime: { metroPort: 8082 } }), true); + assert.equal(isMetroTargetBound({ runtime: { bundleUrl: 'http://10.0.0.5:8082' } }), true); +}); + test('reload endpoint resolution prioritizes explicit flags, then session runtime hints, then defaults', () => { // no-hint default: neither an explicit flag nor a runtime hint is present. assert.equal(resolveMetroReloadEndpoints({}).reloadUrl, 'http://localhost:8081/reload'); diff --git a/packages/react-native/src/metro/metro-reload-endpoints.ts b/packages/react-native/src/metro/metro-reload-endpoints.ts index 59fa3fe0aa..ef81a8ca1f 100644 --- a/packages/react-native/src/metro/metro-reload-endpoints.ts +++ b/packages/react-native/src/metro/metro-reload-endpoints.ts @@ -39,15 +39,22 @@ export function parsePort(value: number | string | undefined, fallback: number): * rather than a default address. */ export function isMetroTargetBound(input: MetroReloadTargetInput): boolean { - const explicit = - trimRuntimeValue(input.bundleUrl) !== undefined || - trimRuntimeValue(input.metroHost) !== undefined || - input.metroPort !== undefined; - const session = + return ( + namesDevServer(input) || trimRuntimeValue(input.runtime?.bundleUrl) !== undefined || trimRuntimeValue(input.runtime?.metroHost) !== undefined || - input.runtime?.metroPort !== undefined; - return explicit || session; + input.runtime?.metroPort !== undefined + ); +} + +function namesDevServer(input: MetroReloadTargetInput): boolean { + // `parsePort` treats an empty or blank port as absent, and so does this: a caller that sent + // nothing must reach discovery rather than resolve to the default address. + return ( + trimRuntimeValue(input.bundleUrl) !== undefined || + trimRuntimeValue(input.metroHost) !== undefined || + (input.metroPort !== undefined && trimRuntimeValue(String(input.metroPort)) !== undefined) + ); } // Explicit flags win over session runtime hints, which win over localhost:8081. diff --git a/packages/react-native/src/metro/metro-session-hints.test.ts b/packages/react-native/src/metro/metro-session-hints.test.ts index 2b14e6b8a7..5a7376f405 100644 --- a/packages/react-native/src/metro/metro-session-hints.test.ts +++ b/packages/react-native/src/metro/metro-session-hints.test.ts @@ -4,9 +4,13 @@ import { randomUUID } from 'node:crypto'; import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; import path from 'node:path'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { clearMetroSessionHints, + readMetroSessionAppTarget, readMetroSessionHints, + recordOpenedMetroSession, + recordPreparedMetroSession, writeMetroSessionHints, } from './metro-session-hints.ts'; import { mkdtempForTestSync } from '@agent-device/test-kit'; @@ -136,3 +140,171 @@ test('released session records retain their reload address when read as a bindin controlBaseUrl: 'https://metro.example.test/tenant-42', }); }); + +const iosApp = { + platform: 'ios', + deviceKind: 'simulator', + deviceId: 'UDID-1', + appId: 'com.example.app', + hostedLocally: true, +} as const; + +function hostFor(stateDir: string): HostEnvironment { + return { env: { AGENT_DEVICE_STATE_DIR: stateDir }, cwd: stateDir }; +} + +test('an open with no dev-server hint records the app a later reload looks up', () => { + const stateDir = tempStateDir(); + try { + recordOpenedMetroSession( + { stateDir, session: 'fresh', host: hostFor(stateDir) }, + { runtime: undefined, explicitRuntime: false, sessionReused: false, app: iosApp }, + ); + + assert.deepEqual( + readMetroSessionAppTarget({ stateDir, session: 'fresh', host: hostFor(stateDir) }), + iosApp, + ); + // An app-only record binds no address, so it is never read as a binding. + assert.equal(readMetroSessionHints({ stateDir, session: 'fresh' }), undefined); + } finally { + rmSync(stateDir, { recursive: true, force: true }); + } +}); + +test('a reused session that opens another app replaces the recorded app', () => { + const stateDir = tempStateDir(); + try { + const options = { stateDir, session: 'reused', host: hostFor(stateDir) }; + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: false, + app: iosApp, + }); + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: true, + app: { ...iosApp, appId: 'com.other.app', deviceId: 'UDID-2' }, + }); + + assert.deepEqual(readMetroSessionAppTarget({ ...options }), { + ...iosApp, + appId: 'com.other.app', + deviceId: 'UDID-2', + }); + } finally { + rmSync(stateDir, { recursive: true, force: true }); + } +}); + +test('re-recording the app keeps a binding the session already had', () => { + const stateDir = tempStateDir(); + try { + const options = { stateDir, session: 'bound', host: hostFor(stateDir) }; + recordPreparedMetroSession(options, { + statusUrl: 'http://127.0.0.1:8096/status', + iosRuntime: { metroHost: '127.0.0.1', metroPort: 8096 }, + androidRuntime: { metroHost: '127.0.0.1', metroPort: 8096, platform: 'android' }, + }); + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: true, + app: iosApp, + }); + + assert.deepEqual(readMetroSessionHints({ stateDir, session: 'bound' }), { + controlBaseUrl: 'http://127.0.0.1:8096/', + deviceBaseUrls: ['http://127.0.0.1:8096/'], + app: iosApp, + }); + } finally { + rmSync(stateDir, { recursive: true, force: true }); + } +}); + +test('an open that reports no app leaves a reused session record alone and clears a fresh one', () => { + const stateDir = tempStateDir(); + try { + const options = { stateDir, session: 'keep', host: hostFor(stateDir) }; + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: false, + app: iosApp, + }); + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: true, + }); + assert.deepEqual(readMetroSessionAppTarget({ ...options }), iosApp); + + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: false, + }); + assert.equal(readMetroSessionAppTarget({ ...options }), undefined); + } finally { + rmSync(stateDir, { recursive: true, force: true }); + } +}); + +test('the recorded app is read back only when its record names a real app on a device', () => { + const stateDir = tempStateDir(); + const options = { stateDir, session: 'stored', host: hostFor(stateDir) }; + const file = path.join(stateDir, 'metro-sessions', 'stored.json'); + const write = (app: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify({ app })); + }; + try { + write(iosApp); + assert.deepEqual(readMetroSessionAppTarget({ ...options }), iosApp); + + // A record from before the host trait, or one that says the device is elsewhere, is not local. + write({ ...iosApp, hostedLocally: false }); + assert.deepEqual(readMetroSessionAppTarget({ ...options }), { + platform: 'ios', + deviceKind: 'simulator', + deviceId: 'UDID-1', + appId: 'com.example.app', + }); + + // A device kind the reader does not know stays absent: discovery decides on its own. + write({ platform: 'android', deviceId: 'emulator-5554', deviceKind: 'phone' }); + assert.deepEqual(readMetroSessionAppTarget({ ...options }), { + platform: 'android', + deviceId: 'emulator-5554', + }); + + for (const app of [ + undefined, + null, + 'string', + [], + {}, + { platform: 'web', deviceId: 'x' }, + { platform: 'ios' }, + { deviceId: 'UDID-1' }, + ]) { + write(app); + assert.equal(readMetroSessionAppTarget({ ...options }), undefined, JSON.stringify(app)); + } + } finally { + rmSync(stateDir, { recursive: true, force: true }); + } +}); + +test('an unusable state directory yields no recorded app instead of throwing', () => { + assert.equal( + readMetroSessionAppTarget({ + session: 's', + host: { env: { AGENT_DEVICE_STATE_DIR: '../escape' }, cwd: '/tmp' }, + }), + undefined, + ); +}); diff --git a/packages/react-native/src/metro/metro-session-hints.ts b/packages/react-native/src/metro/metro-session-hints.ts index 649c7c6558..85dbe5fce6 100644 --- a/packages/react-native/src/metro/metro-session-hints.ts +++ b/packages/react-native/src/metro/metro-session-hints.ts @@ -105,6 +105,9 @@ function readStoredAppTarget(value: unknown): MetroAppTarget | undefined { deviceId, ...(deviceKind ? { deviceKind } : {}), ...(typeof record.appId === 'string' ? { appId: record.appId } : {}), + // Only an explicit `true` says the device is hosted here; a record from before this field, or a + // provider device, reads as not proven local. + ...(record.hostedLocally === true ? { hostedLocally: true } : {}), }; } @@ -252,13 +255,23 @@ export function recordOpenedMetroSession( }); return; } - // No dev-server hint came with the open, so no address is bound. A fresh session still records - // the app it opened: that is what a later reload looks the app's own address up from. A reused - // session keeps whatever its first open recorded. - if (!input.sessionReused) { - if (input.app) writeMetroSessionHints({ ...scope, hints: { app: input.app } }); - else clearMetroSessionHints(scope); + // No dev-server hint came with the open, so no address is bound. What is recorded is the app this + // open launched: a later reload looks that app's own address up from it. A reused session can + // open a different app, so a recorded app always replaces the previous one; an open that reports + // no app keeps what a reused session already had, and clears a stale record on a fresh session. + if (input.app) { + const binding = readMetroSessionHints(scope); + writeMetroSessionHints({ + ...scope, + hints: { + ...(binding?.controlBaseUrl ? { controlBaseUrl: binding.controlBaseUrl } : {}), + ...(binding?.deviceBaseUrls ? { deviceBaseUrls: binding.deviceBaseUrls } : {}), + app: input.app, + }, + }); + return; } + if (!input.sessionReused) clearMetroSessionHints(scope); } catch {} } diff --git a/packages/test-kit/src/metro-session.fixtures.ts b/packages/test-kit/src/metro-session.fixtures.ts index edc7b62514..91d3212a67 100644 --- a/packages/test-kit/src/metro-session.fixtures.ts +++ b/packages/test-kit/src/metro-session.fixtures.ts @@ -9,7 +9,19 @@ function bindingPath(scope: MetroSessionFixture): string { } export function writeMetroSessionFixture( - options: MetroSessionFixture & { hints: { controlBaseUrl: string; deviceBaseUrls?: string[] } }, + options: MetroSessionFixture & { + hints: { + controlBaseUrl?: string; + deviceBaseUrls?: string[]; + app?: { + platform: 'ios' | 'android'; + deviceKind?: 'simulator' | 'emulator' | 'device'; + deviceId: string; + appId?: string; + hostedLocally?: boolean; + }; + }; + }, ): void { const file = bindingPath(options); fs.mkdirSync(path.dirname(file), { recursive: true }); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 6714402b5b..981f1fd7cf 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2179,7 +2179,7 @@ agent-device metro reload --bundle-url "http://localhost:8081/index.bundle?platf ``` - `metro reload` asks connected React Native dev builds to reload JavaScript without restarting the native process, like pressing `r` in the Metro terminal. -- Without flags, it reloads the dev server the session bound through `metro prepare` or `open`'s Metro hints. When no session bound one and the app runs on a local simulator or emulator, it next uses the dev-server address the app itself stored, then a local dev server that serves this directory. Otherwise it fails with `details.reason: 'metro_dev_server_unresolved'` instead of calling `localhost:8081`, which belongs to whichever project owns that port. A reused session name never reloads a previous project's server. +- Without flags, it reloads the dev server the session bound through `metro prepare` or `open`'s Metro hints. When a recorded app on a local simulator or emulator has no bound server, it next uses that app's own reported address (iOS simulators only) when a dev server there serves this project, then a local dev server whose reported project root is this directory or a parent or child of it. If neither local lookup resolves, it fails with `details.reason: 'metro_dev_server_unresolved'`; physical, provider-hosted, and app-less sessions retain their existing address behavior, the `localhost:8081` default included. A reused session name never reloads a previous project's server. - Use `open --relaunch` instead when the app is not connected to Metro, the reload fails, or the native process must restart. See `agent-device help metro` for the binding rules. ## Media and logs From 07a0b609d23f012e28aacf9aa9027f8b09a31fd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 11:42:24 +0100 Subject: [PATCH 03/10] fix(metro): gate local discovery on the daemon's own device and widen host reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Records where a session's device runs when open resolves it, instead of second-guessing the device kind: the trait is true when the daemon answering is local and it named the device from its own inventory, false for a provider device, and left out when the answer says nothing, so a later open keeps what an earlier one proved for the same device. A physical device on this machine is now in scope and a provider device on a simulator is not, which is what the host actually is. Shares one loopback test with the daemon's own and drops the half-baked URL check that read 127.1.2.3 as remote. A live Mac answers lsof in over 1.5s with simulators running — measured, not guessed — so the port listing went empty on a real reload. The host-read budget now covers the slow machine, because a timeout there is indistinguishable from "this machine listens on nothing". Co-authored-by: Apex --- packages/client/src/index.ts | 17 ++++++---- packages/command-surface/src/metro/index.ts | 2 +- .../metro/metro-dev-server-discovery.test.ts | 8 ++--- .../src/metro/metro-dev-server-discovery.ts | 27 +++++++-------- .../src/metro/metro-session-hints.ts | 34 ++++++++++++++----- website/docs/docs/commands.md | 2 +- 6 files changed, 54 insertions(+), 36 deletions(-) diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 026e012747..29a66ed503 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -599,16 +599,19 @@ function daemonIsLocal(config: AgentDeviceClientConfig, host: HostEnvironment): /** * Whether `open` proved the session's device runs on this machine: the daemon answers here, and it - * resolved the device from this host's own inventory. A provider device, a device inherited from an - * earlier request, or a daemon on another machine leaves it unproven, and reload then skips the local - * lookups instead of reading unrelated state. + * resolved the device from its own local inventory. A provider device, a device carried over from an + * earlier request, or a daemon on another machine leaves it unproven — `undefined`, not `false` — and + * the record keeps whatever an earlier open proved for the same device. */ function appHostedLocally( config: AgentDeviceClientConfig, host: HostEnvironment, selection: DeviceSelectionMetadata | undefined, -): boolean { - return daemonIsLocal(config, host) && selection?.source === 'local'; +): boolean | undefined { + if (!daemonIsLocal(config, host)) return false; + if (selection?.source === 'local') return true; + if (selection?.source === 'provider') return false; + return undefined; } /** @@ -619,7 +622,7 @@ function appHostedLocally( function metroAppTargetFromOpen( device: ReturnType, appBundleId: string | undefined, - hostedLocally: boolean, + hostedLocally: boolean | undefined, ): MetroAppTarget | undefined { if (!device || !appBundleId) return undefined; if (device.platform !== 'ios' && device.platform !== 'android') return undefined; @@ -628,7 +631,7 @@ function metroAppTargetFromOpen( deviceId: device.id, ...(device.kind ? { deviceKind: device.kind } : {}), appId: appBundleId, - ...(hostedLocally ? { hostedLocally: true } : {}), + ...(hostedLocally === undefined ? {} : { hostedLocally }), }; } diff --git a/packages/command-surface/src/metro/index.ts b/packages/command-surface/src/metro/index.ts index ef756f4d09..a9487539b6 100644 --- a/packages/command-surface/src/metro/index.ts +++ b/packages/command-surface/src/metro/index.ts @@ -138,7 +138,7 @@ export const metroCommandFacet = defineCommandFacet({ summary: 'Prepare the dev server or reload apps', searchHint: 'bundler', cliDetail: - "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. When the session never bound one and open recorded its app as hosted on this machine, on a simulator or emulator, reload then reads the dev-server address the app itself stored (RCT_jsLocation in the app's preferences; iOS simulators only) and accepts it when a running dev server there reports a project root that is this project's root or a parent or child of it. Failing that, it probes the ports a local process is listening on for a dev server whose X-React-Native-Project-Root is this project's root or a parent or child of it (a monorepo server reports the repo root), so it never silently reloads a different project's server. When nothing resolves, reload fails with details.reason 'metro_dev_server_unresolved' naming the address it would have used, instead of calling localhost:8081, which belongs to whichever project owns that port. A session whose device this machine does not host — a physical or provider-hosted device, or an app-less session — skips the local lookups and keeps the default address. 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).", + "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. When the session never bound one, and the daemon that answered open reported the session's device as one of its own local devices, reload then reads the dev-server address the app itself stored (RCT_jsLocation in the app's preferences; an iOS simulator only) and accepts it when a running dev server there reports a project root that is this project's root or a parent or child of it. Failing that, it probes the ports a local process is listening on for a dev server whose X-React-Native-Project-Root is this project's root or a parent or child of it (a monorepo server reports the repo root), so it never silently reloads a different project's server. Run it from the project's own directory, or pass --metro-port, since a local search matches the working directory. When nothing resolves, reload fails with details.reason 'metro_dev_server_unresolved' naming the address it would have used, instead of calling localhost:8081, which belongs to whichever project owns that port. A session this machine cannot prove hosts its device — a provider device, a device inherited from an earlier request, or an app-less session — skips the local lookups and keeps the default address. 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).", }, metadata: metroCommandMetadata, run: async (client, input): Promise => diff --git a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts index 8a7e6d136d..f09c47b926 100644 --- a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts @@ -280,11 +280,11 @@ test('nothing found fails typed and names the address the fallback would have us }); test('an app whose host is not proven local keeps the previous address instead of probing', async () => { + // A provider-hosted device, a device inherited from an earlier request that reported nothing, and + // an app-less session all leave the trait unproven. for (const app of [ { ...simulatorApp, hostedLocally: false }, { ...simulatorApp, hostedLocally: undefined }, - { ...simulatorApp, deviceKind: 'device' as const }, - { ...simulatorApp, deviceKind: undefined }, undefined, ]) { const probe = probeReturning([serverAt(8096, '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/app/project')]); @@ -295,10 +295,10 @@ test('an app whose host is not proven local keeps the previous address instead o } }); -test('discovery is allowed only for an app proven to be hosted here on a virtual target', () => { +test('discovery is allowed only for an app open proved to sit on this machine', () => { assert.equal(canDiscoverForApp(simulatorApp), true); assert.equal(canDiscoverForApp({ ...simulatorApp, deviceKind: 'emulator' }), true); - assert.equal(canDiscoverForApp({ ...simulatorApp, deviceKind: 'device' }), false); + assert.equal(canDiscoverForApp({ ...simulatorApp, deviceKind: 'device' }), true); assert.equal(canDiscoverForApp({ ...simulatorApp, hostedLocally: false }), false); assert.equal(canDiscoverForApp({ ...simulatorApp, hostedLocally: undefined }), false); assert.equal(canDiscoverForApp(undefined), false); diff --git a/packages/react-native/src/metro/metro-dev-server-discovery.ts b/packages/react-native/src/metro/metro-dev-server-discovery.ts index 1118eb72e8..d5a9fdb4eb 100644 --- a/packages/react-native/src/metro/metro-dev-server-discovery.ts +++ b/packages/react-native/src/metro/metro-dev-server-discovery.ts @@ -1,5 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; +import { isLoopbackHostname } from '@agent-device/daemon-contracts/daemon-resolution'; import { runCmd } from '@agent-device/host-kit/command'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; @@ -57,7 +58,10 @@ export const METRO_RELOAD_REASONS = { const SIMULATOR_DEVICES_ROOT = 'Library/Developer/CoreSimulator/Devices'; const METRO_PROJECT_ROOT_HEADER = 'x-react-native-project-root'; -const HOST_READ_TIMEOUT_MS = 1_500; +// A live machine answers these reads slowly: `lsof` walks every process's descriptors and took over +// 1.5 s on a developer Mac with simulators running. The budget has to be the slow machine's, because +// a timeout here is indistinguishable from "this machine listens on nothing". +const HOST_READ_TIMEOUT_MS = 4_000; const STATUS_PROBE_TIMEOUT_MS = 800; const MAX_CONCURRENT_STATUS_PROBES = 32; @@ -92,10 +96,10 @@ export type ResolveMetroReloadServerInput = MetroReloadTargetInput & * live server at that address still has to serve this project to count. * 3. A local dev server that serves the current project. * - * Only a session whose app runs on a simulator or emulator reaches steps 2 and 3: a physical device's - * host is not this machine, so its sessions keep their existing behavior, including the default - * address. With no signal at all, this fails typed rather than calling `localhost:8081`, which in an - * unbound session belongs to whichever project happens to own that port. + * Only a session whose device `open` proved is this daemon's own local device reaches steps 2 and 3: + * a provider device's host is not this machine, so its sessions keep their existing behavior, the + * default address included. With no signal at all, this fails typed rather than calling + * `localhost:8081`, which in an unbound session belongs to whichever project owns that port. */ export async function resolveMetroReloadServerUrl( input: ResolveMetroReloadServerInput, @@ -139,13 +143,12 @@ export async function resolveMetroReloadServerUrl( /** * Whether reload may look for a dev server on this machine for a session's app. It may, only when - * `open` recorded the app as hosted here: a provider-hosted or physical device runs somewhere else, - * so its dev server is not one of this machine's ports, and probing here would answer a question + * `open` recorded the app's device as this daemon's own local device. A provider device runs somewhere + * else, so its dev server is not one of this machine's ports, and probing here would answer a question * nobody asked. */ export function canDiscoverForApp(app: MetroAppTarget | undefined): boolean { - if (!app || app.hostedLocally !== true) return false; - return app.deviceKind === 'simulator' || app.deviceKind === 'emulator'; + return app?.hostedLocally === true; } /** @@ -158,7 +161,7 @@ async function servesProjectRoot( projectRoots: string[], probe: MetroDevServerProbe, ): Promise { - if (!isLoopbackUrl(serverUrl)) return true; + if (!isLoopbackHostname(serverUrl.hostname)) return true; const probeServer = probe.probeServer ?? probeLocalMetroServer; const running = await probeServer(serverUrl, STATUS_PROBE_TIMEOUT_MS).catch(() => undefined); // The app named this address itself, so a server that answers and names no root stays what it @@ -326,10 +329,6 @@ export function metroDevServerUnresolvedError(): AppError { ); } -function isLoopbackUrl(url: URL): boolean { - return ['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0'].includes(url.hostname); -} - function candidateProjectRoots(projectRoots: string[]): string[] { const resolved = projectRoots.map((root) => normalizeRealPath(root)); return [...new Set(resolved)]; diff --git a/packages/react-native/src/metro/metro-session-hints.ts b/packages/react-native/src/metro/metro-session-hints.ts index 85dbe5fce6..67ced2e4a9 100644 --- a/packages/react-native/src/metro/metro-session-hints.ts +++ b/packages/react-native/src/metro/metro-session-hints.ts @@ -245,28 +245,33 @@ export function recordOpenedMetroSession( ): void { try { const scope = resolveMetroSessionScope(options); + const stored = readMetroSessionRecord(scope); + const app = input.app ? keepProvenHost(input.app, stored?.app) : undefined; const url = runtimeServerUrl(input.runtime); if (url) { const binding = input.explicitRuntime ? undefined : readMetroSessionHints(scope); - if (binding && (input.sessionReused || binding.deviceBaseUrls?.includes(url))) return; + if (binding && (input.sessionReused || binding.deviceBaseUrls?.includes(url))) { + if (app) writeMetroSessionHints({ ...scope, hints: { ...binding, app } }); + return; + } writeMetroSessionHints({ ...scope, - hints: { controlBaseUrl: url, ...(input.app ? { app: input.app } : {}) }, + hints: { controlBaseUrl: url, ...(app ? { app } : {}) }, }); return; } // No dev-server hint came with the open, so no address is bound. What is recorded is the app this // open launched: a later reload looks that app's own address up from it. A reused session can - // open a different app, so a recorded app always replaces the previous one; an open that reports - // no app keeps what a reused session already had, and clears a stale record on a fresh session. - if (input.app) { - const binding = readMetroSessionHints(scope); + // open a different app, so a recorded app always replaces the previous one, and it keeps whatever + // address the session already bound. An open that reports no app leaves a reused session's record + // alone and clears a stale one on a fresh session. + if (app) { writeMetroSessionHints({ ...scope, hints: { - ...(binding?.controlBaseUrl ? { controlBaseUrl: binding.controlBaseUrl } : {}), - ...(binding?.deviceBaseUrls ? { deviceBaseUrls: binding.deviceBaseUrls } : {}), - app: input.app, + ...(stored?.controlBaseUrl ? { controlBaseUrl: stored.controlBaseUrl } : {}), + ...(stored?.deviceBaseUrls ? { deviceBaseUrls: stored.deviceBaseUrls } : {}), + app, }, }); return; @@ -275,6 +280,17 @@ export function recordOpenedMetroSession( } catch {} } +/** + * Keeps the host trait an earlier open proved for the same device. An open that resolves the device + * from the session rather than from an inventory reports nothing about where it runs, and that silence + * must not erase what was already proven about this device. + */ +function keepProvenHost(app: MetroAppTarget, stored: MetroAppTarget | undefined): MetroAppTarget { + if (app.hostedLocally !== undefined) return app; + if (!stored || stored.deviceId !== app.deviceId) return app; + return stored.hostedLocally === undefined ? app : { ...app, hostedLocally: stored.hostedLocally }; +} + export function clearMetroSessionHintsQuietly(options: MetroSessionOptions): void { try { clearMetroSessionHints(resolveMetroSessionScope(options)); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 981f1fd7cf..9e22b063b5 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2179,7 +2179,7 @@ agent-device metro reload --bundle-url "http://localhost:8081/index.bundle?platf ``` - `metro reload` asks connected React Native dev builds to reload JavaScript without restarting the native process, like pressing `r` in the Metro terminal. -- Without flags, it reloads the dev server the session bound through `metro prepare` or `open`'s Metro hints. When a recorded app on a local simulator or emulator has no bound server, it next uses that app's own reported address (iOS simulators only) when a dev server there serves this project, then a local dev server whose reported project root is this directory or a parent or child of it. If neither local lookup resolves, it fails with `details.reason: 'metro_dev_server_unresolved'`; physical, provider-hosted, and app-less sessions retain their existing address behavior, the `localhost:8081` default included. A reused session name never reloads a previous project's server. +- Without flags, it reloads the dev server the session bound through `metro prepare` or `open`'s Metro hints. When no session bound one, and the daemon that answered `open` reported the session's device as one of its own local devices, it next uses the dev-server address the app itself stored (an iOS simulator only) when a dev server there serves this project, then a local dev server whose reported project root is this directory or a parent or child of it. Run it from the project's own directory, or pass `--metro-port`, because a local search matches the working directory. If neither local lookup resolves, it fails with `details.reason: 'metro_dev_server_unresolved'`; a provider device, a device inherited from an earlier request, or an app-less session retains the existing `localhost:8081` default. A reused session name never reloads a previous project's server. - Use `open --relaunch` instead when the app is not connected to Metro, the reload fails, or the native process must restart. See `agent-device help metro` for the binding rules. ## Media and logs From 38300d4adaaa87e83c2dcb8ed699b20d8a0c9ddb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 11:50:44 +0100 Subject: [PATCH 04/10] refactor(metro): keep discovery helpers private and split the open recorder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Un-exports the four parsers no caller outside the module reads — the status literal, the netstat address port, host:port, and the JSON-object read — which the tests already cover through the parsers that call them, and splits what `open` records into the binding path and the app path, so neither branch carries the other's conditions. Renames the two unit tests that were named for no module beside them: the reload walkthrough is a package-entry test, the host reads belong to the module whose I/O wrappers they pin. Co-authored-by: Apex --- packages/client/src/index.ts | 2 +- ...ndex-metro-reload-local-discovery.test.ts} | 0 ...etro-dev-server-discovery-host-io.test.ts} | 0 .../metro/metro-dev-server-discovery.test.ts | 7 +- .../metro/metro-dev-server-parsing.test.ts | 2 +- .../src/metro/metro-dev-server-parsing.ts | 8 +- .../src/metro/metro-session-hints.ts | 81 ++++++++++++------- 7 files changed, 61 insertions(+), 39 deletions(-) rename packages/react-native/src/{metro-reload-local-discovery.test.ts => index-metro-reload-local-discovery.test.ts} (100%) rename packages/react-native/src/metro/{metro-dev-server-host-io.test.ts => metro-dev-server-discovery-host-io.test.ts} (100%) diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 29a66ed503..970b6ec4fe 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -19,6 +19,7 @@ import type { CaptureSnapshotResult, DaemonBinding, DaemonLifecycle, + DeviceSelectionMetadata, FlingOptions, MaterializationReleaseOptions, PanOptions, @@ -30,7 +31,6 @@ import type { } from '@agent-device/contracts/client'; import type { AgentArtifactsResult } from '@agent-device/contracts/observability'; import type { MetroPrepareOptions } from '@agent-device/contracts/remote'; -import type { DeviceSelectionMetadata } from '@agent-device/contracts/client'; import { isNonDefaultResponseLevel, type ResponseLevel } from '@agent-device/kernel/contracts'; import { AppError, throwDaemonError } from '@agent-device/kernel/errors'; import { createRequestId } from '@agent-device/host-kit/diagnostics'; diff --git a/packages/react-native/src/metro-reload-local-discovery.test.ts b/packages/react-native/src/index-metro-reload-local-discovery.test.ts similarity index 100% rename from packages/react-native/src/metro-reload-local-discovery.test.ts rename to packages/react-native/src/index-metro-reload-local-discovery.test.ts diff --git a/packages/react-native/src/metro/metro-dev-server-host-io.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts similarity index 100% rename from packages/react-native/src/metro/metro-dev-server-host-io.test.ts rename to packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts diff --git a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts index f09c47b926..bf84f9fe77 100644 --- a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts @@ -231,6 +231,7 @@ test('a port lister that fails, or finds nothing, yields no server', async () => test('every listening port is probed, in bounded batches rather than at once', async () => { const ports = Array.from({ length: 100 }, (_, index) => 20_000 + index); + const lastPort = ports.at(-1)!; let inFlight = 0; let peakInFlight = 0; const matching = await discoverLocalMetroServer({ @@ -241,13 +242,11 @@ test('every listening port is probed, in bounded batches rather than at once', a peakInFlight = Math.max(peakInFlight, inFlight); await Promise.resolve(); inFlight -= 1; - return Number(url.port) === ports[ports.length - 1] - ? serverAt(ports[ports.length - 1]!, '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/app/project') - : undefined; + return Number(url.port) === lastPort ? serverAt(lastPort, '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/app/project') : undefined; }, }); // The 100th port is a real candidate: truncating at the concurrency limit would miss it. - assert.equal(matching?.serverUrl.port, String(ports[ports.length - 1])); + assert.equal(matching?.serverUrl.port, String(lastPort)); assert.ok(peakInFlight <= 32, `peak in-flight was ${peakInFlight}`); }); diff --git a/packages/react-native/src/metro/metro-dev-server-parsing.test.ts b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts index a0cac676ae..35f44e6166 100644 --- a/packages/react-native/src/metro/metro-dev-server-parsing.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts @@ -23,7 +23,7 @@ test('the project-root header is kept plain, percent-decoded, or dropped when em assert.equal(parseMetroProjectRootHeader(' /home/dev/app '), '/home/dev/app'); assert.equal( parseMetroProjectRootHeader('C%3A%5CUsers%5Cdev%5Cproyecto%20n%E2%80%99%C3%AD'), - 'C:\\Users\\dev\\proyecto n’í', + String.raw`C:\Users\dev\proyecto n’í`, ); assert.equal(parseMetroProjectRootHeader('/app/%E2%80%'), '/app/%E2%80%'); assert.equal(parseMetroProjectRootHeader(''), undefined); diff --git a/packages/react-native/src/metro/metro-dev-server-parsing.ts b/packages/react-native/src/metro/metro-dev-server-parsing.ts index 88ea586494..c669a042ae 100644 --- a/packages/react-native/src/metro/metro-dev-server-parsing.ts +++ b/packages/react-native/src/metro/metro-dev-server-parsing.ts @@ -12,7 +12,7 @@ const MAX_PORT = 65_535; const NETSTAT_LISTEN_STATE = 'LISTEN'; /** The body a running React Native dev server answers on `/status`. */ -export const METRO_STATUS_READY_TEXT = 'packager-status:running'; +const METRO_STATUS_READY_TEXT = 'packager-status:running'; export function isMetroStatusBody(text: string): boolean { return text.includes(METRO_STATUS_READY_TEXT); @@ -75,7 +75,7 @@ export function parsePortFromSocketName(name: string): number | undefined { * The port a `netstat` local address ends with, after either separator the two platforms use. A * wildcard address such as `*.*` names no port. */ -export function parsePortFromNetstatAddress(address: string): number | undefined { +function parsePortFromNetstatAddress(address: string): number | undefined { const withoutBrackets = address.replace(/\]$/, ''); const separator = Math.max(withoutBrackets.lastIndexOf(':'), withoutBrackets.lastIndexOf('.')); if (separator <= 0) return undefined; @@ -100,7 +100,7 @@ export function parseAppReportedServerUrl(settingsJson: string): URL | undefined * A `host:port` address, as React Native stores it. The port token must be plain digits: * `127.0.0.1:8081junk` is a broken value, not a hint to reload port 8081. */ -export function parseHostAndPort(value: string, scheme: 'http' | 'https'): URL | undefined { +function parseHostAndPort(value: string, scheme: 'http' | 'https'): URL | undefined { const separator = value.lastIndexOf(':'); if (separator <= 0) return undefined; const host = value.slice(0, separator); @@ -134,7 +134,7 @@ function parsePortToken(token: string): number | undefined { return port >= 1 && port <= MAX_PORT ? port : undefined; } -export function parseJsonObject(text: string): Record | undefined { +function parseJsonObject(text: string): Record | undefined { try { const parsed: unknown = JSON.parse(text); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) diff --git a/packages/react-native/src/metro/metro-session-hints.ts b/packages/react-native/src/metro/metro-session-hints.ts index 67ced2e4a9..053758ea77 100644 --- a/packages/react-native/src/metro/metro-session-hints.ts +++ b/packages/react-native/src/metro/metro-session-hints.ts @@ -239,6 +239,10 @@ export type MetroSessionOpenInput = { app?: MetroAppTarget; }; +/** + * Records what `open` left behind: the address it bound, or the app it launched when it bound none. An + * open never drops a record the session still needs, and a fresh session never inherits one. + */ export function recordOpenedMetroSession( options: MetroSessionOptions, input: MetroSessionOpenInput, @@ -248,38 +252,57 @@ export function recordOpenedMetroSession( const stored = readMetroSessionRecord(scope); const app = input.app ? keepProvenHost(input.app, stored?.app) : undefined; const url = runtimeServerUrl(input.runtime); - if (url) { - const binding = input.explicitRuntime ? undefined : readMetroSessionHints(scope); - if (binding && (input.sessionReused || binding.deviceBaseUrls?.includes(url))) { - if (app) writeMetroSessionHints({ ...scope, hints: { ...binding, app } }); - return; - } - writeMetroSessionHints({ - ...scope, - hints: { controlBaseUrl: url, ...(app ? { app } : {}) }, - }); - return; - } - // No dev-server hint came with the open, so no address is bound. What is recorded is the app this - // open launched: a later reload looks that app's own address up from it. A reused session can - // open a different app, so a recorded app always replaces the previous one, and it keeps whatever - // address the session already bound. An open that reports no app leaves a reused session's record - // alone and clears a stale one on a fresh session. - if (app) { - writeMetroSessionHints({ - ...scope, - hints: { - ...(stored?.controlBaseUrl ? { controlBaseUrl: stored.controlBaseUrl } : {}), - ...(stored?.deviceBaseUrls ? { deviceBaseUrls: stored.deviceBaseUrls } : {}), - app, - }, - }); - return; - } - if (!input.sessionReused) clearMetroSessionHints(scope); + if (url) recordOpenedBinding(scope, input, url, app); + else recordOpenedApp(scope, input.sessionReused, app, stored); } catch {} } +/** + * Records the dev-server address this open bound. A reused session, or one that re-binds an address one + * of its devices already uses, keeps the binding it has: the address it published to those devices is + * the one they are dialling. + */ +function recordOpenedBinding( + scope: MetroSessionScope, + input: MetroSessionOpenInput, + url: string, + app: MetroAppTarget | undefined, +): void { + const binding = input.explicitRuntime ? undefined : readMetroSessionHints(scope); + if (binding && (input.sessionReused || binding.deviceBaseUrls?.includes(url))) { + if (app) writeMetroSessionHints({ ...scope, hints: { ...binding, app } }); + return; + } + writeMetroSessionHints({ ...scope, hints: { controlBaseUrl: url, ...(app ? { app } : {}) } }); +} + +/** + * Records an open that bound no address. What is left is the app this open launched: a later reload + * looks that app's own dev-server address up from it. A reused session can open a different app, so a + * recorded app always replaces the previous one and keeps the address the session already had. An open + * that reports no app leaves a reused session's record alone and clears a stale one on a fresh session. + */ +function recordOpenedApp( + scope: MetroSessionScope, + sessionReused: boolean, + app: MetroAppTarget | undefined, + stored: MetroSessionRecord | undefined, +): void { + if (!app) { + if (!sessionReused) clearMetroSessionHints(scope); + return; + } + writeMetroSessionHints({ ...scope, hints: { ...bindingFields(stored), app } }); +} + +/** The address fields of a stored record, apart from the app recorded beside them. */ +function bindingFields(stored: MetroSessionRecord | undefined): MetroSessionHints { + return { + ...(stored?.controlBaseUrl ? { controlBaseUrl: stored.controlBaseUrl } : {}), + ...(stored?.deviceBaseUrls ? { deviceBaseUrls: stored.deviceBaseUrls } : {}), + }; +} + /** * Keeps the host trait an earlier open proved for the same device. An open that resolves the device * from the session rather than from an inventory reports nothing about where it runs, and that silence From ffc3f908faccf1eefab33eee70bb1a34e4ba1816 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 12:36:49 +0100 Subject: [PATCH 05/10] fix(metro): confirm any app-reported address and dial the family the host named A flagless fresh open no longer inherits a binding a previous run left under the same session name: that address belongs to the project that bound it. A reused session keeps its address, including one stored as runtime hints before the control address existed, so rewriting the record never drops a binding. The app-reported address is now confirmed wherever it points, so a LAN host left by `open --metro-host` is refused when its server serves another project. Listening sockets keep the address the host reported, so a dev server bound to IPv6 loopback only is dialled at `[::1]` instead of being missed on 127.0.0.1. --- packages/client/src/index.ts | 9 +- ...metro-dev-server-discovery-host-io.test.ts | 48 ++++---- .../metro/metro-dev-server-discovery.test.ts | 83 ++++++++++++-- .../src/metro/metro-dev-server-discovery.ts | 77 +++++++------ .../metro/metro-dev-server-parsing.test.ts | 83 +++++++++----- .../src/metro/metro-dev-server-parsing.ts | 103 ++++++++++++------ .../src/metro/metro-session-hints.test.ts | 54 +++++++++ .../src/metro/metro-session-hints.ts | 28 +++-- 8 files changed, 347 insertions(+), 138 deletions(-) diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 970b6ec4fe..487686acc8 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -598,10 +598,11 @@ function daemonIsLocal(config: AgentDeviceClientConfig, host: HostEnvironment): } /** - * Whether `open` proved the session's device runs on this machine: the daemon answers here, and it - * resolved the device from its own local inventory. A provider device, a device carried over from an - * earlier request, or a daemon on another machine leaves it unproven — `undefined`, not `false` — and - * the record keeps whatever an earlier open proved for the same device. + * Whether `open` proved where the session's device runs. A daemon on another machine proves the device + * is not on this one: the record is written here, so nothing here can read that device's state, and the + * answer is `false`. On a local daemon the device's origin decides: `true` when the daemon resolved it + * from its own inventory, `false` when it came from a provider, and `undefined` when the answer says + * nothing, which keeps whatever an earlier open proved for the same device. */ function appHostedLocally( config: AgentDeviceClientConfig, diff --git a/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts index 8bf43fab97..6d98294b02 100644 --- a/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts @@ -7,8 +7,8 @@ import path from 'node:path'; import { withCommandExecutorOverride } from '@agent-device/host-kit/command'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { - listLocalListeningPorts, - probeLocalMetroServer, + listLocalListeningSockets, + probeMetroServerStatus, readAppReportedMetroServerUrl, type MetroAppTarget, } from './metro-dev-server-discovery.ts'; @@ -124,50 +124,56 @@ test('an app reports nothing when its preferences, HOME, or the converter is una test('ports come from lsof when it is installed', async () => { const spawned: string[] = []; - const ports = await withCommandExecutorOverride( + const sockets = await withCommandExecutorOverride( (command) => { spawned.push(command); return Promise.resolve({ - stdout: command === 'lsof' ? 'p1\nn127.0.0.1:8081\nn*:8096\n' : '', + stdout: command === 'lsof' ? 'p1\nn127.0.0.1:8081\nn[::1]:8096\n' : '', stderr: '', exitCode: 0, }); }, - async () => await listLocalListeningPorts(), + async () => await listLocalListeningSockets(), ); - assert.deepEqual(ports, [8081, 8096]); + assert.deepEqual(sockets, [ + { host: '127.0.0.1', port: 8081 }, + { host: '::1', port: 8096 }, + ]); // netstat is only asked where lsof could not answer. assert.deepEqual(spawned, ['lsof']); }); test('ports fall back to netstat on a host without lsof', async () => { const spawned: string[] = []; - const ports = await withCommandExecutorOverride( + const sockets = await withCommandExecutorOverride( (command) => { spawned.push(command); if (command === 'lsof') return Promise.reject(new Error('lsof ENOENT')); return Promise.resolve({ - stdout: 'tcp4 0 0 127.0.0.1.8081 *.* LISTEN\ntcp4 0 0 127.0.0.1.9999 *.* ESTABLISHED\n', + stdout: 'tcp4 0 0 127.0.0.1.8081 *.* LISTEN\ntcp6 0 0 ::1.8096 *.* LISTEN\ntcp4 0 0 127.0.0.1.9999 *.* ESTABLISHED\n', stderr: '', exitCode: 0, }); }, - async () => await listLocalListeningPorts(), + async () => await listLocalListeningSockets(), ); - assert.deepEqual(ports, [8081]); + assert.deepEqual(sockets, [ + { host: '127.0.0.1', port: 8081 }, + { host: '::1', port: 8096 }, + ]); assert.deepEqual(spawned, ['lsof', 'netstat']); }); test('a host with neither lsof nor netstat reports no ports instead of failing', async () => { - const ports = await withCommandExecutorOverride( + const sockets = await withCommandExecutorOverride( (command) => Promise.reject(new Error(`${command} ENOENT`)), - async () => await listLocalListeningPorts(), + async () => await listLocalListeningSockets(), ); - assert.deepEqual(ports, []); + assert.deepEqual(sockets, []); }); test('a tool that answers with an empty success still lets the other tool answer', async () => { - const ports = await withCommandExecutorOverride( + const sockets = await withCommandExecutorOverride( (command) => command === 'lsof' ? Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }) @@ -176,9 +182,9 @@ test('a tool that answers with an empty success still lets the other tool answer stderr: '', exitCode: 0, }), - async () => await listLocalListeningPorts(), + async () => await listLocalListeningSockets(), ); - assert.deepEqual(ports, [8081]); + assert.deepEqual(sockets, [{ host: '127.0.0.1', port: 8081 }]); }); test('a /status that says the packager is running reports the server and its project root', async () => { @@ -188,7 +194,7 @@ test('a /status that says the packager is running reports the server and its pro }); const port = await listenOnLoopback(server); try { - const running = await probeLocalMetroServer(new URL(`http://127.0.0.1:${port}`), 2_000); + const running = await probeMetroServerStatus(new URL(`http://127.0.0.1:${port}`), 2_000); assert.equal(running?.serverUrl.port, String(port)); assert.equal(running?.projectRoot, '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/app/project'); } finally { @@ -200,7 +206,7 @@ test('a server without a project-root header is reported without one', async () const server = answerStatusServer({ body: 'packager-status:running' }); const port = await listenOnLoopback(server); try { - const running = await probeLocalMetroServer(new URL(`http://127.0.0.1:${port}`), 2_000); + const running = await probeMetroServerStatus(new URL(`http://127.0.0.1:${port}`), 2_000); assert.equal(running?.projectRoot, undefined); } finally { await closeLoopbackServer(server); @@ -217,15 +223,15 @@ test('a /status that is not Metro, or is not there at all, reports no server', a const unavailablePort = await listenOnLoopback(unavailable); try { assert.equal( - await probeLocalMetroServer(new URL(`http://127.0.0.1:${notMetroPort}`), 2_000), + await probeMetroServerStatus(new URL(`http://127.0.0.1:${notMetroPort}`), 2_000), undefined, ); assert.equal( - await probeLocalMetroServer(new URL(`http://127.0.0.1:${unavailablePort}`), 2_000), + await probeMetroServerStatus(new URL(`http://127.0.0.1:${unavailablePort}`), 2_000), undefined, ); // A port nothing listens on: a connection error, not a crash. - assert.equal(await probeLocalMetroServer(new URL('http://127.0.0.1:1'), 500), undefined); + assert.equal(await probeMetroServerStatus(new URL('http://127.0.0.1:1'), 500), undefined); } finally { await closeLoopbackServer(notMetro); await closeLoopbackServer(unavailable); diff --git a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts index bf84f9fe77..67c00a22e4 100644 --- a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts @@ -24,8 +24,14 @@ const simulatorApp: MetroAppTarget = { }; function serverAt(port: number, projectRoot?: string): LocalMetroServer { + return serverAtHost('127.0.0.1', port, projectRoot); +} + +function serverAtHost(address: string, port: number, projectRoot?: string): LocalMetroServer { + // An IPv6 address needs URL brackets to be dialled at all, which the host part then drops. + const bracketed = address.includes(':') && !address.startsWith('[') ? `[${address}]` : address; return { - serverUrl: new URL(`http://127.0.0.1:${port}`), + serverUrl: new URL(`http://${bracketed}:${port}`), ...(projectRoot ? { projectRoot } : {}), }; } @@ -38,9 +44,13 @@ function probeReturning( return { record: recorded, probe: { - listListeningPorts: async () => { + listListeningSockets: async () => { recorded.portsRead += 1; - return servers.map((server) => Number(server.serverUrl.port)); + return servers.map((server) => ({ + // What a host lister names: an IPv6 address arrives without URL brackets. + host: server.serverUrl.hostname.replace(/[[\]]/g, ''), + port: Number(server.serverUrl.port), + })); }, probeServer: async (url: URL) => byUrl.get(url.origin), readAppReportedServerUrl: async () => { @@ -146,11 +156,14 @@ test('a server that runs and reports no project root is still the address the ap assert.equal(resolved.serverUrl.port, '8096'); }); -test('an app-reported address that is not loopback is taken without probing this host', async () => { - const probe = probeReturning([]); +test('an app-reported address off this host is confirmed the same way as one on it', async () => { + // A LAN host left by `open --metro-host` is a host this reload is about to call anyway, so the same + // bounded `/status` read decides it: its project root, not the address, is what makes it ours. + const probe = probeReturning([serverAtHost('10.0.0.5', 19000, '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/app/project')]); const resolved = await resolveMetroReloadServerUrl({ host, app: simulatorApp, + projectRoot: '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/app/project', probe: { ...probe.probe, readAppReportedServerUrl: async () => new URL('http://10.0.0.5:19000'), @@ -160,12 +173,36 @@ test('an app-reported address that is not loopback is taken without probing this assert.equal(resolved.serverUrl.origin, 'http://10.0.0.5:19000'); }); +test("an app-reported address off this host is refused when its server serves another project", async () => { + const probe = probeReturning([serverAtHost('10.0.0.5', 19000, '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/other/project')]); + await assert.rejects( + () => + resolveMetroReloadServerUrl({ + host, + app: simulatorApp, + projectRoot: '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/app/project', + probe: { + ...probe.probe, + readAppReportedServerUrl: async () => new URL('http://10.0.0.5:19000'), + }, + }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, METRO_RELOAD_REASONS.devServerUnresolved.reason); + return true; + }, + ); +}); + test('an app-reported address whose probe fails is refused instead of trusted', async () => { const resolved = await resolveMetroReloadServerUrl({ host, app: simulatorApp, probe: { - listListeningPorts: async () => [8096, 8097], + listListeningSockets: async () => [ + { host: '127.0.0.1', port: 8096 }, + { host: '127.0.0.1', port: 8097 }, + ], probeServer: async (url: URL) => { if (url.port === '8097') throw new Error('ECONNREFUSED'); return serverAt(8096, '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/app/project'); @@ -182,7 +219,7 @@ test('an app address with no server behind it falls through to the local search' host, app: simulatorApp, probe: { - listListeningPorts: async () => [8096], + listListeningSockets: async () => [{ host: '127.0.0.1', port: 8096 }], probeServer: async (url: URL) => url.port === '8096' ? serverAt(8096, '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/app/project') : undefined, readAppReportedServerUrl: async () => new URL('http://127.0.0.1:8097'), @@ -195,7 +232,10 @@ test('an app address with no server behind it falls through to the local search' test("the local search matches the project root and never picks another project's server", async () => { const matching = await discoverLocalMetroServer({ projectRoots: ['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/app/project'], - listListeningPorts: async () => [8081, 8096], + listListeningSockets: async () => [ + { host: '127.0.0.1', port: 8081 }, + { host: '127.0.0.1', port: 8096 }, + ], probeServer: async (url: URL) => url.port === '8096' ? serverAt(8096, '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/app/project/packages/mobile') @@ -205,16 +245,35 @@ test("the local search matches the project root and never picks another project' const foreign = await discoverLocalMetroServer({ projectRoots: ['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/app/project'], - listListeningPorts: async () => [8081], + listListeningSockets: async () => [{ host: '127.0.0.1', port: 8081 }], probeServer: async () => serverAt(8081, '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/other/project'), }); assert.equal(foreign, undefined); }); +test('a socket is dialled at the address the host reported, so an IPv6-only server is found', async () => { + // Metro bound to `[::1]` answers no request on 127.0.0.1, so dialling the family the lister named is + // the only way a sweep reaches it. + const seen: string[] = []; + const matching = await discoverLocalMetroServer({ + projectRoots: ['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/app/project'], + listListeningSockets: async () => [ + { host: '127.0.0.1', port: 8096 }, + { host: '::1', port: 8097 }, + ], + probeServer: async (url: URL) => { + seen.push(url.origin); + return url.port === '8097' ? serverAtHost('::1', 8097, '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/app/project') : undefined; + }, + }); + assert.deepEqual(seen, ['http://127.0.0.1:8096', 'http://[::1]:8097']); + assert.equal(matching?.serverUrl.toString(), 'http://[::1]:8097/'); +}); + test('a port lister that fails, or finds nothing, yields no server', async () => { const failing = await discoverLocalMetroServer({ projectRoots: ['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/app/project'], - listListeningPorts: async () => { + listListeningSockets: async () => { throw new Error('lsof not found in PATH'); }, probeServer: async () => serverAt(8081, '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/app/project'), @@ -223,7 +282,7 @@ test('a port lister that fails, or finds nothing, yields no server', async () => const empty = await discoverLocalMetroServer({ projectRoots: ['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/app/project'], - listListeningPorts: async () => [], + listListeningSockets: async () => [], probeServer: async () => serverAt(8081, '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/app/project'), }); assert.equal(empty, undefined); @@ -236,7 +295,7 @@ test('every listening port is probed, in bounded batches rather than at once', a let peakInFlight = 0; const matching = await discoverLocalMetroServer({ projectRoots: ['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/app/project'], - listListeningPorts: async () => ports, + listListeningSockets: async () => ports.map((port) => ({ host: '127.0.0.1', port })), probeServer: async (url: URL) => { inFlight += 1; peakInFlight = Math.max(peakInFlight, inFlight); diff --git a/packages/react-native/src/metro/metro-dev-server-discovery.ts b/packages/react-native/src/metro/metro-dev-server-discovery.ts index d5a9fdb4eb..322b513d0f 100644 --- a/packages/react-native/src/metro/metro-dev-server-discovery.ts +++ b/packages/react-native/src/metro/metro-dev-server-discovery.ts @@ -1,6 +1,5 @@ import fs from 'node:fs'; import path from 'node:path'; -import { isLoopbackHostname } from '@agent-device/daemon-contracts/daemon-resolution'; import { runCmd } from '@agent-device/host-kit/command'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; @@ -14,10 +13,12 @@ import { import { isMetroStatusBody, parseAppReportedServerUrl, - parseLsofListeningPorts, + parseLsofListeningSockets, parseMetroProjectRootHeader, - parseNetstatListeningPorts, + parseNetstatListeningSockets, projectRootsOverlap, + socketUrl, + type ListeningSocket, } from './metro-dev-server-parsing.ts'; /** @@ -67,8 +68,8 @@ const MAX_CONCURRENT_STATUS_PROBES = 32; /** The host reads a reload can make, injectable so the resolution order is testable without a host. */ export type MetroDevServerProbe = Readonly<{ - /** Ports a local process is listening on. */ - listListeningPorts?: () => Promise; + /** Listening sockets a local process is dialled on, each with the address the host reported. */ + listListeningSockets?: () => Promise; /** The dev server at an address, when one answers there. */ probeServer?: (serverUrl: URL, timeoutMs: number) => Promise; /** What the session's app itself stored as its dev-server address. */ @@ -123,16 +124,17 @@ export async function resolveMetroReloadServerUrl( host, ).catch(() => undefined); if (reported && (await servesProjectRoot(reported, projectRoots, probe))) { - // The app cannot be wrong about the server it loads from, but its stored address can outlive - // that server, and somebody else's Metro can take the port. On loopback, where this host can - // answer for it, one bounded probe settles both questions. + // The app cannot be wrong about the server it loads from, but its stored address can outlive that + // server, and something else can take the host or port since. One bounded `/status` read settles + // both questions, wherever the address points: a LAN host left by `open --metro-host` is a host + // this reload is about to call anyway. return { serverUrl: reported, resolvedBy: 'app-reported' }; } const discovered = await discoverLocalMetroServer({ projectRoots, - listListeningPorts: probe.listListeningPorts ?? listLocalListeningPorts, - probeServer: probe.probeServer ?? probeLocalMetroServer, + listListeningSockets: probe.listListeningSockets ?? listLocalListeningSockets, + probeServer: probe.probeServer ?? probeMetroServerStatus, }); if (discovered) { return { serverUrl: discovered.serverUrl, resolvedBy: 'local-project-root' }; @@ -152,20 +154,21 @@ export function canDiscoverForApp(app: MetroAppTarget | undefined): boolean { } /** - * Confirms an app-reported address against the project it must serve. A server that is not running, - * or one that names a project unrelated to this session, is refused. A server that reports no root at - * all is accepted: the app named this address itself, and older dev servers send no root header. + * Confirms an app-reported address against the project it must serve. A server that does not answer, + * or one that names a project unrelated to this session, is refused. A server that answers and reports + * no root at all is accepted: the app named this address itself, and older dev servers send no root + * header. The read is bounded and makes no assumptions about where the address points, so an address + * that leaves this machine is confirmed the same way as one that stays on it. */ async function servesProjectRoot( serverUrl: URL, projectRoots: string[], probe: MetroDevServerProbe, ): Promise { - if (!isLoopbackHostname(serverUrl.hostname)) return true; - const probeServer = probe.probeServer ?? probeLocalMetroServer; + const probeServer = probe.probeServer ?? probeMetroServerStatus; const running = await probeServer(serverUrl, STATUS_PROBE_TIMEOUT_MS).catch(() => undefined); // The app named this address itself, so a server that answers and names no root stays what it - // reported. Only a root that names a different project refuses it. + // reported. Only a server that is gone, or one that names a different project, refuses it. if (!running) return false; return running.projectRoot === undefined || matchesProjectRoot(running, projectRoots); } @@ -211,9 +214,9 @@ async function readSimulatorAppPreferences( } /** - * The local dev server that serves this project: a listening port whose `/status` answers + * The local dev server that serves this project: a listening socket whose `/status` answers * `packager-status:running` and whose `X-React-Native-Project-Root` is one of the project roots or a - * parent or child of one (a monorepo server serves from the repo root). Ports come from what a local + * parent or child of one (a monorepo server serves from the repo root). Sockets come from what a local * process actually listens on, each probe is short, and they run bounded in parallel, so a miss costs * one bounded sweep rather than a reload timeout. A project-root match always wins, and a server that * names a different project never counts, so another project's Metro is not reloaded by accident. @@ -221,29 +224,33 @@ async function readSimulatorAppPreferences( export async function discoverLocalMetroServer( input: Readonly<{ projectRoots: string[]; - listListeningPorts: () => Promise; + listListeningSockets: () => Promise; probeServer: (serverUrl: URL, timeoutMs: number) => Promise; probeTimeoutMs?: number; }>, ): Promise { - const ports = await input.listListeningPorts().catch(() => [] as number[]); + const sockets = await input.listListeningSockets().catch(() => [] as ListeningSocket[]); const timeoutMs = input.probeTimeoutMs ?? STATUS_PROBE_TIMEOUT_MS; - const servers = await probePorts(ports, input.probeServer, timeoutMs); + const servers = await probeListeningSockets(sockets, input.probeServer, timeoutMs); const roots = candidateProjectRoots(input.projectRoots); return servers.find((candidate) => matchesProjectRoot(candidate, roots)); } -/** Probes every port, at most MAX_CONCURRENT_STATUS_PROBES at a time, keeping probe failures quiet. */ -async function probePorts( - ports: number[], +/** + * Probes every socket, at most MAX_CONCURRENT_STATUS_PROBES at a time, keeping probe failures quiet. + * Each is dialled at the address the host reported it on: a process bound to one address family is + * unreachable over the other, so an IPv6-only dev server is met at its IPv6 address. + */ +async function probeListeningSockets( + sockets: ListeningSocket[], probeServer: (serverUrl: URL, timeoutMs: number) => Promise, timeoutMs: number, ): Promise { const servers: LocalMetroServer[] = []; - for (let start = 0; start < ports.length; start += MAX_CONCURRENT_STATUS_PROBES) { - const batch = ports + for (let start = 0; start < sockets.length; start += MAX_CONCURRENT_STATUS_PROBES) { + const batch = sockets .slice(start, start + MAX_CONCURRENT_STATUS_PROBES) - .map((port) => probeServer(new URL(`http://127.0.0.1:${port}`), timeoutMs)); + .map((socket) => probeServer(socketUrl(socket), timeoutMs)); for (const settled of await Promise.allSettled(batch)) { if (settled.status === 'fulfilled' && settled.value) servers.push(settled.value); } @@ -266,18 +273,18 @@ function normalizeRealPath(input: string): string { } /** - * The ports this host's processes listen on: what `lsof` reports, or, where `lsof` is not installed, - * what `netstat` reports. A host with neither tool yields no ports, and reload answers with the typed + * The sockets this host's processes listen on: what `lsof` reports, or, where `lsof` is not installed, + * what `netstat` reports. A host with neither tool yields no sockets, and reload answers with the typed * failure rather than a crash or a guess. */ -export async function listLocalListeningPorts(): Promise { +export async function listLocalListeningSockets(): Promise { const lsof = await runHostCommand('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-Fn']); if (lsof !== undefined) { - const ports = parseLsofListeningPorts(lsof); - if (ports.length > 0) return ports; + const sockets = parseLsofListeningSockets(lsof); + if (sockets.length > 0) return sockets; } const netstat = await runHostCommand('netstat', ['-an', '-p', 'tcp']); - return netstat === undefined ? [] : parseNetstatListeningPorts(netstat); + return netstat === undefined ? [] : parseNetstatListeningSockets(netstat); } /** A host command's stdout, or undefined when it is missing, fails, or times out. */ @@ -289,8 +296,8 @@ async function runHostCommand(command: string, args: string[]): Promise { diff --git a/packages/react-native/src/metro/metro-dev-server-parsing.test.ts b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts index 35f44e6166..85f3354d39 100644 --- a/packages/react-native/src/metro/metro-dev-server-parsing.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts @@ -4,11 +4,11 @@ import path from 'node:path'; import { isMetroStatusBody, parseAppReportedServerUrl, - parseLsofListeningPorts, + parseLsofListeningSockets, parseMetroProjectRootHeader, - parseNetstatListeningPorts, - parsePortFromSocketName, + parseNetstatListeningSockets, projectRootsOverlap, + socketUrl, } from './metro-dev-server-parsing.ts'; test('a /status body counts as a running dev server only when it names the packager', () => { @@ -31,21 +31,47 @@ test('the project-root header is kept plain, percent-decoded, or dropped when em assert.equal(parseMetroProjectRootHeader(null), undefined); }); -test('lsof field output yields each listening port once, ascending', () => { +test('lsof field output yields each listening socket once, ordered by port', () => { assert.deepEqual( - parseLsofListeningPorts('p956\nf9\nn*:7000\nn127.0.0.1:8081\np12\nn[::1]:8081\n'), - [7000, 8081], + parseLsofListeningSockets('p956\nf9\nn*:7000\nn127.0.0.1:8081\np12\nn[::1]:8081\n'), + [ + { host: '127.0.0.1', port: 7000 }, + { host: '127.0.0.1', port: 8081 }, + { host: '::1', port: 8081 }, + ], + ); +}); + +test('lsof keeps the address family it reports, brackets and all', () => { + // Metro bound to IPv6 loopback only is unreachable on 127.0.0.1, so this is the address it must be + // dialled at; a wildcard listener is kept as loopback, which reaches every address of this host. + const sockets = parseLsofListeningSockets('n[::1]:8096\nn127.0.0.1:8096\nn*:8097\nn[2001:db8::1]:8098\n'); + assert.deepEqual(sockets, [ + { host: '127.0.0.1', port: 8096 }, + { host: '::1', port: 8096 }, + { host: '127.0.0.1', port: 8097 }, + { host: '2001:db8::1', port: 8098 }, + ]); + assert.deepEqual( + sockets.map((socket) => socketUrl(socket).toString()), + [ + 'http://127.0.0.1:8096/', + 'http://[::1]:8096/', + 'http://127.0.0.1:8097/', + 'http://[2001:db8::1]:8098/', + ], ); }); test('lsof lines that name no socket or no numeric port are skipped', () => { - assert.deepEqual(parseLsofListeningPorts('p956\nf9\ncTCP\n'), []); - assert.deepEqual(parseLsofListeningPorts('nlocalhost:http-alt\nn:8081\nn127.0.0.1:0\n'), []); + assert.deepEqual(parseLsofListeningSockets('p956\nf9\ncTCP\n'), []); + assert.deepEqual(parseLsofListeningSockets('nlocalhost:http-alt\nn:8081\nn127.0.0.1:0\n'), []); + assert.deepEqual(parseLsofListeningSockets('n127.0.0.1:8081junk\nn]:8081\n'), []); }); -test('netstat output yields only tcp rows in LISTEN state, deduplicated and ascending', () => { +test('netstat output yields only tcp rows in LISTEN state, deduplicated and ordered', () => { assert.deepEqual( - parseNetstatListeningPorts( + parseNetstatListeningSockets( [ 'tcp4 0 0 127.0.0.1.8081 *.* LISTEN', 'tcp4 0 0 127.0.0.1.8081 127.0.0.1.55121 ESTABLISHED', @@ -54,25 +80,30 @@ test('netstat output yields only tcp rows in LISTEN state, deduplicated and asce 'udp4 0 0 127.0.0.1.5353 *.*', ].join('\n'), ), - [8081, 8096], + [ + { host: '127.0.0.1', port: 8081 }, + { host: '::1', port: 8096 }, + ], ); }); -test('both netstat address spellings name their port, and a wildcard still names none', () => { - // Linux prints `127.0.0.1:8081`; macOS prints `127.0.0.1.8081`. - assert.deepEqual(parseNetstatListeningPorts('tcp4 0 0 127.0.0.1:8081 0.0.0.0:* LISTEN'), [8081]); - assert.deepEqual(parseNetstatListeningPorts('tcp4 0 0 *.8081 *.* LISTEN'), [8081]); - assert.deepEqual(parseNetstatListeningPorts('tcp4 0 0 *.*.* LISTEN'), []); -}); - -test('the port a socket name ends with is read only when it is a real port', () => { - assert.equal(parsePortFromSocketName('127.0.0.1:8081'), 8081); - assert.equal(parsePortFromSocketName('[::1]:8096'), 8096); - assert.equal(parsePortFromSocketName('127.0.0.1:8081junk'), undefined); - assert.equal(parsePortFromSocketName('127.0.0.1:70000'), undefined); - assert.equal(parsePortFromSocketName('127.0.0.1:0'), undefined); - assert.equal(parsePortFromSocketName('8081'), undefined); - assert.equal(parsePortFromSocketName(':8081'), undefined); +test('both netstat address spellings name their host and port, and a wildcard names loopback', () => { + // Linux prints `127.0.0.1:8081` and `[::1]:8096`; macOS prints `127.0.0.1.8081` and `::1.8096`. + assert.deepEqual(parseNetstatListeningSockets('tcp4 0 0 127.0.0.1:8081 0.0.0.0:* LISTEN'), [ + { host: '127.0.0.1', port: 8081 }, + ]); + assert.deepEqual(parseNetstatListeningSockets('tcp4 0 0 *.8081 *.* LISTEN'), [ + { host: '127.0.0.1', port: 8081 }, + ]); + assert.deepEqual(parseNetstatListeningSockets('tcp6 0 0 [::1]:8096 0.0.0.0:* LISTEN'), [ + { host: '::1', port: 8096 }, + ]); + assert.deepEqual(parseNetstatListeningSockets('tcp6 0 0 *.8096 *.* LISTEN'), [ + { host: '127.0.0.1', port: 8096 }, + ]); + // No host before the separator is no address to dial. + assert.deepEqual(parseNetstatListeningSockets('tcp4 0 0 *.*.* LISTEN'), []); + assert.deepEqual(parseNetstatListeningSockets('tcp4 0 0 127.0.0.1.8081 *.* TIME_WAIT'), []); }); test('the app-reported server URL is what RCT_jsLocation names, with the stored scheme', () => { diff --git a/packages/react-native/src/metro/metro-dev-server-parsing.ts b/packages/react-native/src/metro/metro-dev-server-parsing.ts index c669a042ae..186a71719b 100644 --- a/packages/react-native/src/metro/metro-dev-server-parsing.ts +++ b/packages/react-native/src/metro/metro-dev-server-parsing.ts @@ -34,54 +34,91 @@ export function parseMetroProjectRootHeader(value: string | null): string | unde } /** - * The listening ports `lsof -nP -iTCP -sTCP:LISTEN -Fn` reports, deduplicated and ascending. A line - * that names no socket, or a name whose port is not a plain number, is not a listening TCP socket. + * A TCP socket a local process listens on, kept as the address family the host reported it in: the + * host part is a bare hostname (`127.0.0.1`, `::1`, `localhost`) and never carries URL brackets. */ -export function parseLsofListeningPorts(stdout: string): number[] { - const ports = new Set(); - for (const line of stdout.split('\n')) { - if (!line.startsWith('n')) continue; - const port = parsePortFromSocketName(line.slice(1)); - if (port !== undefined) ports.add(port); - } - return [...ports].sort((left, right) => left - right); +export type ListeningSocket = Readonly<{ host: string; port: number }>; + +const LOOPBACK_HOST = '127.0.0.1'; +const IPV6_SEPARATOR = ':'; + +/** + * The address to dial for a listening socket. A host with a colon is an IPv6 address and needs URL + * brackets; an IPv4 or named host does not. + */ +export function socketUrl(socket: ListeningSocket, scheme: 'http' | 'https' = 'http'): URL { + const host = socket.host.includes(IPV6_SEPARATOR) ? `[${socket.host}]` : socket.host; + return new URL(`${scheme}://${host}:${socket.port}`); } /** - * The listening ports `netstat -an -p tcp` reports, deduplicated and ascending. Linux and macOS - * number the same columns: local address fourth, state sixth. Their address formats differ — Linux - * writes `127.0.0.1:8081`, macOS `127.0.0.1.8081` — so either trailing separator names the port. + * The listening sockets `lsof -nP -iTCP -sTCP:LISTEN -Fn` reports, deduplicated and ordered by port. + * A line that names no socket, or a name whose port is not a plain number, is not a listening TCP + * socket. `lsof` writes an IPv6 socket as `[::1]:8096`, and the brackets are not part of the host. */ -export function parseNetstatListeningPorts(stdout: string): number[] { - const ports = new Set(); - for (const line of stdout.split('\n')) { +export function parseLsofListeningSockets(stdout: string): ListeningSocket[] { + return collectListeningSockets(stdout, (line) => (line.startsWith('n') ? line.slice(1) : '')); +} + +/** + * The listening sockets `netstat -an -p tcp` reports, deduplicated and ordered by port. Linux and + * macOS number the same columns: local address fourth, state sixth. + */ +export function parseNetstatListeningSockets(stdout: string): ListeningSocket[] { + return collectListeningSockets(stdout, (line) => { const columns = line.trim().split(/\s+/); - if (!columns[0]?.startsWith('tcp')) continue; - if (columns[5] !== NETSTAT_LISTEN_STATE) continue; - const port = parsePortFromNetstatAddress(columns[3] ?? ''); - if (port !== undefined) ports.add(port); - } - return [...ports].sort((left, right) => left - right); + if (!columns[0]?.startsWith('tcp') || columns[5] !== NETSTAT_LISTEN_STATE) return ''; + return columns[3] ?? ''; + }); } -/** The port a socket name such as `127.0.0.1:8081` ends with. */ -export function parsePortFromSocketName(name: string): number | undefined { - const separator = name.lastIndexOf(':'); - if (separator <= 0) return undefined; - return parsePortToken(name.slice(separator + 1)); +function collectListeningSockets( + stdout: string, + addressOf: (line: string) => string, +): ListeningSocket[] { + const sockets = new Map(); + for (const line of stdout.split('\n')) { + const socket = parseListeningSocket(addressOf(line)); + if (socket) sockets.set(`${socket.host}:${socket.port}`, socket); + } + return [...sockets.values()].sort((left, right) => left.port - right.port || byName(left, right)); } /** - * The port a `netstat` local address ends with, after either separator the two platforms use. A - * wildcard address such as `*.*` names no port. + * One socket address: a host and a plain-digit port, split at whichever separator comes last, since + * the two hosts write them differently (`127.0.0.1:8081`, `127.0.0.1.8081`, `[::1]:8096`, `::1.8096`). + * URL brackets are not part of the host. A name with no host before the separator — `:8081`, `*.*` — + * names no address to dial; a wildcard host answers on this host's own addresses, so loopback reaches + * it and the record keeps the dialling address rather than the wildcard. */ -function parsePortFromNetstatAddress(address: string): number | undefined { - const withoutBrackets = address.replace(/\]$/, ''); - const separator = Math.max(withoutBrackets.lastIndexOf(':'), withoutBrackets.lastIndexOf('.')); +function parseListeningSocket(address: string): ListeningSocket | undefined { + // An IPv6 name is bracketed and keeps its colons inside: `[::1]:8096`. + const bracketEnd = address.lastIndexOf(']'); + if (bracketEnd > 0) { + return namedSocket( + address.slice(1, bracketEnd), + parsePortToken(address.slice(bracketEnd + 1).replace(/^[:.]/, '')), + ); + } + const separator = Math.max(address.lastIndexOf('.'), address.lastIndexOf(':')); if (separator <= 0) return undefined; - return parsePortToken(withoutBrackets.slice(separator + 1)); + return namedSocket(address.slice(0, separator), parsePortToken(address.slice(separator + 1))); } +function namedSocket(host: string, port: number | undefined): ListeningSocket | undefined { + // A host left holding a bracket came from a name that is not an address at all. + if (!host || port === undefined || host.includes('[') || host.includes(']')) return undefined; + return { host: WILDCARD_HOSTS.has(host) ? LOOPBACK_HOST : host, port }; +} + +/** Names two sockets at the same port in a stable order, whatever the host's locale is. */ +function byName(left: ListeningSocket, right: ListeningSocket): number { + return left.host < right.host ? -1 : left.host > right.host ? 1 : 0; +} + +/** Listeners bound to every address of this host, which loopback therefore reaches. */ +const WILDCARD_HOSTS = new Set(['*', '::', '0.0.0.0']); + /** * The dev server an iOS app stored in its own preferences: `RCT_jsLocation` as `host:port`, with * `RCT_packager_scheme` selecting `https` when it says so. Anything else — no settings, no key, an diff --git a/packages/react-native/src/metro/metro-session-hints.test.ts b/packages/react-native/src/metro/metro-session-hints.test.ts index 5a7376f405..87d74237d8 100644 --- a/packages/react-native/src/metro/metro-session-hints.test.ts +++ b/packages/react-native/src/metro/metro-session-hints.test.ts @@ -225,6 +225,60 @@ test('re-recording the app keeps a binding the session already had', () => { } }); +test('a fresh open with no metro flags drops a binding a previous run left behind', () => { + const stateDir = tempStateDir(); + try { + const options = { stateDir, session: 'stale', host: hostFor(stateDir) }; + // Project A bound this session name to its own dev server in an earlier run. + recordPreparedMetroSession(options, { + statusUrl: 'http://127.0.0.1:8081/status', + iosRuntime: { metroHost: '127.0.0.1', metroPort: 8081 }, + androidRuntime: { metroHost: '127.0.0.1', metroPort: 8081, platform: 'android' }, + }); + // A fresh open of project B, with no --metro-host/--metro-port, must not inherit that address. + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: false, + app: iosApp, + }); + + assert.equal(readMetroSessionHints({ stateDir, session: 'stale' }), undefined); + assert.deepEqual(readMetroSessionAppTarget({ ...options }), iosApp); + } finally { + rmSync(stateDir, { recursive: true, force: true }); + } +}); + +test('re-recording the app keeps a binding written in the older runtime-hint shape', () => { + const stateDir = tempStateDir(); + try { + const options = { stateDir, session: 'legacy', host: hostFor(stateDir) }; + // A record from before the control address existed: the reader resolves a binding from it. + const file = path.join(stateDir, 'metro-sessions', 'legacy.json'); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify({ metroHost: '127.0.0.1', metroPort: 8096 })); + assert.deepEqual(readMetroSessionHints({ stateDir, session: 'legacy' }), { + controlBaseUrl: 'http://127.0.0.1:8096/', + }); + + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: true, + app: iosApp, + }); + + // Rewriting the record must not drop the binding it only had as runtime hints. + assert.deepEqual(readMetroSessionHints({ stateDir, session: 'legacy' }), { + controlBaseUrl: 'http://127.0.0.1:8096/', + app: iosApp, + }); + } finally { + rmSync(stateDir, { recursive: true, force: true }); + } +}); + test('an open that reports no app leaves a reused session record alone and clears a fresh one', () => { const stateDir = tempStateDir(); try { diff --git a/packages/react-native/src/metro/metro-session-hints.ts b/packages/react-native/src/metro/metro-session-hints.ts index 053758ea77..49bc6cd449 100644 --- a/packages/react-native/src/metro/metro-session-hints.ts +++ b/packages/react-native/src/metro/metro-session-hints.ts @@ -277,10 +277,10 @@ function recordOpenedBinding( } /** - * Records an open that bound no address. What is left is the app this open launched: a later reload - * looks that app's own dev-server address up from it. A reused session can open a different app, so a - * recorded app always replaces the previous one and keeps the address the session already had. An open - * that reports no app leaves a reused session's record alone and clears a stale one on a fresh session. + * Records an open that bound no address. A fresh session keeps nothing a previous one left behind: an + * address bound by an earlier run belongs to the project that bound it, so a flagless open of a + * different project must not inherit it, and the record holds only the app this open launched. A + * reused session keeps the address it bound, and only swaps the app, which may be another one. */ function recordOpenedApp( scope: MetroSessionScope, @@ -292,17 +292,31 @@ function recordOpenedApp( if (!sessionReused) clearMetroSessionHints(scope); return; } - writeMetroSessionHints({ ...scope, hints: { ...bindingFields(stored), app } }); + writeMetroSessionHints({ + ...scope, + hints: { ...(sessionReused ? bindingFields(stored) : {}), app }, + }); } -/** The address fields of a stored record, apart from the app recorded beside them. */ +/** + * The address fields of a stored record, apart from the app recorded beside them. A record written + * before the control address existed names its address as runtime hints instead, so the projection + * resolves those to the same field the reader reads: one field set, never a binding that only one of + * the two understands. + */ function bindingFields(stored: MetroSessionRecord | undefined): MetroSessionHints { + const controlBaseUrl = stored?.controlBaseUrl ?? storedBindingUrl(stored); return { - ...(stored?.controlBaseUrl ? { controlBaseUrl: stored.controlBaseUrl } : {}), + ...(controlBaseUrl ? { controlBaseUrl } : {}), ...(stored?.deviceBaseUrls ? { deviceBaseUrls: stored.deviceBaseUrls } : {}), }; } +function storedBindingUrl(stored: MetroSessionRecord | undefined): string | undefined { + if (!stored || !hasStoredRuntimeHints(stored.raw)) return undefined; + return resolveMetroServerUrl({ runtime: readStoredRuntimeHints(stored.raw) }).toString(); +} + /** * Keeps the host trait an earlier open proved for the same device. An open that resolves the device * from the session rather than from an inventory reports nothing about where it runs, and that silence From ab36cf14f88df7e6164f9d231efba797e7eb7c6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 12:37:19 +0100 Subject: [PATCH 06/10] test(metro): pin that an unproven open keeps the host trait proved earlier An open whose device selection says nothing about where the device runs must leave the trait an earlier open proved for that device in place, and must not carry it over to a different device. --- .../src/metro/metro-session-hints.test.ts | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/packages/react-native/src/metro/metro-session-hints.test.ts b/packages/react-native/src/metro/metro-session-hints.test.ts index 87d74237d8..2c9e583995 100644 --- a/packages/react-native/src/metro/metro-session-hints.test.ts +++ b/packages/react-native/src/metro/metro-session-hints.test.ts @@ -307,6 +307,46 @@ test('an open that reports no app leaves a reused session record alone and clear } }); +test('an open that proves nothing about the device keeps what an earlier open proved', () => { + const stateDir = tempStateDir(); + try { + const options = { stateDir, session: 'proven', host: hostFor(stateDir) }; + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: false, + app: iosApp, + }); + // A later open that resolves the device from the session reports nothing about where it runs, so + // it must not erase the proof the first one gave for the same device. + const { hostedLocally: _dropped, ...unproven } = iosApp; + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: true, + app: { ...unproven, appId: 'com.other.app' }, + }); + assert.deepEqual(readMetroSessionAppTarget({ ...options }), { + ...iosApp, + appId: 'com.other.app', + }); + + // Another device is a different question: nothing is proven for it, so nothing is inherited. + recordOpenedMetroSession(options, { + runtime: undefined, + explicitRuntime: false, + sessionReused: true, + app: { ...unproven, deviceId: 'UDID-2' }, + }); + assert.deepEqual(readMetroSessionAppTarget({ ...options }), { + ...unproven, + deviceId: 'UDID-2', + }); + } finally { + rmSync(stateDir, { recursive: true, force: true }); + } +}); + test('the recorded app is read back only when its record names a real app on a device', () => { const stateDir = tempStateDir(); const options = { stateDir, session: 'stored', host: hostFor(stateDir) }; From 8c928809bccc4e02776c8410ff897a5fe8735994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 12:39:14 +0100 Subject: [PATCH 07/10] test(metro): run reloadMetro's discovery branch from the module that owns it The four reload cases went through the package entry, so nothing said which module pinned them. They call reloadMetro directly now, beside client-metro.ts, which holds the host branch that decides whether local discovery runs at all. --- .../client-metro-reload-local-discovery.test.ts} | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) rename packages/react-native/src/{index-metro-reload-local-discovery.test.ts => metro/client-metro-reload-local-discovery.test.ts} (92%) diff --git a/packages/react-native/src/index-metro-reload-local-discovery.test.ts b/packages/react-native/src/metro/client-metro-reload-local-discovery.test.ts similarity index 92% rename from packages/react-native/src/index-metro-reload-local-discovery.test.ts rename to packages/react-native/src/metro/client-metro-reload-local-discovery.test.ts index 8f7e326b41..0c4a03c117 100644 --- a/packages/react-native/src/index-metro-reload-local-discovery.test.ts +++ b/packages/react-native/src/metro/client-metro-reload-local-discovery.test.ts @@ -3,14 +3,14 @@ import assert from 'node:assert/strict'; import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; import { createServer } from 'node:http'; import path from 'node:path'; -import { reloadMetro } from './index.ts'; +import { reloadMetro } from './client-metro.ts'; import { AppError } from '@agent-device/kernel/errors'; import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; -import type { MetroAppTarget } from './metro/metro-dev-server-discovery.ts'; +import type { MetroAppTarget } from './metro-dev-server-discovery.ts'; -// These run the whole local reload path against a loopback dev server: the session record's app, the -// host's listening ports, the real `/status` probe, and the real reload call. Only the port listing is -// answered from a table, so a test does not sweep whatever else this machine listens on. +// These run `reloadMetro`'s local-discovery branch against a loopback dev server: the session's app, +// the host's listening ports, the real `/status` probe, and the real reload call. Only the port listing +// is answered from a table, so a test sweeps its own ports and never a real Metro. const portListing = vi.hoisted(() => ({ ports: [] as number[] })); From c6854341c396b0ca69615601eacd2e3d36072da5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 12:42:37 +0100 Subject: [PATCH 08/10] style(metro): format the discovery tests and use replaceAll Co-Authored-By: Claude Opus 5.5 --- .../src/metro/metro-dev-server-discovery-host-io.test.ts | 3 ++- .../react-native/src/metro/metro-dev-server-discovery.test.ts | 4 ++-- .../react-native/src/metro/metro-dev-server-parsing.test.ts | 4 +++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts index 6d98294b02..0cd9705ce5 100644 --- a/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts @@ -150,7 +150,8 @@ test('ports fall back to netstat on a host without lsof', async () => { spawned.push(command); if (command === 'lsof') return Promise.reject(new Error('lsof ENOENT')); return Promise.resolve({ - stdout: 'tcp4 0 0 127.0.0.1.8081 *.* LISTEN\ntcp6 0 0 ::1.8096 *.* LISTEN\ntcp4 0 0 127.0.0.1.9999 *.* ESTABLISHED\n', + stdout: + 'tcp4 0 0 127.0.0.1.8081 *.* LISTEN\ntcp6 0 0 ::1.8096 *.* LISTEN\ntcp4 0 0 127.0.0.1.9999 *.* ESTABLISHED\n', stderr: '', exitCode: 0, }); diff --git a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts index 67c00a22e4..d7eb94cf7d 100644 --- a/packages/react-native/src/metro/metro-dev-server-discovery.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts @@ -48,7 +48,7 @@ function probeReturning( recorded.portsRead += 1; return servers.map((server) => ({ // What a host lister names: an IPv6 address arrives without URL brackets. - host: server.serverUrl.hostname.replace(/[[\]]/g, ''), + host: server.serverUrl.hostname.replaceAll(/[[\]]/g, ''), port: Number(server.serverUrl.port), })); }, @@ -173,7 +173,7 @@ test('an app-reported address off this host is confirmed the same way as one on assert.equal(resolved.serverUrl.origin, 'http://10.0.0.5:19000'); }); -test("an app-reported address off this host is refused when its server serves another project", async () => { +test('an app-reported address off this host is refused when its server serves another project', async () => { const probe = probeReturning([serverAtHost('10.0.0.5', 19000, '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/other/project')]); await assert.rejects( () => diff --git a/packages/react-native/src/metro/metro-dev-server-parsing.test.ts b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts index 85f3354d39..045fe0199b 100644 --- a/packages/react-native/src/metro/metro-dev-server-parsing.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts @@ -45,7 +45,9 @@ test('lsof field output yields each listening socket once, ordered by port', () test('lsof keeps the address family it reports, brackets and all', () => { // Metro bound to IPv6 loopback only is unreachable on 127.0.0.1, so this is the address it must be // dialled at; a wildcard listener is kept as loopback, which reaches every address of this host. - const sockets = parseLsofListeningSockets('n[::1]:8096\nn127.0.0.1:8096\nn*:8097\nn[2001:db8::1]:8098\n'); + const sockets = parseLsofListeningSockets( + 'n[::1]:8096\nn127.0.0.1:8096\nn*:8097\nn[2001:db8::1]:8098\n', + ); assert.deepEqual(sockets, [ { host: '127.0.0.1', port: 8096 }, { host: '::1', port: 8096 }, From 3b46e85bb9fb879e4f77daab2aebcf76e63644cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 12:57:15 +0100 Subject: [PATCH 09/10] fix(metro): skip zone-scoped IPv6 listeners in the port sweep A scoped address like fe80::1%en0 is not dialable by new URL; one such listener threw a raw TypeError that aborted the whole sweep. Co-Authored-By: Claude Opus 5.5 --- .../src/metro/metro-dev-server-parsing.test.ts | 8 ++++++++ .../react-native/src/metro/metro-dev-server-parsing.ts | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/react-native/src/metro/metro-dev-server-parsing.test.ts b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts index 045fe0199b..7fd80c5bfa 100644 --- a/packages/react-native/src/metro/metro-dev-server-parsing.test.ts +++ b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts @@ -42,6 +42,14 @@ test('lsof field output yields each listening socket once, ordered by port', () ); }); +test('a zone-scoped IPv6 listener is skipped, not dialled', () => { + const sockets = parseLsofListeningSockets( + 'n[fe80::1%en0]:7000\nnfe80:1::1%en0:7001\nn127.0.0.1:8081\n', + ); + assert.deepEqual(sockets, [{ host: '127.0.0.1', port: 8081 }]); + assert.doesNotThrow(() => sockets.map((socket) => socketUrl(socket))); +}); + test('lsof keeps the address family it reports, brackets and all', () => { // Metro bound to IPv6 loopback only is unreachable on 127.0.0.1, so this is the address it must be // dialled at; a wildcard listener is kept as loopback, which reaches every address of this host. diff --git a/packages/react-native/src/metro/metro-dev-server-parsing.ts b/packages/react-native/src/metro/metro-dev-server-parsing.ts index 186a71719b..bb9eb12233 100644 --- a/packages/react-native/src/metro/metro-dev-server-parsing.ts +++ b/packages/react-native/src/metro/metro-dev-server-parsing.ts @@ -106,8 +106,9 @@ function parseListeningSocket(address: string): ListeningSocket | undefined { } function namedSocket(host: string, port: number | undefined): ListeningSocket | undefined { - // A host left holding a bracket came from a name that is not an address at all. - if (!host || port === undefined || host.includes('[') || host.includes(']')) return undefined; + // A host left holding a bracket came from a name that is not an address at all, and a zone-scoped + // one (`fe80::1%en0`) is no address `new URL` can dial. + if (!host || port === undefined || /[[\]%]/.test(host)) return undefined; return { host: WILDCARD_HOSTS.has(host) ? LOOPBACK_HOST : host, port }; } From c7290dc596ddfacae2827b9a43c582d493801ae0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 14:10:42 +0100 Subject: [PATCH 10/10] test(client): pin the host trait an open records for each device source Nothing covered the device-selection mapping through open, and it decides whether a later flagless reload may read this machine's simulator containers and listening ports at all. --- .../index-metro-open-hosted-locally.test.ts | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 packages/client/src/__tests__/index-metro-open-hosted-locally.test.ts diff --git a/packages/client/src/__tests__/index-metro-open-hosted-locally.test.ts b/packages/client/src/__tests__/index-metro-open-hosted-locally.test.ts new file mode 100644 index 0000000000..12bb8ccd78 --- /dev/null +++ b/packages/client/src/__tests__/index-metro-open-hosted-locally.test.ts @@ -0,0 +1,90 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { createAgentDeviceClient } from '../index.ts'; +import { createClientTransport, mkdtempForTestSync } from '@agent-device/test-kit'; + +// `open` records where the session's device runs, and that is what lets a later flagless +// `metro reload` read this machine's simulator containers and listening ports at all. These pin the +// mapping from the daemon's device-selection answer to that trait, through the real open path. + +type RecordedApp = { + platform: string; + deviceId: string; + appId: string; + hostedLocally?: boolean; +}; + +/** An `open` answered by a local daemon, as the given device-selection metadata reports it. */ +async function openWith(selection: unknown): Promise<{ stateDir: string; app: RecordedApp }> { + const stateDir = mkdtempForTestSync('agent-device-client-open-host-'); + const setup = createClientTransport(async () => ({ + ok: true, + data: { + session: 'qa', + platform: 'ios', + id: 'UDID-1', + device: 'iPhone Air', + kind: 'simulator', + appBundleId: 'com.example.app', + ...(selection === undefined ? {} : { selection }), + }, + })); + const client = createAgentDeviceClient( + { ...setup.config, stateDir, daemonBaseUrl: 'http://127.0.0.1:1' }, + { transport: setup.transport, host: { env: {}, cwd: stateDir } }, + ); + + await client.apps.open({ app: 'com.example.app', platform: 'ios' }); + + const record = JSON.parse( + fs.readFileSync(path.join(stateDir, 'metro-sessions', 'qa.json'), 'utf8'), + ) as { app?: RecordedApp }; + assert.ok(record.app, 'open records the app a later reload looks the dev server up from'); + return { stateDir, app: record.app }; +} + +function selectionWith(source: string) { + return { reason: 'single-booted-local', source, candidateCount: 1, bootOccurred: false }; +} + +test('an open that resolved the device locally records it as hosted here', async () => { + const { stateDir, app } = await openWith(selectionWith('local')); + try { + assert.equal(app.hostedLocally, true); + assert.equal(app.deviceId, 'UDID-1'); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } +}); + +test('an open of a provider device records it as not hosted here', async () => { + const { stateDir, app } = await openWith(selectionWith('provider')); + try { + // A provider's device can be anywhere, so a reload may not read this machine's state for it. + assert.equal(app.hostedLocally, false); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } +}); + +test('an open that says nothing about the device records no host trait at all', async () => { + // `session` means the device was carried over from an earlier request: that says nothing about where + // it runs, so it must stay unproven rather than claim either way. + const { stateDir, app } = await openWith(selectionWith('session')); + try { + assert.equal('hostedLocally' in app, false); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } +}); + +test('an open response without a selection block records no host trait either', async () => { + const { stateDir, app } = await openWith(undefined); + try { + assert.equal('hostedLocally' in app, false); + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }); + } +});