Skip to content

fix(metro): reload the app's own dev server instead of assuming port 8081 - #5098

Merged
thymikee merged 10 commits into
mainfrom
fix/metro-reload-discover-dev-server
Nov 25, 2026
Merged

thymikee merged 10 commits into
mainfrom
fix/metro-reload-discover-dev-server

Conversation

@thymikee

@thymikee thymikee commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Summary

A flagless metro reload resolved localhost:8081 whenever the session had bound no dev server. That port is another project's, so reload acted on the wrong app or failed as fetch failed.

Reload now resolves in order: the binding (--metro-host/--metro-port/--bundle-url, or what metro prepare or open bound); what the app reports (RCT_jsLocation, iOS simulator only, confirmed by one bounded /status read); then a sweep of ports a local process listens on, for a dev server whose X-React-Native-Project-Root is this directory or a parent or child of it. A server naming another project is never used. With no signal it fails typed: metro_dev_server_unresolved.

Both lookups are gated on one trait open records: the daemon answers on loopback and named the device from its own inventory. Any device attached to this machine, a physical device included, gets the port sweep; only the preferences read is iOS-simulator only. A provider or inherited device, or an app-less session, keeps the old default.

Before / after

Metro on 8096, no flags: fetch failed → reloadUrl: http://127.0.0.1:8096/reload.
No server for this project: localhost:8081 → typed failure.

Validation

Head c7290dc596; CI owns the gate. Live two-server transcript: stand-in servers on 8083/projA and 8082/projB; flagless reload from each directory reloaded only its own, on iPhone Air and an Android emulator, server logs as evidence. Also live: the typed failure from an unserved project; an app-reported address refused from one project and accepted from the other, loopback and LAN; a [::1]-only server.


Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

View guided diff Turn on auto-fix

…8081

