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 }); + } +}); 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 3690984da2..487686acc8 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, @@ -63,8 +64,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 +119,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 +343,23 @@ 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; + 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, + appHostedLocally(config, host, selection), + ), }, ); - const device = normalizeOpenDevice(data); - const appBundleId = readOptionalString(data, 'appBundleId'); - const appId = appBundleId; return { session, ...readScriptDeliveryDisclosure(data), @@ -357,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, @@ -428,15 +441,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 +588,54 @@ 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); +} + +/** + * 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, + host: HostEnvironment, + selection: DeviceSelectionMetadata | undefined, +): boolean | undefined { + if (!daemonIsLocal(config, host)) return false; + if (selection?.source === 'local') return true; + if (selection?.source === 'provider') return false; + return undefined; +} + +/** + * 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, + hostedLocally: boolean | 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, + ...(hostedLocally === undefined ? {} : { hostedLocally }), + }; +} + 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..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 (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 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/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-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/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-reload-local-discovery.test.ts b/packages/react-native/src/metro/client-metro-reload-local-discovery.test.ts new file mode 100644 index 0000000000..0c4a03c117 --- /dev/null +++ b/packages/react-native/src/metro/client-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 './client-metro.ts'; +import { AppError } from '@agent-device/kernel/errors'; +import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import type { MetroAppTarget } from './metro-dev-server-discovery.ts'; + +// 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[] })); + +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 910806576d..7790b69585 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,29 @@ 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({ + 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-host-io.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts new file mode 100644 index 0000000000..0cd9705ce5 --- /dev/null +++ b/packages/react-native/src/metro/metro-dev-server-discovery-host-io.test.ts @@ -0,0 +1,254 @@ +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 { + listLocalListeningSockets, + probeMetroServerStatus, + 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 sockets = await withCommandExecutorOverride( + (command) => { + spawned.push(command); + return Promise.resolve({ + stdout: command === 'lsof' ? 'p1\nn127.0.0.1:8081\nn[::1]:8096\n' : '', + stderr: '', + exitCode: 0, + }); + }, + async () => await listLocalListeningSockets(), + ); + 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 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\ntcp6 0 0 ::1.8096 *.* LISTEN\ntcp4 0 0 127.0.0.1.9999 *.* ESTABLISHED\n', + stderr: '', + exitCode: 0, + }); + }, + async () => await listLocalListeningSockets(), + ); + 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 sockets = await withCommandExecutorOverride( + (command) => Promise.reject(new Error(`${command} ENOENT`)), + async () => await listLocalListeningSockets(), + ); + assert.deepEqual(sockets, []); +}); + +test('a tool that answers with an empty success still lets the other tool answer', async () => { + const sockets = 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 listLocalListeningSockets(), + ); + 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 () => { + const server = answerStatusServer({ + body: 'packager-status:running', + projectRoot: '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/app/project', + }); + const port = await listenOnLoopback(server); + try { + 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 { + 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 probeMetroServerStatus(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 probeMetroServerStatus(new URL(`http://127.0.0.1:${notMetroPort}`), 2_000), + undefined, + ); + assert.equal( + 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 probeMetroServerStatus(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-discovery.test.ts b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts new file mode 100644 index 0000000000..d7eb94cf7d --- /dev/null +++ b/packages/react-native/src/metro/metro-dev-server-discovery.test.ts @@ -0,0 +1,368 @@ +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, + 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 { + 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://${bracketed}:${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: { + listListeningSockets: async () => { + recorded.portsRead += 1; + return servers.map((server) => ({ + // What a host lister names: an IPv6 address arrives without URL brackets. + host: server.serverUrl.hostname.replaceAll(/[[\]]/g, ''), + port: Number(server.serverUrl.port), + })); + }, + probeServer: async (url: URL) => byUrl.get(url.origin), + readAppReportedServerUrl: async () => { + recorded.appRead += 1; + return undefined; + }, + } satisfies MetroDevServerProbe, + }; +} + +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('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({ + 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-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 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'), + }, + }); + assert.equal(resolved.resolvedBy, 'app-reported'); + 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: { + 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'); + }, + 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, + app: simulatorApp, + probe: { + 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'), + }, + }); + 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'], + 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') + : 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'], + 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'], + listListeningSockets: 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'], + listListeningSockets: 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); + const lastPort = ports.at(-1)!; + let inFlight = 0; + let peakInFlight = 0; + const matching = await discoverLocalMetroServer({ + projectRoots: ['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/app/project'], + listListeningSockets: async () => ports.map((port) => ({ host: '127.0.0.1', port })), + probeServer: async (url: URL) => { + inFlight += 1; + peakInFlight = Math.max(peakInFlight, inFlight); + await Promise.resolve(); + inFlight -= 1; + 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(lastPort)); + 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( + () => 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('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 }, + undefined, + ]) { + const probe = probeReturning([serverAt(8096, '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/app/project')]); + 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 }); + } +}); + +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' }), true); + 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', () => { + 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..322b513d0f --- /dev/null +++ b/packages/react-native/src/metro/metro-dev-server-discovery.ts @@ -0,0 +1,351 @@ +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'; +import { + isMetroStatusBody, + parseAppReportedServerUrl, + parseLsofListeningSockets, + parseMetroProjectRootHeader, + parseNetstatListeningSockets, + projectRootsOverlap, + socketUrl, + type ListeningSocket, +} from './metro-dev-server-parsing.ts'; + +/** + * 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. */ +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 SIMULATOR_DEVICES_ROOT = 'Library/Developer/CoreSimulator/Devices'; +const METRO_PROJECT_ROOT_HEADER = 'x-react-native-project-root'; +// 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; + +/** The host reads a reload can make, injectable so the resolution order is testable without a host. */ +export type MetroDevServerProbe = Readonly<{ + /** 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. */ + 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, 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 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, +): Promise { + if (isMetroTargetBound(input)) { + return { serverUrl: resolveMetroServerUrl(input), resolvedBy: 'binding' }; + } + + const app = input.app; + 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 projectRoots = candidateProjectRoots([input.projectRoot ?? host.cwd, host.cwd]); + const reported = await (probe.readAppReportedServerUrl ?? readAppReportedMetroServerUrl)( + app, + 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 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, + listListeningSockets: probe.listListeningSockets ?? listLocalListeningSockets, + probeServer: probe.probeServer ?? probeMetroServerStatus, + }); + 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 app. It may, only when + * `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 { + return app?.hostedLocally === true; +} + +/** + * 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 { + 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 server that is gone, or one that names a different project, refuses it. + if (!running) return false; + return running.projectRoot === undefined || matchesProjectRoot(running, projectRoots); +} + +/** + * 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. + */ +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, + 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, + }).catch(() => undefined); + if (!result || result.exitCode !== 0) return undefined; + return result.stdout; +} + +/** + * 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). 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. + */ +export async function discoverLocalMetroServer( + input: Readonly<{ + projectRoots: string[]; + listListeningSockets: () => Promise; + probeServer: (serverUrl: URL, timeoutMs: number) => Promise; + probeTimeoutMs?: number; + }>, +): Promise { + const sockets = await input.listListeningSockets().catch(() => [] as ListeningSocket[]); + const timeoutMs = input.probeTimeoutMs ?? STATUS_PROBE_TIMEOUT_MS; + const servers = await probeListeningSockets(sockets, input.probeServer, timeoutMs); + const roots = candidateProjectRoots(input.projectRoots); + return servers.find((candidate) => matchesProjectRoot(candidate, roots)); +} + +/** + * 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 < sockets.length; start += MAX_CONCURRENT_STATUS_PROBES) { + const batch = sockets + .slice(start, start + MAX_CONCURRENT_STATUS_PROBES) + .map((socket) => probeServer(socketUrl(socket), 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); + } +} + +/** + * 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 listLocalListeningSockets(): Promise { + const lsof = await runHostCommand('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-Fn']); + if (lsof !== undefined) { + const sockets = parseLsofListeningSockets(lsof); + if (sockets.length > 0) return sockets; + } + const netstat = await runHostCommand('netstat', ['-an', '-p', 'tcp']); + return netstat === undefined ? [] : parseNetstatListeningSockets(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, + }).catch(() => undefined); + return result && result.exitCode === 0 ? result.stdout : undefined; +} + +/** One bounded `/status` read of an address: running dev server, plus its project root. */ +export async function probeMetroServerStatus( + 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 (!isMetroStatusBody(body)) return undefined; + const projectRoot = parseMetroProjectRootHeader( + 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 candidateProjectRoots(projectRoots: string[]): string[] { + const resolved = projectRoots.map((root) => normalizeRealPath(root)); + return [...new Set(resolved)]; +} + +function fileExists(filePath: string): boolean { + try { + fs.accessSync(filePath, fs.constants.F_OK); + return true; + } catch { + return false; + } +} 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..7fd80c5bfa --- /dev/null +++ b/packages/react-native/src/metro/metro-dev-server-parsing.test.ts @@ -0,0 +1,176 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { + isMetroStatusBody, + parseAppReportedServerUrl, + parseLsofListeningSockets, + parseMetroProjectRootHeader, + 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', () => { + 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'), + String.raw`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 socket once, ordered by port', () => { + assert.deepEqual( + 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('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. + 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(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 ordered', () => { + assert.deepEqual( + parseNetstatListeningSockets( + [ + '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'), + ), + [ + { host: '127.0.0.1', port: 8081 }, + { host: '::1', port: 8096 }, + ], + ); +}); + +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', () => { + 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..bb9eb12233 --- /dev/null +++ b/packages/react-native/src/metro/metro-dev-server-parsing.ts @@ -0,0 +1,188 @@ +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`. */ +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; + } +} + +/** + * 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 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 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 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') || columns[5] !== NETSTAT_LISTEN_STATE) return ''; + return columns[3] ?? ''; + }); +} + +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)); +} + +/** + * 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 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 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, 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 }; +} + +/** 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 + * 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. + */ +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; +} + +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 60691104e5..ef81a8ca1f 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,30 @@ 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 { + return ( + namesDevServer(input) || + trimRuntimeValue(input.runtime?.bundleUrl) !== undefined || + trimRuntimeValue(input.runtime?.metroHost) !== undefined || + 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. export function resolveMetroServerUrl(input: MetroReloadTargetInput): URL { const explicitBundleUrl = trimRuntimeValue(input.bundleUrl); @@ -58,7 +81,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.test.ts b/packages/react-native/src/metro/metro-session-hints.test.ts index 2b14e6b8a7..2c9e583995 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,265 @@ 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('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 { + 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('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) }; + 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 d9260cdbca..49bc6cd449 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,95 @@ 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 } : {}), + // 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 } : {}), + }; +} + +/** 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 +182,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,23 +235,99 @@ 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; }; +/** + * 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, ): 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; - writeMetroSessionHints({ ...scope, hints: { controlBaseUrl: url } }); - } else 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. 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, + sessionReused: boolean, + app: MetroAppTarget | undefined, + stored: MetroSessionRecord | undefined, +): void { + if (!app) { + if (!sessionReused) clearMetroSessionHints(scope); + return; + } + writeMetroSessionHints({ + ...scope, + hints: { ...(sessionReused ? bindingFields(stored) : {}), app }, + }); +} + +/** + * 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 { + ...(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 + * 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/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 16d33c8ffa..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, 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 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 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 |