A flagless metro reload resolved localhost:8081 whenever the session had bound no
dev server, which reloaded whichever project owned that port, or failed as a bare
fetch error. It now resolves in order: the session or explicit binding, the address
the app itself stored (RCT_jsLocation in an iOS simulator's preferences), then a
local dev server whose X-React-Native-Project-Root matches this directory. When
nothing resolves, it fails with details.reason metro_dev_server_unresolved naming
the address the fallback would have used. Only a session whose app runs on a local
simulator or emulator runs the lookups; a remote or physical device keeps the
previous default. Sessions that bind no address now record the app they opened so
the reload has something to look that app's address up from.
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.60 MB 6.59 MB -10.9 kB
Package (unpacked) 6.60 MB 6.59 MB -10.9 kB
Package (download) 2.01 MB 2.01 MB -2.4 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 25.7 ms 22.4 ms -3.2 ms
CLI --help 53.2 ms 47.8 ms -5.5 ms

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 12 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread website/docs/docs/commands.md Resolved
@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 21ef0b3. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

At 21ef0b3, flagless metro reload can fail for a provider-hosted simulator or emulator that reloaded before, and the two-server case is not yet shown live.

A provider-hosted iOS simulator or Android emulator driven by a local daemon still reports kind simulator or emulator, so discovery treats it as local. It reads this host's simulator data and ports, and throws metro_dev_server_unresolved when no local Metro has an overlapping root. Before this change, the same command called localhost:8081, and the new help text says provider-hosted devices keep that default. Local lookups should run only when the session device's provider or target declares that it is hosted on this machine, and that fact should be recorded with the app at open. If the current behavior is intended, please remove the provider-hosted claim from help and docs.

The reload route changed, but the live run in the description uses only one dev server on 8096. The rule that another project's server is never reloaded is covered only by unit tests with injected probes. Before merge, a live transcript is required with project B's Metro on 8081, the session app's project A on 8096, and a session opened without Metro flags. On an iOS simulator with no stored RCT_jsLocation, flagless reload from A's directory must return reloaded: true with reloadUrl http://127.0.0.1:8096/reload, and B's app must not reload. The same command from an unrelated directory must return details.reason metro_dev_server_unresolved. One Android emulator run of the first case is also needed, to cover the local project root route.

Not blocking: these can be taken or left: use one loopback predicate because the local list and isLoopbackHostname disagree on 0.0.0.0 and 127.0.0.2; read the app-reported address from the custom simulator device set when the session uses one; name the working directory requirement (or --metro-port) in the hint or help, since a local simulator with one Metro on 8081 and no stored address now fails from outside the project; avoid the second stored copy of the session app and the repeated binding precedence, as in the question below; and add one client-level test where open records an app-only hint and flagless reload resolves the matching server and refuses a foreign root.

Could the reload keep resolveMetroReloadServerUrl as the single owner but read the current app, device id, device set and a daemon-declared "hosted on this machine" fact from one session status read? The hints file would then stay binding-only (about 100 lines less), a reused session would always reflect its current app, and resolveMetroServerUrl returning undefined when nothing is bound could replace isMetroTargetBound. Discovery could also apply the same root-overlap refusal to the app-reported probe and use the shared loopback predicate. This first needs the daemon open or status response to expose whether the device is provider-hosted, which would replace both the daemon URL check and the device kind check.

These open threads still apply: stale loopback address and reused session app, which both break the rule above and need a fix, plus port candidate limit, empty Metro port, loose port parsing, missing lsof fallback, Windows path separators and docs failure claim. Two lower-priority threads also still apply. This thread does not apply and can be resolved: the local client path always passes the host, and the route without a host is the deliberate remote-daemon exception in the description.

The Coverage check fails, likely because of this change: no test exercises the new branches in packages/client/src/index.ts, the app-only record in metro-session-hints.ts or the host branch in client-metro.ts. The two cancelled body-rule runs were superseded and do not involve this code.

Not verified here: the tests and the live route were not run, and the live run in the description has no transcript. A full provider-hosted open was not traced end to end to confirm that its response carries that device kind and the app id. It was also not checked whether every remote configuration sets a daemon URL before the client is created; if neither the option nor the environment variable is set, the route would be treated as local.

Before merge, the provider-hosted case, the two threads that break the rule, and the Coverage failure need fixes, and the live two-server run is required.

thymikee and others added 3 commits November 25, 2026 11:29
…ed server

Splits the pure reads out of dev-server discovery — lsof and netstat port
tables, the app's stored preferences, the project-root header, host:port, and
root overlap — so each branch is tested without a process or a socket, and the
I/O wrappers stay thin. Gates local lookups on the app being recorded as hosted
here, refuses an app-reported server whose root names another project, batches
port probes instead of dropping ports past the 32nd, falls back to netstat where
lsof is missing, treats a blank metroPort as no binding, and replaces the
recorded app on every open.

Co-authored-by: Apex <noreply@callstack.com>
… host reads

Records where a session's device runs when open resolves it, instead of
second-guessing the device kind: the trait is true when the daemon answering is
local and it named the device from its own inventory, false for a provider
device, and left out when the answer says nothing, so a later open keeps what an
earlier one proved for the same device. A physical device on this machine is now
in scope and a provider device on a simulator is not, which is what the host
actually is. Shares one loopback test with the daemon's own and drops the
half-baked URL check that read 127.1.2.3 as remote.

A live Mac answers lsof in over 1.5s with simulators running — measured, not
guessed — so the port listing went empty on a real reload. The host-read budget
now covers the slow machine, because a timeout there is indistinguishable from
"this machine listens on nothing".

Co-authored-by: Apex <noreply@callstack.com>
…corder

Un-exports the four parsers no caller outside the module reads — the status
literal, the netstat address port, host:port, and the JSON-object read — which
the tests already cover through the parsers that call them, and splits what
`open` records into the binding path and the app path, so neither branch carries
the other's conditions. Renames the two unit tests that were named for no module
beside them: the reload walkthrough is a package-entry test, the host reads
belong to the module whose I/O wrappers they pin.

Co-authored-by: Apex <noreply@callstack.com>
@thymikee

Copy link
Copy Markdown
Member Author

Live two-server check: metro reload from each project reloads only its own

Two stand-in Metro dev servers on one machine, one per project. Each answers /status the way the React Native CLI's statusPageMiddleware does (X-React-Native-Project-Root + packager-status:running) and appends every /reload it receives to its own log file. The logs are the evidence; nothing here is asserted from internals.

Both listen on non-default ports, so the old localhost:8081 default can never look like a pass:

Port X-React-Native-Project-Root Log
8083 /tmp/metro-fake/projA a.log
8082 /tmp/metro-fake/projB b.log

CLI built from this branch (0.21.43-dev), its own AGENT_DEVICE_STATE_DIR, and no --metro-host/--metro-port/--bundle-url on any reload call — the working directory is the only thing that changes between calls.

iOS Simulator — iPhone Air, iOS 27.0 (1B89356B-961C-4993-B0BE-4C0F3917D995)

$ cd /tmp/metro-fake/projA && agent-device open com.callstack.agentdevicelab --platform ios --udid 1B89…D995 --session twoserver
Opened: com.callstack.agentdevicelab
Session state: /tmp/metro-fake/state/sessions/twoserver

$ cat /tmp/metro-fake/state/metro-sessions/twoserver.json     # what open recorded
{
  "app": {
    "platform": "ios",
    "deviceId": "1B89356B-961C-4993-B0BE-4C0F3917D995",
    "deviceKind": "simulator",
    "appId": "com.callstack.agentdevicelab",
    "hostedLocally": true
  }
}

$ cd /tmp/metro-fake/projA && agent-device --platform ios --udid 1B89…D995 --session twoserver metro reload
Reloaded React Native apps via http://127.0.0.1:8083/reload
   -> a.log: RELOAD project=/tmp/metro-fake/projA at=2026-11-25T10:52:17.202Z
   -> b.log: (nothing)

$ cd /tmp/metro-fake/projB && agent-device --platform ios --udid 1B89…D995 --session twoserver metro reload
Reloaded React Native apps via http://127.0.0.1:8082/reload
   -> a.log: (unchanged)
   -> b.log: RELOAD project=/tmp/metro-fake/projB at=2026-11-25T10:52:20.611Z

Android emulator — focus-order-probe-api37, Android 17.0 (emulator-5560, started for this check)

Same two servers, same two directories, same flagless calls. Local discovery works on Android, so this platform is not a docs exception:

$ cd /tmp/metro-fake/projA && agent-device open com.callstack.agentdevicelab --platform android --serial emulator-5560 --session twoserver-android
Opened: com.callstack.agentdevicelab
$ cat …/metro-sessions/twoserver-android.json
{ "app": { "platform": "android", "deviceId": "emulator-5560", "deviceKind": "emulator",
           "appId": "com.callstack.agentdevicelab", "hostedLocally": true } }

$ cd /tmp/metro-fake/projA && agent-device --platform android --serial emulator-5560 --session twoserver-android metro reload
Reloaded React Native apps via http://127.0.0.1:8083/reload
   -> a.log: RELOAD project=/tmp/metro-fake/projA at=2026-11-25T10:52:23.789Z

$ cd /tmp/metro-fake/projB && agent-device --platform android --serial emulator-5560 --session twoserver-android metro reload
Reloaded React Native apps via http://127.0.0.1:8082/reload
   -> b.log: RELOAD project=/tmp/metro-fake/projB at=2026-11-25T10:52:26.601Z

What is iOS-only is the app-reported address step (RCT_jsLocation read from the app's preferences file): an Android app's stored address is not readable this way, so Android goes straight to the port sweep. CLI help and website/docs/docs/commands.md name an iOS simulator for that step only, and put no platform limit on the port sweep.

Both logs, after all four calls

$ cat a.log                              # port 8083, project A
LISTENING 8083 for /tmp/metro-fake/projA
RELOAD project=/tmp/metro-fake/projA at=2026-11-25T10:52:17.202Z   # iOS,  from projA
RELOAD project=/tmp/metro-fake/projA at=2026-11-25T10:52:23.789Z   # android, from projA

$ cat b.log                              # port 8082, project B
LISTENING 8082 for /tmp/metro-fake/projB
RELOAD project=/tmp/metro-fake/projB at=2026-11-25T10:52:20.611Z   # iOS,  from projB
RELOAD project=/tmp/metro-fake/projB at=2026-11-25T10:52:26.601Z   # android, from projB

Each server was called exactly once per platform, by the project it serves. No call reached localhost:8081, and no call reloaded a server reporting an unrelated project root.

The two guards, observed on the same pair of servers

A project no server serves fails typed instead of calling the default port. From a third project directory, with both servers running and the session's app recorded as local:

$ cd /tmp/metro-fake/projC && agent-device --platform ios --udid 1B89…D995 --session twoserver metro reload
Error (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
http://localhost:8081. Next: Pass --metro-port <port> …

Neither log gained a RELOAD line.

An app-reported address is refused when its server serves another project. RCT_jsLocation in the app's container was set to localhost:8082 — projB's live server — while reload ran from projA:

$ plutil -replace RCT_jsLocation -string "localhost:8082" …/com.callstack.agentdevicelab.plist
$ cd /tmp/metro-fake/projA && agent-device --platform ios --udid 1B89…D995 --session twoserver metro reload
Reloaded React Native apps via http://127.0.0.1:8083/reload     # projA's server, by port sweep
   -> b.log: (no new line — the app's own address was probed and refused, not reloaded)

$ cd /tmp/metro-fake/projB && agent-device --platform ios --udid 1B89…D995 --session twoserver metro reload
Reloaded React Native apps via http://localhost:8082/reload     # same address, now accepted
   -> b.log: RELOAD project=/tmp/metro-fake/projB at=2026-11-25T10:52:49.246Z

One address, two working directories, two verdicts — the project root the server reports decides it, not the address itself. (The simulator's preference was removed again afterwards.)

One thing the unit tests could not tell me

The first two live runs failed with metro_dev_server_unresolved while the right server was listening. lsof -nP -iTCP -sTCP:LISTEN -Fn needs over 1.5 s on this Mac with simulators running (/usr/bin/time: 1.54 s, 1.26 s, 1.17 s), and the port-listing budget was exactly 1.5 s — so the host answered "this machine listens on nothing". Every transcript line above exists only after HOST_READ_TIMEOUT_MS went to 4 s in 07a0b60. A timeout on that read is indistinguishable from an empty port list, so no port-table test could have caught it: the mock always answers instantly.

The stand-in server used for this check
// answers /status like the RN CLI's statusPageMiddleware; logs every /reload
import { createServer } from 'node:http';
import fs from 'node:fs';
const [port, projectRoot, logPath] = process.argv.slice(2);
createServer((req, res) => {
  const url = new URL(req.url, `http://127.0.0.1:${port}`);
  if (url.pathname === '/status') {
    res.setHeader('X-React-Native-Project-Root', projectRoot);
    res.end('packager-status:running');
    return;
  }
  if (url.pathname === '/reload') {
    fs.appendFileSync(logPath, `RELOAD project=${projectRoot} at=${new Date().toISOString()}\n`);
    res.end(`RELOADED ${projectRoot}`);
    return;
  }
  res.statusCode = 404; res.end('not found');
}).listen(Number(port), '127.0.0.1');

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 4 new findings on 38300d4. The verdict and the full list are in the summary comment.

Comment thread packages/client/src/index.ts Resolved
thymikee and others added 4 commits November 25, 2026 12:36
…host named

A flagless fresh open no longer inherits a binding a previous run left under
the same session name: that address belongs to the project that bound it. A
reused session keeps its address, including one stored as runtime hints before
the control address existed, so rewriting the record never drops a binding.

The app-reported address is now confirmed wherever it points, so a LAN host
left by `open --metro-host` is refused when its server serves another project.
Listening sockets keep the address the host reported, so a dev server bound to
IPv6 loopback only is dialled at `[::1]` instead of being missed on 127.0.0.1.
…rlier

An open whose device selection says nothing about where the device runs must
leave the trait an earlier open proved for that device in place, and must not
carry it over to a different device.
…owns it

The four reload cases went through the package entry, so nothing said which
module pinned them. They call reloadMetro directly now, beside client-metro.ts,
which holds the host branch that decides whether local discovery runs at all.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on c685434. The verdict and the full list are in the summary comment.

A scoped address like fe80::1%en0 is not dialable by new URL; one such
listener threw a raw TypeError that aborted the whole sweep.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

This PR is ready at 3b46e85: the blocking points from the earlier review at 21ef0b3 are fixed, and nothing blocking remains.

Not blocking: these can be taken or left: add client tests that run apps.open with selection.source set to 'provider' and to 'local' and assert the recorded hostedLocally (or that a provider reload lists no ports), because no test covers that mapping through open, and update the PR body to say that physical devices attached to this machine now use the port sweep, with the Validation commit refreshed and the live transcript linked.

These open threads no longer apply and can be resolved: app-reported address check (fixed: the probe and root overlap check use that address); app record rewrite (fixed: every open rewrites the app); socket probe cap (fixed: all sockets are probed in batches of 32); blank Metro port (fixed: it counts as absent); SDK reload default (intended and now documented: without a host the pre-discovery default is kept, and the CLI passes a host for a local daemon); port value parsing (fixed: only digits are accepted); socket listing fallback (fixed: netstat is the fallback, and the list is empty with neither tool); path containment check (fixed: it uses path.relative and path.sep); docs failure scope (fixed: the failure is scoped to local devices and the default cases are named); help wording (fixed: help names the root relation and the working-directory requirement); reload discovery test (fixed: a test drives reloadMetro and asserts the URL and typed reason); port cap again (fixed by the same batching); reused session fields (fixed: binding fields are copied only for a reused session, and legacy runtime-hint fields are resolved); non-loopback root check (fixed: non-loopback hosts are checked too); IPv6 socket host (fixed: the host is kept and the URL has brackets); unproven local selection (no behavior problem: it already returned undefined, and an earlier proof is carried forward); zone-scoped host (fixed: such hosts are dropped before new URL).

CI is green: all 21 checks pass, including Coverage, which failed at 21ef0b3.

Not verified here: tests and the live route were not run, so CI and the author's live transcript are the evidence. Not verified here: real Metro on 8081 and 8096 at the reviewed commit, because that transcript used stand-in dev servers on 8082 and 8083 at 7351ef4 and ffc3f90, with only parser changes after it. Not verified here: a provider-hosted open was not run live, and its hostedLocally: false route was only traced in code. Not verified here: whether any provider deployment reports devices that run on this machine as inventory in discovery was not checked; such devices would keep the default address, as documented.

Nothing else needs to happen before merge; both notes above can be follow-ups.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 25, 2026
Nothing covered the device-selection mapping through open, and it decides
whether a later flagless reload may read this machine's simulator containers
and listening ports at all.
@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of c7290dc

Since the review of 3b46e85: 0 new · 0 still open · 0 no longer raised

No open findings.

Reviewed with this repository's own Sentinel configuration (f1c5f3dc3ed1).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

@thymikee thymikee removed the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 25, 2026
@thymikee

Copy link
Copy Markdown
Member Author

No code problems were found at c7290dc. The only change since the earlier review of 3b46e85, which also found none, is a new client test, and the production code is identical.

None of the earlier inline threads still applies, so they can be resolved. Fixed: the app-reported address is now probed and checked against the project root; each open now rewrites the recorded app; all sockets are now probed in batches; a blank Metro port now counts as absent; port parsing now requires digits only; socket listing now falls back and can return an empty list; path containment now uses proper path handling; the command docs now scope the failure to local devices; the help text now states the root and working-directory rules; a client reload test now covers this; batched probing removes the port cap; binding fields are now copied only for a reused session; non-loopback hosts are now checked too; IPv6 hosts are now kept and bracketed; zone-scoped hosts are now dropped before URL parsing. No change needed: the SDK default without a host is intentional and documented; an unproven local selection already returned no host.

All 22 reported checks pass, and the required evidence is in place. Not verified here: tests were not run locally, so passing CI is the test evidence. No live run was done on this commit, and a provider-hosted open has never been run live. The thread statuses are based on the earlier code trace and the test-only change since then.

Nothing from this review needs to change before merge.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 25, 2026
@thymikee
thymikee merged commit 24f8181 into main Nov 25, 2026
22 checks passed
@thymikee
thymikee deleted the fix/metro-reload-discover-dev-server branch November 25, 2026 15:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant